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 "MCTargetDesc/RISCVMatInt.h" 16 #include "RISCV.h" 17 #include "RISCVMachineFunctionInfo.h" 18 #include "RISCVRegisterInfo.h" 19 #include "RISCVSubtarget.h" 20 #include "RISCVTargetMachine.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/MemoryLocation.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstrBuilder.h" 27 #include "llvm/CodeGen/MachineJumpTableInfo.h" 28 #include "llvm/CodeGen/MachineRegisterInfo.h" 29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 30 #include "llvm/CodeGen/ValueTypes.h" 31 #include "llvm/IR/DiagnosticInfo.h" 32 #include "llvm/IR/DiagnosticPrinter.h" 33 #include "llvm/IR/IRBuilder.h" 34 #include "llvm/IR/IntrinsicsRISCV.h" 35 #include "llvm/IR/PatternMatch.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/ErrorHandling.h" 38 #include "llvm/Support/KnownBits.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/raw_ostream.h" 41 42 using namespace llvm; 43 44 #define DEBUG_TYPE "riscv-lower" 45 46 STATISTIC(NumTailCalls, "Number of tail calls"); 47 48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 49 const RISCVSubtarget &STI) 50 : TargetLowering(TM), Subtarget(STI) { 51 52 if (Subtarget.isRV32E()) 53 report_fatal_error("Codegen not yet implemented for RV32E"); 54 55 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 56 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 57 58 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 59 !Subtarget.hasStdExtF()) { 60 errs() << "Hard-float 'f' ABI can't be used for a target that " 61 "doesn't support the F instruction set extension (ignoring " 62 "target-abi)\n"; 63 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 64 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 65 !Subtarget.hasStdExtD()) { 66 errs() << "Hard-float 'd' ABI can't be used for a target that " 67 "doesn't support the D instruction set extension (ignoring " 68 "target-abi)\n"; 69 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 70 } 71 72 switch (ABI) { 73 default: 74 report_fatal_error("Don't know how to lower this ABI"); 75 case RISCVABI::ABI_ILP32: 76 case RISCVABI::ABI_ILP32F: 77 case RISCVABI::ABI_ILP32D: 78 case RISCVABI::ABI_LP64: 79 case RISCVABI::ABI_LP64F: 80 case RISCVABI::ABI_LP64D: 81 break; 82 } 83 84 MVT XLenVT = Subtarget.getXLenVT(); 85 86 // Set up the register classes. 87 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 88 89 if (Subtarget.hasStdExtZfh()) 90 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass); 91 if (Subtarget.hasStdExtF()) 92 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 93 if (Subtarget.hasStdExtD()) 94 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 95 96 static const MVT::SimpleValueType BoolVecVTs[] = { 97 MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1, 98 MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1}; 99 static const MVT::SimpleValueType IntVecVTs[] = { 100 MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8, 101 MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16, 102 MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32, 103 MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64, 104 MVT::nxv4i64, MVT::nxv8i64}; 105 static const MVT::SimpleValueType F16VecVTs[] = { 106 MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16, 107 MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16}; 108 static const MVT::SimpleValueType F32VecVTs[] = { 109 MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32}; 110 static const MVT::SimpleValueType F64VecVTs[] = { 111 MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64}; 112 113 if (Subtarget.hasVInstructions()) { 114 auto addRegClassForRVV = [this](MVT VT) { 115 // Disable the smallest fractional LMUL types if ELEN is less than 116 // RVVBitsPerBlock. 117 unsigned MinElts = RISCV::RVVBitsPerBlock / Subtarget.getELEN(); 118 if (VT.getVectorMinNumElements() < MinElts) 119 return; 120 121 unsigned Size = VT.getSizeInBits().getKnownMinValue(); 122 const TargetRegisterClass *RC; 123 if (Size <= RISCV::RVVBitsPerBlock) 124 RC = &RISCV::VRRegClass; 125 else if (Size == 2 * RISCV::RVVBitsPerBlock) 126 RC = &RISCV::VRM2RegClass; 127 else if (Size == 4 * RISCV::RVVBitsPerBlock) 128 RC = &RISCV::VRM4RegClass; 129 else if (Size == 8 * RISCV::RVVBitsPerBlock) 130 RC = &RISCV::VRM8RegClass; 131 else 132 llvm_unreachable("Unexpected size"); 133 134 addRegisterClass(VT, RC); 135 }; 136 137 for (MVT VT : BoolVecVTs) 138 addRegClassForRVV(VT); 139 for (MVT VT : IntVecVTs) { 140 if (VT.getVectorElementType() == MVT::i64 && 141 !Subtarget.hasVInstructionsI64()) 142 continue; 143 addRegClassForRVV(VT); 144 } 145 146 if (Subtarget.hasVInstructionsF16()) 147 for (MVT VT : F16VecVTs) 148 addRegClassForRVV(VT); 149 150 if (Subtarget.hasVInstructionsF32()) 151 for (MVT VT : F32VecVTs) 152 addRegClassForRVV(VT); 153 154 if (Subtarget.hasVInstructionsF64()) 155 for (MVT VT : F64VecVTs) 156 addRegClassForRVV(VT); 157 158 if (Subtarget.useRVVForFixedLengthVectors()) { 159 auto addRegClassForFixedVectors = [this](MVT VT) { 160 MVT ContainerVT = getContainerForFixedLengthVector(VT); 161 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 162 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 163 addRegisterClass(VT, TRI.getRegClass(RCID)); 164 }; 165 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 166 if (useRVVForFixedLengthVectorVT(VT)) 167 addRegClassForFixedVectors(VT); 168 169 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 170 if (useRVVForFixedLengthVectorVT(VT)) 171 addRegClassForFixedVectors(VT); 172 } 173 } 174 175 // Compute derived properties from the register classes. 176 computeRegisterProperties(STI.getRegisterInfo()); 177 178 setStackPointerRegisterToSaveRestore(RISCV::X2); 179 180 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, XLenVT, 181 MVT::i1, Promote); 182 183 // TODO: add all necessary setOperationAction calls. 184 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 185 186 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 187 setOperationAction(ISD::BR_CC, XLenVT, Expand); 188 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 189 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 190 191 setOperationAction({ISD::STACKSAVE, ISD::STACKRESTORE}, MVT::Other, Expand); 192 193 setOperationAction(ISD::VASTART, MVT::Other, Custom); 194 setOperationAction({ISD::VAARG, ISD::VACOPY, ISD::VAEND}, MVT::Other, Expand); 195 196 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 197 198 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 199 200 if (!Subtarget.hasStdExtZbb()) 201 setOperationAction(ISD::SIGN_EXTEND_INREG, {MVT::i8, MVT::i16}, Expand); 202 203 if (Subtarget.is64Bit()) { 204 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 205 206 setOperationAction({ISD::ADD, ISD::SUB, ISD::SHL, ISD::SRA, ISD::SRL}, 207 MVT::i32, Custom); 208 209 setOperationAction({ISD::UADDO, ISD::USUBO, ISD::UADDSAT, ISD::USUBSAT}, 210 MVT::i32, Custom); 211 } else { 212 setLibcallName( 213 {RTLIB::SHL_I128, RTLIB::SRL_I128, RTLIB::SRA_I128, RTLIB::MUL_I128}, 214 nullptr); 215 setLibcallName(RTLIB::MULO_I64, nullptr); 216 } 217 218 if (!Subtarget.hasStdExtM()) { 219 setOperationAction({ISD::MUL, ISD::MULHS, ISD::MULHU, ISD::SDIV, ISD::UDIV, 220 ISD::SREM, ISD::UREM}, 221 XLenVT, Expand); 222 } else { 223 if (Subtarget.is64Bit()) { 224 setOperationAction(ISD::MUL, {MVT::i32, MVT::i128}, Custom); 225 226 setOperationAction({ISD::SDIV, ISD::UDIV, ISD::UREM}, 227 {MVT::i8, MVT::i16, MVT::i32}, Custom); 228 } else { 229 setOperationAction(ISD::MUL, MVT::i64, Custom); 230 } 231 } 232 233 setOperationAction( 234 {ISD::SDIVREM, ISD::UDIVREM, ISD::SMUL_LOHI, ISD::UMUL_LOHI}, XLenVT, 235 Expand); 236 237 setOperationAction({ISD::SHL_PARTS, ISD::SRL_PARTS, ISD::SRA_PARTS}, XLenVT, 238 Custom); 239 240 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 241 Subtarget.hasStdExtZbkb()) { 242 if (Subtarget.is64Bit()) 243 setOperationAction({ISD::ROTL, ISD::ROTR}, MVT::i32, Custom); 244 } else { 245 setOperationAction({ISD::ROTL, ISD::ROTR}, XLenVT, Expand); 246 } 247 248 if (Subtarget.hasStdExtZbp()) { 249 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 250 // more combining. 251 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, XLenVT, Custom); 252 253 // BSWAP i8 doesn't exist. 254 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 255 256 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i16, Custom); 257 258 if (Subtarget.is64Bit()) 259 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i32, Custom); 260 } else { 261 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 262 // pattern match it directly in isel. 263 setOperationAction(ISD::BSWAP, XLenVT, 264 (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) 265 ? Legal 266 : Expand); 267 // Zbkb can use rev8+brev8 to implement bitreverse. 268 setOperationAction(ISD::BITREVERSE, XLenVT, 269 Subtarget.hasStdExtZbkb() ? Custom : Expand); 270 } 271 272 if (Subtarget.hasStdExtZbb()) { 273 setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, XLenVT, 274 Legal); 275 276 if (Subtarget.is64Bit()) 277 setOperationAction( 278 {ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF}, 279 MVT::i32, Custom); 280 } else { 281 setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP}, XLenVT, Expand); 282 283 if (Subtarget.is64Bit()) 284 setOperationAction(ISD::ABS, MVT::i32, Custom); 285 } 286 287 if (Subtarget.hasStdExtZbt()) { 288 setOperationAction({ISD::FSHL, ISD::FSHR}, XLenVT, Custom); 289 setOperationAction(ISD::SELECT, XLenVT, Legal); 290 291 if (Subtarget.is64Bit()) 292 setOperationAction({ISD::FSHL, ISD::FSHR}, MVT::i32, Custom); 293 } else { 294 setOperationAction(ISD::SELECT, XLenVT, Custom); 295 } 296 297 static constexpr ISD::NodeType FPLegalNodeTypes[] = { 298 ISD::FMINNUM, ISD::FMAXNUM, ISD::LRINT, 299 ISD::LLRINT, ISD::LROUND, ISD::LLROUND, 300 ISD::STRICT_LRINT, ISD::STRICT_LLRINT, ISD::STRICT_LROUND, 301 ISD::STRICT_LLROUND, ISD::STRICT_FMA, ISD::STRICT_FADD, 302 ISD::STRICT_FSUB, ISD::STRICT_FMUL, ISD::STRICT_FDIV, 303 ISD::STRICT_FSQRT, ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS}; 304 305 static const ISD::CondCode FPCCToExpand[] = { 306 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 307 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 308 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 309 310 static const ISD::NodeType FPOpToExpand[] = { 311 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 312 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 313 314 if (Subtarget.hasStdExtZfh()) 315 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 316 317 if (Subtarget.hasStdExtZfh()) { 318 for (auto NT : FPLegalNodeTypes) 319 setOperationAction(NT, MVT::f16, Legal); 320 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 321 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 322 setCondCodeAction(FPCCToExpand, MVT::f16, Expand); 323 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 324 setOperationAction(ISD::SELECT, MVT::f16, Custom); 325 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 326 327 setOperationAction({ISD::FREM, ISD::FCEIL, ISD::FFLOOR, ISD::FNEARBYINT, 328 ISD::FRINT, ISD::FROUND, ISD::FROUNDEVEN, ISD::FTRUNC, 329 ISD::FPOW, ISD::FPOWI, ISD::FCOS, ISD::FSIN, 330 ISD::FSINCOS, ISD::FEXP, ISD::FEXP2, ISD::FLOG, 331 ISD::FLOG2, ISD::FLOG10}, 332 MVT::f16, Promote); 333 334 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 335 // complete support for all operations in LegalizeDAG. 336 337 // We need to custom promote this. 338 if (Subtarget.is64Bit()) 339 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 340 } 341 342 if (Subtarget.hasStdExtF()) { 343 for (auto NT : FPLegalNodeTypes) 344 setOperationAction(NT, MVT::f32, Legal); 345 setCondCodeAction(FPCCToExpand, MVT::f32, Expand); 346 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 347 setOperationAction(ISD::SELECT, MVT::f32, Custom); 348 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 349 for (auto Op : FPOpToExpand) 350 setOperationAction(Op, MVT::f32, Expand); 351 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 352 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 353 } 354 355 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 356 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 357 358 if (Subtarget.hasStdExtD()) { 359 for (auto NT : FPLegalNodeTypes) 360 setOperationAction(NT, MVT::f64, Legal); 361 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 362 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 363 setCondCodeAction(FPCCToExpand, MVT::f64, Expand); 364 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 365 setOperationAction(ISD::SELECT, MVT::f64, Custom); 366 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 367 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 368 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 369 for (auto Op : FPOpToExpand) 370 setOperationAction(Op, MVT::f64, Expand); 371 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 372 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 373 } 374 375 if (Subtarget.is64Bit()) 376 setOperationAction({ISD::FP_TO_UINT, ISD::FP_TO_SINT, 377 ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT}, 378 MVT::i32, Custom); 379 380 if (Subtarget.hasStdExtF()) { 381 setOperationAction({ISD::FP_TO_UINT_SAT, ISD::FP_TO_SINT_SAT}, XLenVT, 382 Custom); 383 384 setOperationAction({ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT, 385 ISD::STRICT_UINT_TO_FP, ISD::STRICT_SINT_TO_FP}, 386 XLenVT, Legal); 387 388 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 389 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 390 } 391 392 setOperationAction({ISD::GlobalAddress, ISD::BlockAddress, ISD::ConstantPool, 393 ISD::JumpTable}, 394 XLenVT, Custom); 395 396 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 397 398 if (Subtarget.is64Bit()) 399 setOperationAction(ISD::Constant, MVT::i64, Custom); 400 401 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 402 // Unfortunately this can't be determined just from the ISA naming string. 403 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 404 Subtarget.is64Bit() ? Legal : Custom); 405 406 setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Legal); 407 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 408 if (Subtarget.is64Bit()) 409 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 410 411 if (Subtarget.hasStdExtA()) { 412 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 413 setMinCmpXchgSizeInBits(32); 414 } else { 415 setMaxAtomicSizeInBitsSupported(0); 416 } 417 418 setBooleanContents(ZeroOrOneBooleanContent); 419 420 if (Subtarget.hasVInstructions()) { 421 setBooleanVectorContents(ZeroOrOneBooleanContent); 422 423 setOperationAction(ISD::VSCALE, XLenVT, Custom); 424 425 // RVV intrinsics may have illegal operands. 426 // We also need to custom legalize vmv.x.s. 427 setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN}, 428 {MVT::i8, MVT::i16}, Custom); 429 if (Subtarget.is64Bit()) 430 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 431 else 432 setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN}, 433 MVT::i64, Custom); 434 435 setOperationAction({ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID}, 436 MVT::Other, Custom); 437 438 static const unsigned IntegerVPOps[] = { 439 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 440 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 441 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 442 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 443 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 444 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 445 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 446 ISD::VP_MERGE, ISD::VP_SELECT, ISD::VP_FPTOSI, 447 ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_SIGN_EXTEND, 448 ISD::VP_ZERO_EXTEND, ISD::VP_TRUNCATE}; 449 450 static const unsigned FloatingPointVPOps[] = { 451 ISD::VP_FADD, ISD::VP_FSUB, 452 ISD::VP_FMUL, ISD::VP_FDIV, 453 ISD::VP_FNEG, ISD::VP_FMA, 454 ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 455 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, 456 ISD::VP_MERGE, ISD::VP_SELECT, 457 ISD::VP_SITOFP, ISD::VP_UITOFP, 458 ISD::VP_SETCC, ISD::VP_FP_ROUND, 459 ISD::VP_FP_EXTEND}; 460 461 if (!Subtarget.is64Bit()) { 462 // We must custom-lower certain vXi64 operations on RV32 due to the vector 463 // element type being illegal. 464 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 465 MVT::i64, Custom); 466 467 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, 468 ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR, 469 ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 470 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}, 471 MVT::i64, Custom); 472 473 setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 474 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, 475 ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN, 476 ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN}, 477 MVT::i64, Custom); 478 } 479 480 for (MVT VT : BoolVecVTs) { 481 if (!isTypeLegal(VT)) 482 continue; 483 484 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 485 486 // Mask VTs are custom-expanded into a series of standard nodes 487 setOperationAction({ISD::TRUNCATE, ISD::CONCAT_VECTORS, 488 ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 489 VT, Custom); 490 491 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 492 Custom); 493 494 setOperationAction(ISD::SELECT, VT, Custom); 495 setOperationAction( 496 {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT, 497 Expand); 498 499 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom); 500 501 setOperationAction( 502 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 503 Custom); 504 505 setOperationAction( 506 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 507 Custom); 508 509 // RVV has native int->float & float->int conversions where the 510 // element type sizes are within one power-of-two of each other. Any 511 // wider distances between type sizes have to be lowered as sequences 512 // which progressively narrow the gap in stages. 513 setOperationAction( 514 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 515 VT, Custom); 516 517 // Expand all extending loads to types larger than this, and truncating 518 // stores from types larger than this. 519 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 520 setTruncStoreAction(OtherVT, VT, Expand); 521 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 522 VT, Expand); 523 } 524 525 setOperationAction( 526 {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_TRUNCATE, ISD::VP_SETCC}, VT, 527 Custom); 528 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 529 530 setOperationPromotedToType( 531 ISD::VECTOR_SPLICE, VT, 532 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount())); 533 } 534 535 for (MVT VT : IntVecVTs) { 536 if (!isTypeLegal(VT)) 537 continue; 538 539 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 540 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 541 542 // Vectors implement MULHS/MULHU. 543 setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand); 544 545 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 546 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) 547 setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand); 548 549 setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT, 550 Legal); 551 552 setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand); 553 554 setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP, ISD::BSWAP}, VT, 555 Expand); 556 557 setOperationAction(ISD::BSWAP, VT, Expand); 558 559 // Custom-lower extensions and truncations from/to mask types. 560 setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, 561 VT, Custom); 562 563 // RVV has native int->float & float->int conversions where the 564 // element type sizes are within one power-of-two of each other. Any 565 // wider distances between type sizes have to be lowered as sequences 566 // which progressively narrow the gap in stages. 567 setOperationAction( 568 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 569 VT, Custom); 570 571 setOperationAction( 572 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal); 573 574 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 575 // nodes which truncate by one power of two at a time. 576 setOperationAction(ISD::TRUNCATE, VT, Custom); 577 578 // Custom-lower insert/extract operations to simplify patterns. 579 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 580 Custom); 581 582 // Custom-lower reduction operations to set up the corresponding custom 583 // nodes' operands. 584 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, 585 ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR, 586 ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 587 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}, 588 VT, Custom); 589 590 setOperationAction(IntegerVPOps, VT, Custom); 591 592 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 593 594 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 595 VT, Custom); 596 597 setOperationAction( 598 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 599 Custom); 600 601 setOperationAction( 602 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 603 VT, Custom); 604 605 setOperationAction(ISD::SELECT, VT, Custom); 606 setOperationAction(ISD::SELECT_CC, VT, Expand); 607 608 setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom); 609 610 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 611 setTruncStoreAction(VT, OtherVT, Expand); 612 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 613 VT, Expand); 614 } 615 616 // Splice 617 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 618 619 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 620 // type that can represent the value exactly. 621 if (VT.getVectorElementType() != MVT::i64) { 622 MVT FloatEltVT = 623 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 624 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 625 if (isTypeLegal(FloatVT)) { 626 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 627 Custom); 628 } 629 } 630 } 631 632 // Expand various CCs to best match the RVV ISA, which natively supports UNE 633 // but no other unordered comparisons, and supports all ordered comparisons 634 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 635 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 636 // and we pattern-match those back to the "original", swapping operands once 637 // more. This way we catch both operations and both "vf" and "fv" forms with 638 // fewer patterns. 639 static const ISD::CondCode VFPCCToExpand[] = { 640 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 641 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 642 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 643 }; 644 645 // Sets common operation actions on RVV floating-point vector types. 646 const auto SetCommonVFPActions = [&](MVT VT) { 647 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 648 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 649 // sizes are within one power-of-two of each other. Therefore conversions 650 // between vXf16 and vXf64 must be lowered as sequences which convert via 651 // vXf32. 652 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 653 // Custom-lower insert/extract operations to simplify patterns. 654 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 655 Custom); 656 // Expand various condition codes (explained above). 657 setCondCodeAction(VFPCCToExpand, VT, Expand); 658 659 setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal); 660 661 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 662 VT, Custom); 663 664 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 665 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 666 VT, Custom); 667 668 // Expand FP operations that need libcalls. 669 setOperationAction(ISD::FREM, VT, Expand); 670 setOperationAction(ISD::FPOW, VT, Expand); 671 setOperationAction(ISD::FCOS, VT, Expand); 672 setOperationAction(ISD::FSIN, VT, Expand); 673 setOperationAction(ISD::FSINCOS, VT, Expand); 674 setOperationAction(ISD::FEXP, VT, Expand); 675 setOperationAction(ISD::FEXP2, VT, Expand); 676 setOperationAction(ISD::FLOG, VT, Expand); 677 setOperationAction(ISD::FLOG2, VT, Expand); 678 setOperationAction(ISD::FLOG10, VT, Expand); 679 setOperationAction(ISD::FRINT, VT, Expand); 680 setOperationAction(ISD::FNEARBYINT, VT, Expand); 681 682 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 683 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 684 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 685 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 686 687 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 688 689 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 690 691 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 692 VT, Custom); 693 694 setOperationAction( 695 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 696 Custom); 697 698 setOperationAction(ISD::SELECT, VT, Custom); 699 setOperationAction(ISD::SELECT_CC, VT, Expand); 700 701 setOperationAction( 702 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 703 VT, Custom); 704 705 setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom); 706 707 setOperationAction(FloatingPointVPOps, VT, Custom); 708 }; 709 710 // Sets common extload/truncstore actions on RVV floating-point vector 711 // types. 712 const auto SetCommonVFPExtLoadTruncStoreActions = 713 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 714 for (auto SmallVT : SmallerVTs) { 715 setTruncStoreAction(VT, SmallVT, Expand); 716 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 717 } 718 }; 719 720 if (Subtarget.hasVInstructionsF16()) { 721 for (MVT VT : F16VecVTs) { 722 if (!isTypeLegal(VT)) 723 continue; 724 SetCommonVFPActions(VT); 725 } 726 } 727 728 if (Subtarget.hasVInstructionsF32()) { 729 for (MVT VT : F32VecVTs) { 730 if (!isTypeLegal(VT)) 731 continue; 732 SetCommonVFPActions(VT); 733 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 734 } 735 } 736 737 if (Subtarget.hasVInstructionsF64()) { 738 for (MVT VT : F64VecVTs) { 739 if (!isTypeLegal(VT)) 740 continue; 741 SetCommonVFPActions(VT); 742 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 743 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 744 } 745 } 746 747 if (Subtarget.useRVVForFixedLengthVectors()) { 748 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 749 if (!useRVVForFixedLengthVectorVT(VT)) 750 continue; 751 752 // By default everything must be expanded. 753 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 754 setOperationAction(Op, VT, Expand); 755 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 756 setTruncStoreAction(VT, OtherVT, Expand); 757 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, 758 OtherVT, VT, Expand); 759 } 760 761 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 762 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 763 Custom); 764 765 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT, 766 Custom); 767 768 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 769 VT, Custom); 770 771 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 772 773 setOperationAction(ISD::SETCC, VT, Custom); 774 775 setOperationAction(ISD::SELECT, VT, Custom); 776 777 setOperationAction(ISD::TRUNCATE, VT, Custom); 778 779 setOperationAction(ISD::BITCAST, VT, Custom); 780 781 setOperationAction( 782 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 783 Custom); 784 785 setOperationAction( 786 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 787 Custom); 788 789 setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, 790 ISD::FP_TO_UINT}, 791 VT, Custom); 792 793 // Operations below are different for between masks and other vectors. 794 if (VT.getVectorElementType() == MVT::i1) { 795 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND, 796 ISD::OR, ISD::XOR}, 797 VT, Custom); 798 799 setOperationAction( 800 {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_TRUNCATE}, 801 VT, Custom); 802 continue; 803 } 804 805 // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to 806 // it before type legalization for i64 vectors on RV32. It will then be 807 // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle. 808 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 809 // improvements first. 810 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 811 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 812 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 813 } 814 815 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 816 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 817 818 setOperationAction( 819 {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom); 820 821 setOperationAction( 822 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 823 Custom); 824 825 setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR, 826 ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV, 827 ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL}, 828 VT, Custom); 829 830 setOperationAction( 831 {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom); 832 833 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 834 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) 835 setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom); 836 837 setOperationAction( 838 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, 839 Custom); 840 841 setOperationAction(ISD::VSELECT, VT, Custom); 842 setOperationAction(ISD::SELECT_CC, VT, Expand); 843 844 setOperationAction( 845 {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom); 846 847 // Custom-lower reduction operations to set up the corresponding custom 848 // nodes' operands. 849 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX, 850 ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX, 851 ISD::VECREDUCE_UMIN}, 852 VT, Custom); 853 854 setOperationAction(IntegerVPOps, VT, Custom); 855 856 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 857 // type that can represent the value exactly. 858 if (VT.getVectorElementType() != MVT::i64) { 859 MVT FloatEltVT = 860 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 861 EVT FloatVT = 862 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 863 if (isTypeLegal(FloatVT)) 864 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 865 Custom); 866 } 867 } 868 869 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 870 if (!useRVVForFixedLengthVectorVT(VT)) 871 continue; 872 873 // By default everything must be expanded. 874 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 875 setOperationAction(Op, VT, Expand); 876 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 877 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 878 setTruncStoreAction(VT, OtherVT, Expand); 879 } 880 881 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 882 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 883 Custom); 884 885 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS, 886 ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT, 887 ISD::EXTRACT_VECTOR_ELT}, 888 VT, Custom); 889 890 setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE, 891 ISD::MGATHER, ISD::MSCATTER}, 892 VT, Custom); 893 894 setOperationAction( 895 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 896 Custom); 897 898 setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV, 899 ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT, 900 ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM}, 901 VT, Custom); 902 903 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 904 905 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 906 VT, Custom); 907 908 for (auto CC : VFPCCToExpand) 909 setCondCodeAction(CC, VT, Expand); 910 911 setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom); 912 setOperationAction(ISD::SELECT_CC, VT, Expand); 913 914 setOperationAction(ISD::BITCAST, VT, Custom); 915 916 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 917 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 918 VT, Custom); 919 920 setOperationAction(FloatingPointVPOps, VT, Custom); 921 } 922 923 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 924 setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64}, 925 Custom); 926 if (Subtarget.hasStdExtZfh()) 927 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 928 if (Subtarget.hasStdExtF()) 929 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 930 if (Subtarget.hasStdExtD()) 931 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 932 } 933 } 934 935 // Function alignments. 936 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 937 setMinFunctionAlignment(FunctionAlignment); 938 setPrefFunctionAlignment(FunctionAlignment); 939 940 setMinimumJumpTableEntries(5); 941 942 // Jumps are expensive, compared to logic 943 setJumpIsExpensive(); 944 945 setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND, 946 ISD::OR, ISD::XOR}); 947 if (Subtarget.is64Bit()) 948 setTargetDAGCombine(ISD::SRA); 949 950 if (Subtarget.hasStdExtF()) 951 setTargetDAGCombine({ISD::FADD, ISD::FMAXNUM, ISD::FMINNUM}); 952 953 if (Subtarget.hasStdExtZbp()) 954 setTargetDAGCombine({ISD::ROTL, ISD::ROTR}); 955 956 if (Subtarget.hasStdExtZbb()) 957 setTargetDAGCombine({ISD::UMAX, ISD::UMIN, ISD::SMAX, ISD::SMIN}); 958 959 if (Subtarget.hasStdExtZbkb()) 960 setTargetDAGCombine(ISD::BITREVERSE); 961 if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb()) 962 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 963 if (Subtarget.hasStdExtF()) 964 setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT, 965 ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}); 966 if (Subtarget.hasVInstructions()) 967 setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER, 968 ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL, 969 ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR}); 970 if (Subtarget.useRVVForFixedLengthVectors()) 971 setTargetDAGCombine(ISD::BITCAST); 972 973 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 974 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 975 } 976 977 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 978 LLVMContext &Context, 979 EVT VT) const { 980 if (!VT.isVector()) 981 return getPointerTy(DL); 982 if (Subtarget.hasVInstructions() && 983 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 984 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 985 return VT.changeVectorElementTypeToInteger(); 986 } 987 988 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 989 return Subtarget.getXLenVT(); 990 } 991 992 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 993 const CallInst &I, 994 MachineFunction &MF, 995 unsigned Intrinsic) const { 996 auto &DL = I.getModule()->getDataLayout(); 997 switch (Intrinsic) { 998 default: 999 return false; 1000 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 1001 case Intrinsic::riscv_masked_atomicrmw_add_i32: 1002 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 1003 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1004 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1005 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1006 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1007 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1008 case Intrinsic::riscv_masked_cmpxchg_i32: 1009 Info.opc = ISD::INTRINSIC_W_CHAIN; 1010 Info.memVT = MVT::i32; 1011 Info.ptrVal = I.getArgOperand(0); 1012 Info.offset = 0; 1013 Info.align = Align(4); 1014 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1015 MachineMemOperand::MOVolatile; 1016 return true; 1017 case Intrinsic::riscv_masked_strided_load: 1018 Info.opc = ISD::INTRINSIC_W_CHAIN; 1019 Info.ptrVal = I.getArgOperand(1); 1020 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1021 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1022 Info.size = MemoryLocation::UnknownSize; 1023 Info.flags |= MachineMemOperand::MOLoad; 1024 return true; 1025 case Intrinsic::riscv_masked_strided_store: 1026 Info.opc = ISD::INTRINSIC_VOID; 1027 Info.ptrVal = I.getArgOperand(1); 1028 Info.memVT = 1029 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1030 Info.align = Align( 1031 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1032 8); 1033 Info.size = MemoryLocation::UnknownSize; 1034 Info.flags |= MachineMemOperand::MOStore; 1035 return true; 1036 case Intrinsic::riscv_seg2_load: 1037 case Intrinsic::riscv_seg3_load: 1038 case Intrinsic::riscv_seg4_load: 1039 case Intrinsic::riscv_seg5_load: 1040 case Intrinsic::riscv_seg6_load: 1041 case Intrinsic::riscv_seg7_load: 1042 case Intrinsic::riscv_seg8_load: 1043 Info.opc = ISD::INTRINSIC_W_CHAIN; 1044 Info.ptrVal = I.getArgOperand(0); 1045 Info.memVT = 1046 getValueType(DL, I.getType()->getStructElementType(0)->getScalarType()); 1047 Info.align = 1048 Align(DL.getTypeSizeInBits( 1049 I.getType()->getStructElementType(0)->getScalarType()) / 1050 8); 1051 Info.size = MemoryLocation::UnknownSize; 1052 Info.flags |= MachineMemOperand::MOLoad; 1053 return true; 1054 } 1055 } 1056 1057 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1058 const AddrMode &AM, Type *Ty, 1059 unsigned AS, 1060 Instruction *I) const { 1061 // No global is ever allowed as a base. 1062 if (AM.BaseGV) 1063 return false; 1064 1065 // RVV instructions only support register addressing. 1066 if (Subtarget.hasVInstructions() && isa<VectorType>(Ty)) 1067 return AM.HasBaseReg && AM.Scale == 0 && !AM.BaseOffs; 1068 1069 // Require a 12-bit signed offset. 1070 if (!isInt<12>(AM.BaseOffs)) 1071 return false; 1072 1073 switch (AM.Scale) { 1074 case 0: // "r+i" or just "i", depending on HasBaseReg. 1075 break; 1076 case 1: 1077 if (!AM.HasBaseReg) // allow "r+i". 1078 break; 1079 return false; // disallow "r+r" or "r+r+i". 1080 default: 1081 return false; 1082 } 1083 1084 return true; 1085 } 1086 1087 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1088 return isInt<12>(Imm); 1089 } 1090 1091 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1092 return isInt<12>(Imm); 1093 } 1094 1095 // On RV32, 64-bit integers are split into their high and low parts and held 1096 // in two different registers, so the trunc is free since the low register can 1097 // just be used. 1098 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1099 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1100 return false; 1101 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1102 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1103 return (SrcBits == 64 && DestBits == 32); 1104 } 1105 1106 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1107 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1108 !SrcVT.isInteger() || !DstVT.isInteger()) 1109 return false; 1110 unsigned SrcBits = SrcVT.getSizeInBits(); 1111 unsigned DestBits = DstVT.getSizeInBits(); 1112 return (SrcBits == 64 && DestBits == 32); 1113 } 1114 1115 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1116 // Zexts are free if they can be combined with a load. 1117 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1118 // poorly with type legalization of compares preferring sext. 1119 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1120 EVT MemVT = LD->getMemoryVT(); 1121 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1122 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1123 LD->getExtensionType() == ISD::ZEXTLOAD)) 1124 return true; 1125 } 1126 1127 return TargetLowering::isZExtFree(Val, VT2); 1128 } 1129 1130 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1131 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1132 } 1133 1134 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const { 1135 return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32); 1136 } 1137 1138 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1139 return Subtarget.hasStdExtZbb(); 1140 } 1141 1142 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1143 return Subtarget.hasStdExtZbb(); 1144 } 1145 1146 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1147 EVT VT = Y.getValueType(); 1148 1149 // FIXME: Support vectors once we have tests. 1150 if (VT.isVector()) 1151 return false; 1152 1153 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1154 Subtarget.hasStdExtZbkb()) && 1155 !isa<ConstantSDNode>(Y); 1156 } 1157 1158 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const { 1159 // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position. 1160 auto *C = dyn_cast<ConstantSDNode>(Y); 1161 return C && C->getAPIntValue().ule(10); 1162 } 1163 1164 bool RISCVTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1165 Type *Ty) const { 1166 assert(Ty->isIntegerTy()); 1167 1168 unsigned BitSize = Ty->getIntegerBitWidth(); 1169 if (BitSize > Subtarget.getXLen()) 1170 return false; 1171 1172 // Fast path, assume 32-bit immediates are cheap. 1173 int64_t Val = Imm.getSExtValue(); 1174 if (isInt<32>(Val)) 1175 return true; 1176 1177 // A constant pool entry may be more aligned thant he load we're trying to 1178 // replace. If we don't support unaligned scalar mem, prefer the constant 1179 // pool. 1180 // TODO: Can the caller pass down the alignment? 1181 if (!Subtarget.enableUnalignedScalarMem()) 1182 return true; 1183 1184 // Prefer to keep the load if it would require many instructions. 1185 // This uses the same threshold we use for constant pools but doesn't 1186 // check useConstantPoolForLargeInts. 1187 // TODO: Should we keep the load only when we're definitely going to emit a 1188 // constant pool? 1189 1190 RISCVMatInt::InstSeq Seq = 1191 RISCVMatInt::generateInstSeq(Val, Subtarget.getFeatureBits()); 1192 return Seq.size() <= Subtarget.getMaxBuildIntsCost(); 1193 } 1194 1195 bool RISCVTargetLowering:: 1196 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 1197 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y, 1198 unsigned OldShiftOpcode, unsigned NewShiftOpcode, 1199 SelectionDAG &DAG) const { 1200 // One interesting pattern that we'd want to form is 'bit extract': 1201 // ((1 >> Y) & 1) ==/!= 0 1202 // But we also need to be careful not to try to reverse that fold. 1203 1204 // Is this '((1 >> Y) & 1)'? 1205 if (XC && OldShiftOpcode == ISD::SRL && XC->isOne()) 1206 return false; // Keep the 'bit extract' pattern. 1207 1208 // Will this be '((1 >> Y) & 1)' after the transform? 1209 if (NewShiftOpcode == ISD::SRL && CC->isOne()) 1210 return true; // Do form the 'bit extract' pattern. 1211 1212 // If 'X' is a constant, and we transform, then we will immediately 1213 // try to undo the fold, thus causing endless combine loop. 1214 // So only do the transform if X is not a constant. This matches the default 1215 // implementation of this function. 1216 return !XC; 1217 } 1218 1219 /// Check if sinking \p I's operands to I's basic block is profitable, because 1220 /// the operands can be folded into a target instruction, e.g. 1221 /// splats of scalars can fold into vector instructions. 1222 bool RISCVTargetLowering::shouldSinkOperands( 1223 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1224 using namespace llvm::PatternMatch; 1225 1226 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1227 return false; 1228 1229 auto IsSinker = [&](Instruction *I, int Operand) { 1230 switch (I->getOpcode()) { 1231 case Instruction::Add: 1232 case Instruction::Sub: 1233 case Instruction::Mul: 1234 case Instruction::And: 1235 case Instruction::Or: 1236 case Instruction::Xor: 1237 case Instruction::FAdd: 1238 case Instruction::FSub: 1239 case Instruction::FMul: 1240 case Instruction::FDiv: 1241 case Instruction::ICmp: 1242 case Instruction::FCmp: 1243 return true; 1244 case Instruction::Shl: 1245 case Instruction::LShr: 1246 case Instruction::AShr: 1247 case Instruction::UDiv: 1248 case Instruction::SDiv: 1249 case Instruction::URem: 1250 case Instruction::SRem: 1251 return Operand == 1; 1252 case Instruction::Call: 1253 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1254 switch (II->getIntrinsicID()) { 1255 case Intrinsic::fma: 1256 case Intrinsic::vp_fma: 1257 return Operand == 0 || Operand == 1; 1258 // FIXME: Our patterns can only match vx/vf instructions when the splat 1259 // it on the RHS, because TableGen doesn't recognize our VP operations 1260 // as commutative. 1261 case Intrinsic::vp_add: 1262 case Intrinsic::vp_mul: 1263 case Intrinsic::vp_and: 1264 case Intrinsic::vp_or: 1265 case Intrinsic::vp_xor: 1266 case Intrinsic::vp_fadd: 1267 case Intrinsic::vp_fmul: 1268 case Intrinsic::vp_shl: 1269 case Intrinsic::vp_lshr: 1270 case Intrinsic::vp_ashr: 1271 case Intrinsic::vp_udiv: 1272 case Intrinsic::vp_sdiv: 1273 case Intrinsic::vp_urem: 1274 case Intrinsic::vp_srem: 1275 return Operand == 1; 1276 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1277 // explicit patterns for both LHS and RHS (as 'vr' versions). 1278 case Intrinsic::vp_sub: 1279 case Intrinsic::vp_fsub: 1280 case Intrinsic::vp_fdiv: 1281 return Operand == 0 || Operand == 1; 1282 default: 1283 return false; 1284 } 1285 } 1286 return false; 1287 default: 1288 return false; 1289 } 1290 }; 1291 1292 for (auto OpIdx : enumerate(I->operands())) { 1293 if (!IsSinker(I, OpIdx.index())) 1294 continue; 1295 1296 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1297 // Make sure we are not already sinking this operand 1298 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1299 continue; 1300 1301 // We are looking for a splat that can be sunk. 1302 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1303 m_Undef(), m_ZeroMask()))) 1304 continue; 1305 1306 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1307 // and vector registers 1308 for (Use &U : Op->uses()) { 1309 Instruction *Insn = cast<Instruction>(U.getUser()); 1310 if (!IsSinker(Insn, U.getOperandNo())) 1311 return false; 1312 } 1313 1314 Ops.push_back(&Op->getOperandUse(0)); 1315 Ops.push_back(&OpIdx.value()); 1316 } 1317 return true; 1318 } 1319 1320 bool RISCVTargetLowering::isOffsetFoldingLegal( 1321 const GlobalAddressSDNode *GA) const { 1322 // In order to maximise the opportunity for common subexpression elimination, 1323 // keep a separate ADD node for the global address offset instead of folding 1324 // it in the global address node. Later peephole optimisations may choose to 1325 // fold it back in when profitable. 1326 return false; 1327 } 1328 1329 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1330 bool ForCodeSize) const { 1331 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1332 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1333 return false; 1334 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1335 return false; 1336 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1337 return false; 1338 return Imm.isZero(); 1339 } 1340 1341 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1342 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1343 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1344 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1345 } 1346 1347 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1348 CallingConv::ID CC, 1349 EVT VT) const { 1350 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1351 // We might still end up using a GPR but that will be decided based on ABI. 1352 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1353 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1354 return MVT::f32; 1355 1356 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1357 } 1358 1359 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1360 CallingConv::ID CC, 1361 EVT VT) const { 1362 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1363 // We might still end up using a GPR but that will be decided based on ABI. 1364 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1365 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1366 return 1; 1367 1368 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1369 } 1370 1371 // Changes the condition code and swaps operands if necessary, so the SetCC 1372 // operation matches one of the comparisons supported directly by branches 1373 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1374 // with 1/-1. 1375 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1376 ISD::CondCode &CC, SelectionDAG &DAG) { 1377 // Convert X > -1 to X >= 0. 1378 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1379 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1380 CC = ISD::SETGE; 1381 return; 1382 } 1383 // Convert X < 1 to 0 >= X. 1384 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1385 RHS = LHS; 1386 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1387 CC = ISD::SETGE; 1388 return; 1389 } 1390 1391 switch (CC) { 1392 default: 1393 break; 1394 case ISD::SETGT: 1395 case ISD::SETLE: 1396 case ISD::SETUGT: 1397 case ISD::SETULE: 1398 CC = ISD::getSetCCSwappedOperands(CC); 1399 std::swap(LHS, RHS); 1400 break; 1401 } 1402 } 1403 1404 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1405 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1406 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1407 if (VT.getVectorElementType() == MVT::i1) 1408 KnownSize *= 8; 1409 1410 switch (KnownSize) { 1411 default: 1412 llvm_unreachable("Invalid LMUL."); 1413 case 8: 1414 return RISCVII::VLMUL::LMUL_F8; 1415 case 16: 1416 return RISCVII::VLMUL::LMUL_F4; 1417 case 32: 1418 return RISCVII::VLMUL::LMUL_F2; 1419 case 64: 1420 return RISCVII::VLMUL::LMUL_1; 1421 case 128: 1422 return RISCVII::VLMUL::LMUL_2; 1423 case 256: 1424 return RISCVII::VLMUL::LMUL_4; 1425 case 512: 1426 return RISCVII::VLMUL::LMUL_8; 1427 } 1428 } 1429 1430 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1431 switch (LMul) { 1432 default: 1433 llvm_unreachable("Invalid LMUL."); 1434 case RISCVII::VLMUL::LMUL_F8: 1435 case RISCVII::VLMUL::LMUL_F4: 1436 case RISCVII::VLMUL::LMUL_F2: 1437 case RISCVII::VLMUL::LMUL_1: 1438 return RISCV::VRRegClassID; 1439 case RISCVII::VLMUL::LMUL_2: 1440 return RISCV::VRM2RegClassID; 1441 case RISCVII::VLMUL::LMUL_4: 1442 return RISCV::VRM4RegClassID; 1443 case RISCVII::VLMUL::LMUL_8: 1444 return RISCV::VRM8RegClassID; 1445 } 1446 } 1447 1448 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1449 RISCVII::VLMUL LMUL = getLMUL(VT); 1450 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1451 LMUL == RISCVII::VLMUL::LMUL_F4 || 1452 LMUL == RISCVII::VLMUL::LMUL_F2 || 1453 LMUL == RISCVII::VLMUL::LMUL_1) { 1454 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1455 "Unexpected subreg numbering"); 1456 return RISCV::sub_vrm1_0 + Index; 1457 } 1458 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1459 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1460 "Unexpected subreg numbering"); 1461 return RISCV::sub_vrm2_0 + Index; 1462 } 1463 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1464 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1465 "Unexpected subreg numbering"); 1466 return RISCV::sub_vrm4_0 + Index; 1467 } 1468 llvm_unreachable("Invalid vector type."); 1469 } 1470 1471 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1472 if (VT.getVectorElementType() == MVT::i1) 1473 return RISCV::VRRegClassID; 1474 return getRegClassIDForLMUL(getLMUL(VT)); 1475 } 1476 1477 // Attempt to decompose a subvector insert/extract between VecVT and 1478 // SubVecVT via subregister indices. Returns the subregister index that 1479 // can perform the subvector insert/extract with the given element index, as 1480 // well as the index corresponding to any leftover subvectors that must be 1481 // further inserted/extracted within the register class for SubVecVT. 1482 std::pair<unsigned, unsigned> 1483 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1484 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1485 const RISCVRegisterInfo *TRI) { 1486 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1487 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1488 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1489 "Register classes not ordered"); 1490 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1491 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1492 // Try to compose a subregister index that takes us from the incoming 1493 // LMUL>1 register class down to the outgoing one. At each step we half 1494 // the LMUL: 1495 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1496 // Note that this is not guaranteed to find a subregister index, such as 1497 // when we are extracting from one VR type to another. 1498 unsigned SubRegIdx = RISCV::NoSubRegister; 1499 for (const unsigned RCID : 1500 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1501 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1502 VecVT = VecVT.getHalfNumVectorElementsVT(); 1503 bool IsHi = 1504 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1505 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1506 getSubregIndexByMVT(VecVT, IsHi)); 1507 if (IsHi) 1508 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1509 } 1510 return {SubRegIdx, InsertExtractIdx}; 1511 } 1512 1513 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1514 // stores for those types. 1515 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1516 return !Subtarget.useRVVForFixedLengthVectors() || 1517 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1518 } 1519 1520 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1521 if (ScalarTy->isPointerTy()) 1522 return true; 1523 1524 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1525 ScalarTy->isIntegerTy(32)) 1526 return true; 1527 1528 if (ScalarTy->isIntegerTy(64)) 1529 return Subtarget.hasVInstructionsI64(); 1530 1531 if (ScalarTy->isHalfTy()) 1532 return Subtarget.hasVInstructionsF16(); 1533 if (ScalarTy->isFloatTy()) 1534 return Subtarget.hasVInstructionsF32(); 1535 if (ScalarTy->isDoubleTy()) 1536 return Subtarget.hasVInstructionsF64(); 1537 1538 return false; 1539 } 1540 1541 static SDValue getVLOperand(SDValue Op) { 1542 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1543 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1544 "Unexpected opcode"); 1545 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1546 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1547 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1548 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1549 if (!II) 1550 return SDValue(); 1551 return Op.getOperand(II->VLOperand + 1 + HasChain); 1552 } 1553 1554 static bool useRVVForFixedLengthVectorVT(MVT VT, 1555 const RISCVSubtarget &Subtarget) { 1556 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1557 if (!Subtarget.useRVVForFixedLengthVectors()) 1558 return false; 1559 1560 // We only support a set of vector types with a consistent maximum fixed size 1561 // across all supported vector element types to avoid legalization issues. 1562 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1563 // fixed-length vector type we support is 1024 bytes. 1564 if (VT.getFixedSizeInBits() > 1024 * 8) 1565 return false; 1566 1567 unsigned MinVLen = Subtarget.getRealMinVLen(); 1568 1569 MVT EltVT = VT.getVectorElementType(); 1570 1571 // Don't use RVV for vectors we cannot scalarize if required. 1572 switch (EltVT.SimpleTy) { 1573 // i1 is supported but has different rules. 1574 default: 1575 return false; 1576 case MVT::i1: 1577 // Masks can only use a single register. 1578 if (VT.getVectorNumElements() > MinVLen) 1579 return false; 1580 MinVLen /= 8; 1581 break; 1582 case MVT::i8: 1583 case MVT::i16: 1584 case MVT::i32: 1585 break; 1586 case MVT::i64: 1587 if (!Subtarget.hasVInstructionsI64()) 1588 return false; 1589 break; 1590 case MVT::f16: 1591 if (!Subtarget.hasVInstructionsF16()) 1592 return false; 1593 break; 1594 case MVT::f32: 1595 if (!Subtarget.hasVInstructionsF32()) 1596 return false; 1597 break; 1598 case MVT::f64: 1599 if (!Subtarget.hasVInstructionsF64()) 1600 return false; 1601 break; 1602 } 1603 1604 // Reject elements larger than ELEN. 1605 if (EltVT.getSizeInBits() > Subtarget.getELEN()) 1606 return false; 1607 1608 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1609 // Don't use RVV for types that don't fit. 1610 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1611 return false; 1612 1613 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1614 // the base fixed length RVV support in place. 1615 if (!VT.isPow2VectorType()) 1616 return false; 1617 1618 return true; 1619 } 1620 1621 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1622 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1623 } 1624 1625 // Return the largest legal scalable vector type that matches VT's element type. 1626 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1627 const RISCVSubtarget &Subtarget) { 1628 // This may be called before legal types are setup. 1629 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1630 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1631 "Expected legal fixed length vector!"); 1632 1633 unsigned MinVLen = Subtarget.getRealMinVLen(); 1634 unsigned MaxELen = Subtarget.getELEN(); 1635 1636 MVT EltVT = VT.getVectorElementType(); 1637 switch (EltVT.SimpleTy) { 1638 default: 1639 llvm_unreachable("unexpected element type for RVV container"); 1640 case MVT::i1: 1641 case MVT::i8: 1642 case MVT::i16: 1643 case MVT::i32: 1644 case MVT::i64: 1645 case MVT::f16: 1646 case MVT::f32: 1647 case MVT::f64: { 1648 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1649 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1650 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1651 unsigned NumElts = 1652 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1653 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1654 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1655 return MVT::getScalableVectorVT(EltVT, NumElts); 1656 } 1657 } 1658 } 1659 1660 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1661 const RISCVSubtarget &Subtarget) { 1662 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1663 Subtarget); 1664 } 1665 1666 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1667 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1668 } 1669 1670 // Grow V to consume an entire RVV register. 1671 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1672 const RISCVSubtarget &Subtarget) { 1673 assert(VT.isScalableVector() && 1674 "Expected to convert into a scalable vector!"); 1675 assert(V.getValueType().isFixedLengthVector() && 1676 "Expected a fixed length vector operand!"); 1677 SDLoc DL(V); 1678 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1679 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1680 } 1681 1682 // Shrink V so it's just big enough to maintain a VT's worth of data. 1683 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1684 const RISCVSubtarget &Subtarget) { 1685 assert(VT.isFixedLengthVector() && 1686 "Expected to convert into a fixed length vector!"); 1687 assert(V.getValueType().isScalableVector() && 1688 "Expected a scalable vector operand!"); 1689 SDLoc DL(V); 1690 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1691 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1692 } 1693 1694 /// Return the type of the mask type suitable for masking the provided 1695 /// vector type. This is simply an i1 element type vector of the same 1696 /// (possibly scalable) length. 1697 static MVT getMaskTypeFor(MVT VecVT) { 1698 assert(VecVT.isVector()); 1699 ElementCount EC = VecVT.getVectorElementCount(); 1700 return MVT::getVectorVT(MVT::i1, EC); 1701 } 1702 1703 /// Creates an all ones mask suitable for masking a vector of type VecTy with 1704 /// vector length VL. . 1705 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL, 1706 SelectionDAG &DAG) { 1707 MVT MaskVT = getMaskTypeFor(VecVT); 1708 return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1709 } 1710 1711 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1712 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1713 // the vector type that it is contained in. 1714 static std::pair<SDValue, SDValue> 1715 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1716 const RISCVSubtarget &Subtarget) { 1717 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1718 MVT XLenVT = Subtarget.getXLenVT(); 1719 SDValue VL = VecVT.isFixedLengthVector() 1720 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1721 : DAG.getRegister(RISCV::X0, XLenVT); 1722 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 1723 return {Mask, VL}; 1724 } 1725 1726 // As above but assuming the given type is a scalable vector type. 1727 static std::pair<SDValue, SDValue> 1728 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1729 const RISCVSubtarget &Subtarget) { 1730 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1731 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1732 } 1733 1734 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1735 // of either is (currently) supported. This can get us into an infinite loop 1736 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1737 // as a ..., etc. 1738 // Until either (or both) of these can reliably lower any node, reporting that 1739 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1740 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1741 // which is not desirable. 1742 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1743 EVT VT, unsigned DefinedValues) const { 1744 return false; 1745 } 1746 1747 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1748 const RISCVSubtarget &Subtarget) { 1749 // RISCV FP-to-int conversions saturate to the destination register size, but 1750 // don't produce 0 for nan. We can use a conversion instruction and fix the 1751 // nan case with a compare and a select. 1752 SDValue Src = Op.getOperand(0); 1753 1754 EVT DstVT = Op.getValueType(); 1755 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1756 1757 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1758 unsigned Opc; 1759 if (SatVT == DstVT) 1760 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1761 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1762 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1763 else 1764 return SDValue(); 1765 // FIXME: Support other SatVTs by clamping before or after the conversion. 1766 1767 SDLoc DL(Op); 1768 SDValue FpToInt = DAG.getNode( 1769 Opc, DL, DstVT, Src, 1770 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1771 1772 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1773 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1774 } 1775 1776 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1777 // and back. Taking care to avoid converting values that are nan or already 1778 // correct. 1779 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1780 // have FRM dependencies modeled yet. 1781 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1782 MVT VT = Op.getSimpleValueType(); 1783 assert(VT.isVector() && "Unexpected type"); 1784 1785 SDLoc DL(Op); 1786 1787 // Freeze the source since we are increasing the number of uses. 1788 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1789 1790 // Truncate to integer and convert back to FP. 1791 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1792 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1793 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1794 1795 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1796 1797 if (Op.getOpcode() == ISD::FCEIL) { 1798 // If the truncated value is the greater than or equal to the original 1799 // value, we've computed the ceil. Otherwise, we went the wrong way and 1800 // need to increase by 1. 1801 // FIXME: This should use a masked operation. Handle here or in isel? 1802 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1803 DAG.getConstantFP(1.0, DL, VT)); 1804 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1805 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1806 } else if (Op.getOpcode() == ISD::FFLOOR) { 1807 // If the truncated value is the less than or equal to the original value, 1808 // we've computed the floor. Otherwise, we went the wrong way and need to 1809 // decrease by 1. 1810 // FIXME: This should use a masked operation. Handle here or in isel? 1811 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1812 DAG.getConstantFP(1.0, DL, VT)); 1813 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1814 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1815 } 1816 1817 // Restore the original sign so that -0.0 is preserved. 1818 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1819 1820 // Determine the largest integer that can be represented exactly. This and 1821 // values larger than it don't have any fractional bits so don't need to 1822 // be converted. 1823 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1824 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1825 APFloat MaxVal = APFloat(FltSem); 1826 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1827 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1828 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1829 1830 // If abs(Src) was larger than MaxVal or nan, keep it. 1831 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1832 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1833 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1834 } 1835 1836 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1837 // This mode isn't supported in vector hardware on RISCV. But as long as we 1838 // aren't compiling with trapping math, we can emulate this with 1839 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1840 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1841 // dependencies modeled yet. 1842 // FIXME: Use masked operations to avoid final merge. 1843 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1844 MVT VT = Op.getSimpleValueType(); 1845 assert(VT.isVector() && "Unexpected type"); 1846 1847 SDLoc DL(Op); 1848 1849 // Freeze the source since we are increasing the number of uses. 1850 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1851 1852 // We do the conversion on the absolute value and fix the sign at the end. 1853 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1854 1855 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1856 bool Ignored; 1857 APFloat Point5Pred = APFloat(0.5f); 1858 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1859 Point5Pred.next(/*nextDown*/ true); 1860 1861 // Add the adjustment. 1862 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1863 DAG.getConstantFP(Point5Pred, DL, VT)); 1864 1865 // Truncate to integer and convert back to fp. 1866 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1867 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1868 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1869 1870 // Restore the original sign. 1871 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1872 1873 // Determine the largest integer that can be represented exactly. This and 1874 // values larger than it don't have any fractional bits so don't need to 1875 // be converted. 1876 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1877 APFloat MaxVal = APFloat(FltSem); 1878 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1879 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1880 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1881 1882 // If abs(Src) was larger than MaxVal or nan, keep it. 1883 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1884 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1885 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1886 } 1887 1888 struct VIDSequence { 1889 int64_t StepNumerator; 1890 unsigned StepDenominator; 1891 int64_t Addend; 1892 }; 1893 1894 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1895 // to the (non-zero) step S and start value X. This can be then lowered as the 1896 // RVV sequence (VID * S) + X, for example. 1897 // The step S is represented as an integer numerator divided by a positive 1898 // denominator. Note that the implementation currently only identifies 1899 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1900 // cannot detect 2/3, for example. 1901 // Note that this method will also match potentially unappealing index 1902 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1903 // determine whether this is worth generating code for. 1904 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1905 unsigned NumElts = Op.getNumOperands(); 1906 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1907 if (!Op.getValueType().isInteger()) 1908 return None; 1909 1910 Optional<unsigned> SeqStepDenom; 1911 Optional<int64_t> SeqStepNum, SeqAddend; 1912 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1913 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1914 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1915 // Assume undef elements match the sequence; we just have to be careful 1916 // when interpolating across them. 1917 if (Op.getOperand(Idx).isUndef()) 1918 continue; 1919 // The BUILD_VECTOR must be all constants. 1920 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1921 return None; 1922 1923 uint64_t Val = Op.getConstantOperandVal(Idx) & 1924 maskTrailingOnes<uint64_t>(EltSizeInBits); 1925 1926 if (PrevElt) { 1927 // Calculate the step since the last non-undef element, and ensure 1928 // it's consistent across the entire sequence. 1929 unsigned IdxDiff = Idx - PrevElt->second; 1930 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1931 1932 // A zero-value value difference means that we're somewhere in the middle 1933 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1934 // step change before evaluating the sequence. 1935 if (ValDiff == 0) 1936 continue; 1937 1938 int64_t Remainder = ValDiff % IdxDiff; 1939 // Normalize the step if it's greater than 1. 1940 if (Remainder != ValDiff) { 1941 // The difference must cleanly divide the element span. 1942 if (Remainder != 0) 1943 return None; 1944 ValDiff /= IdxDiff; 1945 IdxDiff = 1; 1946 } 1947 1948 if (!SeqStepNum) 1949 SeqStepNum = ValDiff; 1950 else if (ValDiff != SeqStepNum) 1951 return None; 1952 1953 if (!SeqStepDenom) 1954 SeqStepDenom = IdxDiff; 1955 else if (IdxDiff != *SeqStepDenom) 1956 return None; 1957 } 1958 1959 // Record this non-undef element for later. 1960 if (!PrevElt || PrevElt->first != Val) 1961 PrevElt = std::make_pair(Val, Idx); 1962 } 1963 1964 // We need to have logged a step for this to count as a legal index sequence. 1965 if (!SeqStepNum || !SeqStepDenom) 1966 return None; 1967 1968 // Loop back through the sequence and validate elements we might have skipped 1969 // while waiting for a valid step. While doing this, log any sequence addend. 1970 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1971 if (Op.getOperand(Idx).isUndef()) 1972 continue; 1973 uint64_t Val = Op.getConstantOperandVal(Idx) & 1974 maskTrailingOnes<uint64_t>(EltSizeInBits); 1975 uint64_t ExpectedVal = 1976 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1977 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1978 if (!SeqAddend) 1979 SeqAddend = Addend; 1980 else if (Addend != SeqAddend) 1981 return None; 1982 } 1983 1984 assert(SeqAddend && "Must have an addend if we have a step"); 1985 1986 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1987 } 1988 1989 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1990 // and lower it as a VRGATHER_VX_VL from the source vector. 1991 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 1992 SelectionDAG &DAG, 1993 const RISCVSubtarget &Subtarget) { 1994 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1995 return SDValue(); 1996 SDValue Vec = SplatVal.getOperand(0); 1997 // Only perform this optimization on vectors of the same size for simplicity. 1998 // Don't perform this optimization for i1 vectors. 1999 // FIXME: Support i1 vectors, maybe by promoting to i8? 2000 if (Vec.getValueType() != VT || VT.getVectorElementType() == MVT::i1) 2001 return SDValue(); 2002 SDValue Idx = SplatVal.getOperand(1); 2003 // The index must be a legal type. 2004 if (Idx.getValueType() != Subtarget.getXLenVT()) 2005 return SDValue(); 2006 2007 MVT ContainerVT = VT; 2008 if (VT.isFixedLengthVector()) { 2009 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2010 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 2011 } 2012 2013 SDValue Mask, VL; 2014 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2015 2016 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 2017 Idx, Mask, DAG.getUNDEF(ContainerVT), VL); 2018 2019 if (!VT.isFixedLengthVector()) 2020 return Gather; 2021 2022 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2023 } 2024 2025 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 2026 const RISCVSubtarget &Subtarget) { 2027 MVT VT = Op.getSimpleValueType(); 2028 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 2029 2030 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2031 2032 SDLoc DL(Op); 2033 SDValue Mask, VL; 2034 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2035 2036 MVT XLenVT = Subtarget.getXLenVT(); 2037 unsigned NumElts = Op.getNumOperands(); 2038 2039 if (VT.getVectorElementType() == MVT::i1) { 2040 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 2041 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 2042 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 2043 } 2044 2045 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 2046 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 2047 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 2048 } 2049 2050 // Lower constant mask BUILD_VECTORs via an integer vector type, in 2051 // scalar integer chunks whose bit-width depends on the number of mask 2052 // bits and XLEN. 2053 // First, determine the most appropriate scalar integer type to use. This 2054 // is at most XLenVT, but may be shrunk to a smaller vector element type 2055 // according to the size of the final vector - use i8 chunks rather than 2056 // XLenVT if we're producing a v8i1. This results in more consistent 2057 // codegen across RV32 and RV64. 2058 unsigned NumViaIntegerBits = 2059 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 2060 NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN()); 2061 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 2062 // If we have to use more than one INSERT_VECTOR_ELT then this 2063 // optimization is likely to increase code size; avoid peforming it in 2064 // such a case. We can use a load from a constant pool in this case. 2065 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 2066 return SDValue(); 2067 // Now we can create our integer vector type. Note that it may be larger 2068 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2069 MVT IntegerViaVecVT = 2070 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2071 divideCeil(NumElts, NumViaIntegerBits)); 2072 2073 uint64_t Bits = 0; 2074 unsigned BitPos = 0, IntegerEltIdx = 0; 2075 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2076 2077 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2078 // Once we accumulate enough bits to fill our scalar type, insert into 2079 // our vector and clear our accumulated data. 2080 if (I != 0 && I % NumViaIntegerBits == 0) { 2081 if (NumViaIntegerBits <= 32) 2082 Bits = SignExtend64<32>(Bits); 2083 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2084 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2085 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2086 Bits = 0; 2087 BitPos = 0; 2088 IntegerEltIdx++; 2089 } 2090 SDValue V = Op.getOperand(I); 2091 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2092 Bits |= ((uint64_t)BitValue << BitPos); 2093 } 2094 2095 // Insert the (remaining) scalar value into position in our integer 2096 // vector type. 2097 if (NumViaIntegerBits <= 32) 2098 Bits = SignExtend64<32>(Bits); 2099 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2100 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2101 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2102 2103 if (NumElts < NumViaIntegerBits) { 2104 // If we're producing a smaller vector than our minimum legal integer 2105 // type, bitcast to the equivalent (known-legal) mask type, and extract 2106 // our final mask. 2107 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2108 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2109 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2110 DAG.getConstant(0, DL, XLenVT)); 2111 } else { 2112 // Else we must have produced an integer type with the same size as the 2113 // mask type; bitcast for the final result. 2114 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2115 Vec = DAG.getBitcast(VT, Vec); 2116 } 2117 2118 return Vec; 2119 } 2120 2121 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2122 // vector type, we have a legal equivalently-sized i8 type, so we can use 2123 // that. 2124 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2125 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2126 2127 SDValue WideVec; 2128 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2129 // For a splat, perform a scalar truncate before creating the wider 2130 // vector. 2131 assert(Splat.getValueType() == XLenVT && 2132 "Unexpected type for i1 splat value"); 2133 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2134 DAG.getConstant(1, DL, XLenVT)); 2135 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2136 } else { 2137 SmallVector<SDValue, 8> Ops(Op->op_values()); 2138 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2139 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2140 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2141 } 2142 2143 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2144 } 2145 2146 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2147 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2148 return Gather; 2149 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2150 : RISCVISD::VMV_V_X_VL; 2151 Splat = 2152 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2153 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2154 } 2155 2156 // Try and match index sequences, which we can lower to the vid instruction 2157 // with optional modifications. An all-undef vector is matched by 2158 // getSplatValue, above. 2159 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2160 int64_t StepNumerator = SimpleVID->StepNumerator; 2161 unsigned StepDenominator = SimpleVID->StepDenominator; 2162 int64_t Addend = SimpleVID->Addend; 2163 2164 assert(StepNumerator != 0 && "Invalid step"); 2165 bool Negate = false; 2166 int64_t SplatStepVal = StepNumerator; 2167 unsigned StepOpcode = ISD::MUL; 2168 if (StepNumerator != 1) { 2169 if (isPowerOf2_64(std::abs(StepNumerator))) { 2170 Negate = StepNumerator < 0; 2171 StepOpcode = ISD::SHL; 2172 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2173 } 2174 } 2175 2176 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2177 // threshold since it's the immediate value many RVV instructions accept. 2178 // There is no vmul.vi instruction so ensure multiply constant can fit in 2179 // a single addi instruction. 2180 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2181 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2182 isPowerOf2_32(StepDenominator) && 2183 (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) { 2184 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2185 // Convert right out of the scalable type so we can use standard ISD 2186 // nodes for the rest of the computation. If we used scalable types with 2187 // these, we'd lose the fixed-length vector info and generate worse 2188 // vsetvli code. 2189 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2190 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2191 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2192 SDValue SplatStep = DAG.getSplatBuildVector( 2193 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2194 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2195 } 2196 if (StepDenominator != 1) { 2197 SDValue SplatStep = DAG.getSplatBuildVector( 2198 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2199 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2200 } 2201 if (Addend != 0 || Negate) { 2202 SDValue SplatAddend = DAG.getSplatBuildVector( 2203 VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2204 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2205 } 2206 return VID; 2207 } 2208 } 2209 2210 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2211 // when re-interpreted as a vector with a larger element type. For example, 2212 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2213 // could be instead splat as 2214 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2215 // TODO: This optimization could also work on non-constant splats, but it 2216 // would require bit-manipulation instructions to construct the splat value. 2217 SmallVector<SDValue> Sequence; 2218 unsigned EltBitSize = VT.getScalarSizeInBits(); 2219 const auto *BV = cast<BuildVectorSDNode>(Op); 2220 if (VT.isInteger() && EltBitSize < 64 && 2221 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2222 BV->getRepeatedSequence(Sequence) && 2223 (Sequence.size() * EltBitSize) <= 64) { 2224 unsigned SeqLen = Sequence.size(); 2225 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2226 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2227 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2228 ViaIntVT == MVT::i64) && 2229 "Unexpected sequence type"); 2230 2231 unsigned EltIdx = 0; 2232 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2233 uint64_t SplatValue = 0; 2234 // Construct the amalgamated value which can be splatted as this larger 2235 // vector type. 2236 for (const auto &SeqV : Sequence) { 2237 if (!SeqV.isUndef()) 2238 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2239 << (EltIdx * EltBitSize)); 2240 EltIdx++; 2241 } 2242 2243 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2244 // achieve better constant materializion. 2245 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2246 SplatValue = SignExtend64<32>(SplatValue); 2247 2248 // Since we can't introduce illegal i64 types at this stage, we can only 2249 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2250 // way we can use RVV instructions to splat. 2251 assert((ViaIntVT.bitsLE(XLenVT) || 2252 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2253 "Unexpected bitcast sequence"); 2254 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2255 SDValue ViaVL = 2256 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2257 MVT ViaContainerVT = 2258 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2259 SDValue Splat = 2260 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2261 DAG.getUNDEF(ViaContainerVT), 2262 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2263 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2264 return DAG.getBitcast(VT, Splat); 2265 } 2266 } 2267 2268 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2269 // which constitute a large proportion of the elements. In such cases we can 2270 // splat a vector with the dominant element and make up the shortfall with 2271 // INSERT_VECTOR_ELTs. 2272 // Note that this includes vectors of 2 elements by association. The 2273 // upper-most element is the "dominant" one, allowing us to use a splat to 2274 // "insert" the upper element, and an insert of the lower element at position 2275 // 0, which improves codegen. 2276 SDValue DominantValue; 2277 unsigned MostCommonCount = 0; 2278 DenseMap<SDValue, unsigned> ValueCounts; 2279 unsigned NumUndefElts = 2280 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2281 2282 // Track the number of scalar loads we know we'd be inserting, estimated as 2283 // any non-zero floating-point constant. Other kinds of element are either 2284 // already in registers or are materialized on demand. The threshold at which 2285 // a vector load is more desirable than several scalar materializion and 2286 // vector-insertion instructions is not known. 2287 unsigned NumScalarLoads = 0; 2288 2289 for (SDValue V : Op->op_values()) { 2290 if (V.isUndef()) 2291 continue; 2292 2293 ValueCounts.insert(std::make_pair(V, 0)); 2294 unsigned &Count = ValueCounts[V]; 2295 2296 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2297 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2298 2299 // Is this value dominant? In case of a tie, prefer the highest element as 2300 // it's cheaper to insert near the beginning of a vector than it is at the 2301 // end. 2302 if (++Count >= MostCommonCount) { 2303 DominantValue = V; 2304 MostCommonCount = Count; 2305 } 2306 } 2307 2308 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2309 unsigned NumDefElts = NumElts - NumUndefElts; 2310 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2311 2312 // Don't perform this optimization when optimizing for size, since 2313 // materializing elements and inserting them tends to cause code bloat. 2314 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2315 ((MostCommonCount > DominantValueCountThreshold) || 2316 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2317 // Start by splatting the most common element. 2318 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2319 2320 DenseSet<SDValue> Processed{DominantValue}; 2321 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2322 for (const auto &OpIdx : enumerate(Op->ops())) { 2323 const SDValue &V = OpIdx.value(); 2324 if (V.isUndef() || !Processed.insert(V).second) 2325 continue; 2326 if (ValueCounts[V] == 1) { 2327 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2328 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2329 } else { 2330 // Blend in all instances of this value using a VSELECT, using a 2331 // mask where each bit signals whether that element is the one 2332 // we're after. 2333 SmallVector<SDValue> Ops; 2334 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2335 return DAG.getConstant(V == V1, DL, XLenVT); 2336 }); 2337 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2338 DAG.getBuildVector(SelMaskTy, DL, Ops), 2339 DAG.getSplatBuildVector(VT, DL, V), Vec); 2340 } 2341 } 2342 2343 return Vec; 2344 } 2345 2346 return SDValue(); 2347 } 2348 2349 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2350 SDValue Lo, SDValue Hi, SDValue VL, 2351 SelectionDAG &DAG) { 2352 if (!Passthru) 2353 Passthru = DAG.getUNDEF(VT); 2354 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2355 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2356 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2357 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2358 // node in order to try and match RVV vector/scalar instructions. 2359 if ((LoC >> 31) == HiC) 2360 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2361 2362 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2363 // vmv.v.x whose EEW = 32 to lower it. 2364 auto *Const = dyn_cast<ConstantSDNode>(VL); 2365 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2366 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2367 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2368 // access the subtarget here now. 2369 auto InterVec = DAG.getNode( 2370 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2371 DAG.getRegister(RISCV::X0, MVT::i32)); 2372 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2373 } 2374 } 2375 2376 // Fall back to a stack store and stride x0 vector load. 2377 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2378 Hi, VL); 2379 } 2380 2381 // Called by type legalization to handle splat of i64 on RV32. 2382 // FIXME: We can optimize this when the type has sign or zero bits in one 2383 // of the halves. 2384 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2385 SDValue Scalar, SDValue VL, 2386 SelectionDAG &DAG) { 2387 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2388 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2389 DAG.getConstant(0, DL, MVT::i32)); 2390 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2391 DAG.getConstant(1, DL, MVT::i32)); 2392 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2393 } 2394 2395 // This function lowers a splat of a scalar operand Splat with the vector 2396 // length VL. It ensures the final sequence is type legal, which is useful when 2397 // lowering a splat after type legalization. 2398 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2399 MVT VT, SDLoc DL, SelectionDAG &DAG, 2400 const RISCVSubtarget &Subtarget) { 2401 bool HasPassthru = Passthru && !Passthru.isUndef(); 2402 if (!HasPassthru && !Passthru) 2403 Passthru = DAG.getUNDEF(VT); 2404 if (VT.isFloatingPoint()) { 2405 // If VL is 1, we could use vfmv.s.f. 2406 if (isOneConstant(VL)) 2407 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2408 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2409 } 2410 2411 MVT XLenVT = Subtarget.getXLenVT(); 2412 2413 // Simplest case is that the operand needs to be promoted to XLenVT. 2414 if (Scalar.getValueType().bitsLE(XLenVT)) { 2415 // If the operand is a constant, sign extend to increase our chances 2416 // of being able to use a .vi instruction. ANY_EXTEND would become a 2417 // a zero extend and the simm5 check in isel would fail. 2418 // FIXME: Should we ignore the upper bits in isel instead? 2419 unsigned ExtOpc = 2420 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2421 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2422 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2423 // If VL is 1 and the scalar value won't benefit from immediate, we could 2424 // use vmv.s.x. 2425 if (isOneConstant(VL) && 2426 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2427 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2428 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2429 } 2430 2431 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2432 "Unexpected scalar for splat lowering!"); 2433 2434 if (isOneConstant(VL) && isNullConstant(Scalar)) 2435 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2436 DAG.getConstant(0, DL, XLenVT), VL); 2437 2438 // Otherwise use the more complicated splatting algorithm. 2439 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2440 } 2441 2442 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2443 const RISCVSubtarget &Subtarget) { 2444 // We need to be able to widen elements to the next larger integer type. 2445 if (VT.getScalarSizeInBits() >= Subtarget.getELEN()) 2446 return false; 2447 2448 int Size = Mask.size(); 2449 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2450 2451 int Srcs[] = {-1, -1}; 2452 for (int i = 0; i != Size; ++i) { 2453 // Ignore undef elements. 2454 if (Mask[i] < 0) 2455 continue; 2456 2457 // Is this an even or odd element. 2458 int Pol = i % 2; 2459 2460 // Ensure we consistently use the same source for this element polarity. 2461 int Src = Mask[i] / Size; 2462 if (Srcs[Pol] < 0) 2463 Srcs[Pol] = Src; 2464 if (Srcs[Pol] != Src) 2465 return false; 2466 2467 // Make sure the element within the source is appropriate for this element 2468 // in the destination. 2469 int Elt = Mask[i] % Size; 2470 if (Elt != i / 2) 2471 return false; 2472 } 2473 2474 // We need to find a source for each polarity and they can't be the same. 2475 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2476 return false; 2477 2478 // Swap the sources if the second source was in the even polarity. 2479 SwapSources = Srcs[0] > Srcs[1]; 2480 2481 return true; 2482 } 2483 2484 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2485 /// and then extract the original number of elements from the rotated result. 2486 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2487 /// returned rotation amount is for a rotate right, where elements move from 2488 /// higher elements to lower elements. \p LoSrc indicates the first source 2489 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2490 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2491 /// 0 or 1 if a rotation is found. 2492 /// 2493 /// NOTE: We talk about rotate to the right which matches how bit shift and 2494 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2495 /// and the table below write vectors with the lowest elements on the left. 2496 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2497 int Size = Mask.size(); 2498 2499 // We need to detect various ways of spelling a rotation: 2500 // [11, 12, 13, 14, 15, 0, 1, 2] 2501 // [-1, 12, 13, 14, -1, -1, 1, -1] 2502 // [-1, -1, -1, -1, -1, -1, 1, 2] 2503 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2504 // [-1, 4, 5, 6, -1, -1, 9, -1] 2505 // [-1, 4, 5, 6, -1, -1, -1, -1] 2506 int Rotation = 0; 2507 LoSrc = -1; 2508 HiSrc = -1; 2509 for (int i = 0; i != Size; ++i) { 2510 int M = Mask[i]; 2511 if (M < 0) 2512 continue; 2513 2514 // Determine where a rotate vector would have started. 2515 int StartIdx = i - (M % Size); 2516 // The identity rotation isn't interesting, stop. 2517 if (StartIdx == 0) 2518 return -1; 2519 2520 // If we found the tail of a vector the rotation must be the missing 2521 // front. If we found the head of a vector, it must be how much of the 2522 // head. 2523 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2524 2525 if (Rotation == 0) 2526 Rotation = CandidateRotation; 2527 else if (Rotation != CandidateRotation) 2528 // The rotations don't match, so we can't match this mask. 2529 return -1; 2530 2531 // Compute which value this mask is pointing at. 2532 int MaskSrc = M < Size ? 0 : 1; 2533 2534 // Compute which of the two target values this index should be assigned to. 2535 // This reflects whether the high elements are remaining or the low elemnts 2536 // are remaining. 2537 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2538 2539 // Either set up this value if we've not encountered it before, or check 2540 // that it remains consistent. 2541 if (TargetSrc < 0) 2542 TargetSrc = MaskSrc; 2543 else if (TargetSrc != MaskSrc) 2544 // This may be a rotation, but it pulls from the inputs in some 2545 // unsupported interleaving. 2546 return -1; 2547 } 2548 2549 // Check that we successfully analyzed the mask, and normalize the results. 2550 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2551 assert((LoSrc >= 0 || HiSrc >= 0) && 2552 "Failed to find a rotated input vector!"); 2553 2554 return Rotation; 2555 } 2556 2557 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2558 const RISCVSubtarget &Subtarget) { 2559 SDValue V1 = Op.getOperand(0); 2560 SDValue V2 = Op.getOperand(1); 2561 SDLoc DL(Op); 2562 MVT XLenVT = Subtarget.getXLenVT(); 2563 MVT VT = Op.getSimpleValueType(); 2564 unsigned NumElts = VT.getVectorNumElements(); 2565 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2566 2567 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2568 2569 SDValue TrueMask, VL; 2570 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2571 2572 if (SVN->isSplat()) { 2573 const int Lane = SVN->getSplatIndex(); 2574 if (Lane >= 0) { 2575 MVT SVT = VT.getVectorElementType(); 2576 2577 // Turn splatted vector load into a strided load with an X0 stride. 2578 SDValue V = V1; 2579 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2580 // with undef. 2581 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2582 int Offset = Lane; 2583 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2584 int OpElements = 2585 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2586 V = V.getOperand(Offset / OpElements); 2587 Offset %= OpElements; 2588 } 2589 2590 // We need to ensure the load isn't atomic or volatile. 2591 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2592 auto *Ld = cast<LoadSDNode>(V); 2593 Offset *= SVT.getStoreSize(); 2594 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2595 TypeSize::Fixed(Offset), DL); 2596 2597 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2598 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2599 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2600 SDValue IntID = 2601 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2602 SDValue Ops[] = {Ld->getChain(), 2603 IntID, 2604 DAG.getUNDEF(ContainerVT), 2605 NewAddr, 2606 DAG.getRegister(RISCV::X0, XLenVT), 2607 VL}; 2608 SDValue NewLoad = DAG.getMemIntrinsicNode( 2609 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2610 DAG.getMachineFunction().getMachineMemOperand( 2611 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2612 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2613 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2614 } 2615 2616 // Otherwise use a scalar load and splat. This will give the best 2617 // opportunity to fold a splat into the operation. ISel can turn it into 2618 // the x0 strided load if we aren't able to fold away the select. 2619 if (SVT.isFloatingPoint()) 2620 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2621 Ld->getPointerInfo().getWithOffset(Offset), 2622 Ld->getOriginalAlign(), 2623 Ld->getMemOperand()->getFlags()); 2624 else 2625 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2626 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2627 Ld->getOriginalAlign(), 2628 Ld->getMemOperand()->getFlags()); 2629 DAG.makeEquivalentMemoryOrdering(Ld, V); 2630 2631 unsigned Opc = 2632 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2633 SDValue Splat = 2634 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2635 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2636 } 2637 2638 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2639 assert(Lane < (int)NumElts && "Unexpected lane!"); 2640 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, 2641 V1, DAG.getConstant(Lane, DL, XLenVT), 2642 TrueMask, DAG.getUNDEF(ContainerVT), VL); 2643 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2644 } 2645 } 2646 2647 ArrayRef<int> Mask = SVN->getMask(); 2648 2649 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2650 // be undef which can be handled with a single SLIDEDOWN/UP. 2651 int LoSrc, HiSrc; 2652 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2653 if (Rotation > 0) { 2654 SDValue LoV, HiV; 2655 if (LoSrc >= 0) { 2656 LoV = LoSrc == 0 ? V1 : V2; 2657 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2658 } 2659 if (HiSrc >= 0) { 2660 HiV = HiSrc == 0 ? V1 : V2; 2661 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2662 } 2663 2664 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2665 // to slide LoV up by (NumElts - Rotation). 2666 unsigned InvRotate = NumElts - Rotation; 2667 2668 SDValue Res = DAG.getUNDEF(ContainerVT); 2669 if (HiV) { 2670 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2671 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2672 // causes multiple vsetvlis in some test cases such as lowering 2673 // reduce.mul 2674 SDValue DownVL = VL; 2675 if (LoV) 2676 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2677 Res = 2678 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2679 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2680 } 2681 if (LoV) 2682 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2683 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2684 2685 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2686 } 2687 2688 // Detect an interleave shuffle and lower to 2689 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2690 bool SwapSources; 2691 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2692 // Swap sources if needed. 2693 if (SwapSources) 2694 std::swap(V1, V2); 2695 2696 // Extract the lower half of the vectors. 2697 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2698 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2699 DAG.getConstant(0, DL, XLenVT)); 2700 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2701 DAG.getConstant(0, DL, XLenVT)); 2702 2703 // Double the element width and halve the number of elements in an int type. 2704 unsigned EltBits = VT.getScalarSizeInBits(); 2705 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2706 MVT WideIntVT = 2707 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2708 // Convert this to a scalable vector. We need to base this on the 2709 // destination size to ensure there's always a type with a smaller LMUL. 2710 MVT WideIntContainerVT = 2711 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2712 2713 // Convert sources to scalable vectors with the same element count as the 2714 // larger type. 2715 MVT HalfContainerVT = MVT::getVectorVT( 2716 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2717 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2718 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2719 2720 // Cast sources to integer. 2721 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2722 MVT IntHalfVT = 2723 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2724 V1 = DAG.getBitcast(IntHalfVT, V1); 2725 V2 = DAG.getBitcast(IntHalfVT, V2); 2726 2727 // Freeze V2 since we use it twice and we need to be sure that the add and 2728 // multiply see the same value. 2729 V2 = DAG.getFreeze(V2); 2730 2731 // Recreate TrueMask using the widened type's element count. 2732 TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG); 2733 2734 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2735 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2736 V2, TrueMask, VL); 2737 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2738 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2739 DAG.getUNDEF(IntHalfVT), 2740 DAG.getAllOnesConstant(DL, XLenVT)); 2741 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2742 V2, Multiplier, TrueMask, VL); 2743 // Add the new copies to our previous addition giving us 2^eltbits copies of 2744 // V2. This is equivalent to shifting V2 left by eltbits. This should 2745 // combine with the vwmulu.vv above to form vwmaccu.vv. 2746 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2747 TrueMask, VL); 2748 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2749 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2750 // vector VT. 2751 ContainerVT = 2752 MVT::getVectorVT(VT.getVectorElementType(), 2753 WideIntContainerVT.getVectorElementCount() * 2); 2754 Add = DAG.getBitcast(ContainerVT, Add); 2755 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2756 } 2757 2758 // Detect shuffles which can be re-expressed as vector selects; these are 2759 // shuffles in which each element in the destination is taken from an element 2760 // at the corresponding index in either source vectors. 2761 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2762 int MaskIndex = MaskIdx.value(); 2763 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2764 }); 2765 2766 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2767 2768 SmallVector<SDValue> MaskVals; 2769 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2770 // merged with a second vrgather. 2771 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2772 2773 // By default we preserve the original operand order, and use a mask to 2774 // select LHS as true and RHS as false. However, since RVV vector selects may 2775 // feature splats but only on the LHS, we may choose to invert our mask and 2776 // instead select between RHS and LHS. 2777 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2778 bool InvertMask = IsSelect == SwapOps; 2779 2780 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2781 // half. 2782 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2783 2784 // Now construct the mask that will be used by the vselect or blended 2785 // vrgather operation. For vrgathers, construct the appropriate indices into 2786 // each vector. 2787 for (int MaskIndex : Mask) { 2788 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2789 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2790 if (!IsSelect) { 2791 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2792 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2793 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2794 : DAG.getUNDEF(XLenVT)); 2795 GatherIndicesRHS.push_back( 2796 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2797 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2798 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2799 ++LHSIndexCounts[MaskIndex]; 2800 if (!IsLHSOrUndefIndex) 2801 ++RHSIndexCounts[MaskIndex - NumElts]; 2802 } 2803 } 2804 2805 if (SwapOps) { 2806 std::swap(V1, V2); 2807 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2808 } 2809 2810 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2811 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2812 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2813 2814 if (IsSelect) 2815 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2816 2817 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2818 // On such a large vector we're unable to use i8 as the index type. 2819 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2820 // may involve vector splitting if we're already at LMUL=8, or our 2821 // user-supplied maximum fixed-length LMUL. 2822 return SDValue(); 2823 } 2824 2825 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2826 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2827 MVT IndexVT = VT.changeTypeToInteger(); 2828 // Since we can't introduce illegal index types at this stage, use i16 and 2829 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2830 // than XLenVT. 2831 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2832 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2833 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2834 } 2835 2836 MVT IndexContainerVT = 2837 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2838 2839 SDValue Gather; 2840 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2841 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2842 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2843 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2844 Subtarget); 2845 } else { 2846 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2847 // If only one index is used, we can use a "splat" vrgather. 2848 // TODO: We can splat the most-common index and fix-up any stragglers, if 2849 // that's beneficial. 2850 if (LHSIndexCounts.size() == 1) { 2851 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2852 Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2853 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, 2854 DAG.getUNDEF(ContainerVT), VL); 2855 } else { 2856 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2857 LHSIndices = 2858 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2859 2860 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2861 TrueMask, DAG.getUNDEF(ContainerVT), VL); 2862 } 2863 } 2864 2865 // If a second vector operand is used by this shuffle, blend it in with an 2866 // additional vrgather. 2867 if (!V2.isUndef()) { 2868 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2869 2870 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2871 SelectMask = 2872 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2873 2874 // If only one index is used, we can use a "splat" vrgather. 2875 // TODO: We can splat the most-common index and fix-up any stragglers, if 2876 // that's beneficial. 2877 if (RHSIndexCounts.size() == 1) { 2878 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2879 Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2880 DAG.getConstant(SplatIndex, DL, XLenVT), SelectMask, 2881 Gather, VL); 2882 } else { 2883 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2884 RHSIndices = 2885 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2886 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, 2887 SelectMask, Gather, VL); 2888 } 2889 } 2890 2891 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2892 } 2893 2894 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2895 // Support splats for any type. These should type legalize well. 2896 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2897 return true; 2898 2899 // Only support legal VTs for other shuffles for now. 2900 if (!isTypeLegal(VT)) 2901 return false; 2902 2903 MVT SVT = VT.getSimpleVT(); 2904 2905 bool SwapSources; 2906 int LoSrc, HiSrc; 2907 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2908 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2909 } 2910 2911 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2912 // the exponent. 2913 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2914 MVT VT = Op.getSimpleValueType(); 2915 unsigned EltSize = VT.getScalarSizeInBits(); 2916 SDValue Src = Op.getOperand(0); 2917 SDLoc DL(Op); 2918 2919 // We need a FP type that can represent the value. 2920 // TODO: Use f16 for i8 when possible? 2921 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2922 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2923 2924 // Legal types should have been checked in the RISCVTargetLowering 2925 // constructor. 2926 // TODO: Splitting may make sense in some cases. 2927 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2928 "Expected legal float type!"); 2929 2930 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2931 // The trailing zero count is equal to log2 of this single bit value. 2932 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2933 SDValue Neg = 2934 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2935 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2936 } 2937 2938 // We have a legal FP type, convert to it. 2939 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2940 // Bitcast to integer and shift the exponent to the LSB. 2941 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2942 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2943 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2944 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2945 DAG.getConstant(ShiftAmt, DL, IntVT)); 2946 // Truncate back to original type to allow vnsrl. 2947 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2948 // The exponent contains log2 of the value in biased form. 2949 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2950 2951 // For trailing zeros, we just need to subtract the bias. 2952 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2953 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2954 DAG.getConstant(ExponentBias, DL, VT)); 2955 2956 // For leading zeros, we need to remove the bias and convert from log2 to 2957 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2958 unsigned Adjust = ExponentBias + (EltSize - 1); 2959 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2960 } 2961 2962 // While RVV has alignment restrictions, we should always be able to load as a 2963 // legal equivalently-sized byte-typed vector instead. This method is 2964 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2965 // the load is already correctly-aligned, it returns SDValue(). 2966 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2967 SelectionDAG &DAG) const { 2968 auto *Load = cast<LoadSDNode>(Op); 2969 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2970 2971 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2972 Load->getMemoryVT(), 2973 *Load->getMemOperand())) 2974 return SDValue(); 2975 2976 SDLoc DL(Op); 2977 MVT VT = Op.getSimpleValueType(); 2978 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2979 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2980 "Unexpected unaligned RVV load type"); 2981 MVT NewVT = 2982 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2983 assert(NewVT.isValid() && 2984 "Expecting equally-sized RVV vector types to be legal"); 2985 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2986 Load->getPointerInfo(), Load->getOriginalAlign(), 2987 Load->getMemOperand()->getFlags()); 2988 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2989 } 2990 2991 // While RVV has alignment restrictions, we should always be able to store as a 2992 // legal equivalently-sized byte-typed vector instead. This method is 2993 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2994 // returns SDValue() if the store is already correctly aligned. 2995 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2996 SelectionDAG &DAG) const { 2997 auto *Store = cast<StoreSDNode>(Op); 2998 assert(Store && Store->getValue().getValueType().isVector() && 2999 "Expected vector store"); 3000 3001 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 3002 Store->getMemoryVT(), 3003 *Store->getMemOperand())) 3004 return SDValue(); 3005 3006 SDLoc DL(Op); 3007 SDValue StoredVal = Store->getValue(); 3008 MVT VT = StoredVal.getSimpleValueType(); 3009 unsigned EltSizeBits = VT.getScalarSizeInBits(); 3010 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 3011 "Unexpected unaligned RVV store type"); 3012 MVT NewVT = 3013 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 3014 assert(NewVT.isValid() && 3015 "Expecting equally-sized RVV vector types to be legal"); 3016 StoredVal = DAG.getBitcast(NewVT, StoredVal); 3017 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 3018 Store->getPointerInfo(), Store->getOriginalAlign(), 3019 Store->getMemOperand()->getFlags()); 3020 } 3021 3022 static SDValue lowerConstant(SDValue Op, SelectionDAG &DAG, 3023 const RISCVSubtarget &Subtarget) { 3024 assert(Op.getValueType() == MVT::i64 && "Unexpected VT"); 3025 3026 int64_t Imm = cast<ConstantSDNode>(Op)->getSExtValue(); 3027 3028 // All simm32 constants should be handled by isel. 3029 // NOTE: The getMaxBuildIntsCost call below should return a value >= 2 making 3030 // this check redundant, but small immediates are common so this check 3031 // should have better compile time. 3032 if (isInt<32>(Imm)) 3033 return Op; 3034 3035 // We only need to cost the immediate, if constant pool lowering is enabled. 3036 if (!Subtarget.useConstantPoolForLargeInts()) 3037 return Op; 3038 3039 RISCVMatInt::InstSeq Seq = 3040 RISCVMatInt::generateInstSeq(Imm, Subtarget.getFeatureBits()); 3041 if (Seq.size() <= Subtarget.getMaxBuildIntsCost()) 3042 return Op; 3043 3044 // Expand to a constant pool using the default expansion code. 3045 return SDValue(); 3046 } 3047 3048 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 3049 SelectionDAG &DAG) const { 3050 switch (Op.getOpcode()) { 3051 default: 3052 report_fatal_error("unimplemented operand"); 3053 case ISD::GlobalAddress: 3054 return lowerGlobalAddress(Op, DAG); 3055 case ISD::BlockAddress: 3056 return lowerBlockAddress(Op, DAG); 3057 case ISD::ConstantPool: 3058 return lowerConstantPool(Op, DAG); 3059 case ISD::JumpTable: 3060 return lowerJumpTable(Op, DAG); 3061 case ISD::GlobalTLSAddress: 3062 return lowerGlobalTLSAddress(Op, DAG); 3063 case ISD::Constant: 3064 return lowerConstant(Op, DAG, Subtarget); 3065 case ISD::SELECT: 3066 return lowerSELECT(Op, DAG); 3067 case ISD::BRCOND: 3068 return lowerBRCOND(Op, DAG); 3069 case ISD::VASTART: 3070 return lowerVASTART(Op, DAG); 3071 case ISD::FRAMEADDR: 3072 return lowerFRAMEADDR(Op, DAG); 3073 case ISD::RETURNADDR: 3074 return lowerRETURNADDR(Op, DAG); 3075 case ISD::SHL_PARTS: 3076 return lowerShiftLeftParts(Op, DAG); 3077 case ISD::SRA_PARTS: 3078 return lowerShiftRightParts(Op, DAG, true); 3079 case ISD::SRL_PARTS: 3080 return lowerShiftRightParts(Op, DAG, false); 3081 case ISD::BITCAST: { 3082 SDLoc DL(Op); 3083 EVT VT = Op.getValueType(); 3084 SDValue Op0 = Op.getOperand(0); 3085 EVT Op0VT = Op0.getValueType(); 3086 MVT XLenVT = Subtarget.getXLenVT(); 3087 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 3088 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 3089 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 3090 return FPConv; 3091 } 3092 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 3093 Subtarget.hasStdExtF()) { 3094 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3095 SDValue FPConv = 3096 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3097 return FPConv; 3098 } 3099 3100 // Consider other scalar<->scalar casts as legal if the types are legal. 3101 // Otherwise expand them. 3102 if (!VT.isVector() && !Op0VT.isVector()) { 3103 if (isTypeLegal(VT) && isTypeLegal(Op0VT)) 3104 return Op; 3105 return SDValue(); 3106 } 3107 3108 assert(!VT.isScalableVector() && !Op0VT.isScalableVector() && 3109 "Unexpected types"); 3110 3111 if (VT.isFixedLengthVector()) { 3112 // We can handle fixed length vector bitcasts with a simple replacement 3113 // in isel. 3114 if (Op0VT.isFixedLengthVector()) 3115 return Op; 3116 // When bitcasting from scalar to fixed-length vector, insert the scalar 3117 // into a one-element vector of the result type, and perform a vector 3118 // bitcast. 3119 if (!Op0VT.isVector()) { 3120 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 3121 if (!isTypeLegal(BVT)) 3122 return SDValue(); 3123 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 3124 DAG.getUNDEF(BVT), Op0, 3125 DAG.getConstant(0, DL, XLenVT))); 3126 } 3127 return SDValue(); 3128 } 3129 // Custom-legalize bitcasts from fixed-length vector types to scalar types 3130 // thus: bitcast the vector to a one-element vector type whose element type 3131 // is the same as the result type, and extract the first element. 3132 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 3133 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 3134 if (!isTypeLegal(BVT)) 3135 return SDValue(); 3136 SDValue BVec = DAG.getBitcast(BVT, Op0); 3137 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 3138 DAG.getConstant(0, DL, XLenVT)); 3139 } 3140 return SDValue(); 3141 } 3142 case ISD::INTRINSIC_WO_CHAIN: 3143 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3144 case ISD::INTRINSIC_W_CHAIN: 3145 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3146 case ISD::INTRINSIC_VOID: 3147 return LowerINTRINSIC_VOID(Op, DAG); 3148 case ISD::BSWAP: 3149 case ISD::BITREVERSE: { 3150 MVT VT = Op.getSimpleValueType(); 3151 SDLoc DL(Op); 3152 if (Subtarget.hasStdExtZbp()) { 3153 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3154 // Start with the maximum immediate value which is the bitwidth - 1. 3155 unsigned Imm = VT.getSizeInBits() - 1; 3156 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3157 if (Op.getOpcode() == ISD::BSWAP) 3158 Imm &= ~0x7U; 3159 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3160 DAG.getConstant(Imm, DL, VT)); 3161 } 3162 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3163 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3164 // Expand bitreverse to a bswap(rev8) followed by brev8. 3165 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3166 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3167 // as brev8 by an isel pattern. 3168 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3169 DAG.getConstant(7, DL, VT)); 3170 } 3171 case ISD::FSHL: 3172 case ISD::FSHR: { 3173 MVT VT = Op.getSimpleValueType(); 3174 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3175 SDLoc DL(Op); 3176 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3177 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3178 // accidentally setting the extra bit. 3179 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3180 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3181 DAG.getConstant(ShAmtWidth, DL, VT)); 3182 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3183 // instruction use different orders. fshl will return its first operand for 3184 // shift of zero, fshr will return its second operand. fsl and fsr both 3185 // return rs1 so the ISD nodes need to have different operand orders. 3186 // Shift amount is in rs2. 3187 SDValue Op0 = Op.getOperand(0); 3188 SDValue Op1 = Op.getOperand(1); 3189 unsigned Opc = RISCVISD::FSL; 3190 if (Op.getOpcode() == ISD::FSHR) { 3191 std::swap(Op0, Op1); 3192 Opc = RISCVISD::FSR; 3193 } 3194 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3195 } 3196 case ISD::TRUNCATE: 3197 // Only custom-lower vector truncates 3198 if (!Op.getSimpleValueType().isVector()) 3199 return Op; 3200 return lowerVectorTruncLike(Op, DAG); 3201 case ISD::ANY_EXTEND: 3202 case ISD::ZERO_EXTEND: 3203 if (Op.getOperand(0).getValueType().isVector() && 3204 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3205 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3206 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3207 case ISD::SIGN_EXTEND: 3208 if (Op.getOperand(0).getValueType().isVector() && 3209 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3210 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3211 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3212 case ISD::SPLAT_VECTOR_PARTS: 3213 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3214 case ISD::INSERT_VECTOR_ELT: 3215 return lowerINSERT_VECTOR_ELT(Op, DAG); 3216 case ISD::EXTRACT_VECTOR_ELT: 3217 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3218 case ISD::VSCALE: { 3219 MVT VT = Op.getSimpleValueType(); 3220 SDLoc DL(Op); 3221 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3222 // We define our scalable vector types for lmul=1 to use a 64 bit known 3223 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3224 // vscale as VLENB / 8. 3225 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3226 if (Subtarget.getRealMinVLen() < RISCV::RVVBitsPerBlock) 3227 report_fatal_error("Support for VLEN==32 is incomplete."); 3228 // We assume VLENB is a multiple of 8. We manually choose the best shift 3229 // here because SimplifyDemandedBits isn't always able to simplify it. 3230 uint64_t Val = Op.getConstantOperandVal(0); 3231 if (isPowerOf2_64(Val)) { 3232 uint64_t Log2 = Log2_64(Val); 3233 if (Log2 < 3) 3234 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3235 DAG.getConstant(3 - Log2, DL, VT)); 3236 if (Log2 > 3) 3237 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3238 DAG.getConstant(Log2 - 3, DL, VT)); 3239 return VLENB; 3240 } 3241 // If the multiplier is a multiple of 8, scale it down to avoid needing 3242 // to shift the VLENB value. 3243 if ((Val % 8) == 0) 3244 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3245 DAG.getConstant(Val / 8, DL, VT)); 3246 3247 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3248 DAG.getConstant(3, DL, VT)); 3249 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3250 } 3251 case ISD::FPOWI: { 3252 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3253 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3254 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3255 Op.getOperand(1).getValueType() == MVT::i32) { 3256 SDLoc DL(Op); 3257 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3258 SDValue Powi = 3259 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3260 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3261 DAG.getIntPtrConstant(0, DL)); 3262 } 3263 return SDValue(); 3264 } 3265 case ISD::FP_EXTEND: 3266 case ISD::FP_ROUND: 3267 if (!Op.getValueType().isVector()) 3268 return Op; 3269 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3270 case ISD::FP_TO_SINT: 3271 case ISD::FP_TO_UINT: 3272 case ISD::SINT_TO_FP: 3273 case ISD::UINT_TO_FP: { 3274 // RVV can only do fp<->int conversions to types half/double the size as 3275 // the source. We custom-lower any conversions that do two hops into 3276 // sequences. 3277 MVT VT = Op.getSimpleValueType(); 3278 if (!VT.isVector()) 3279 return Op; 3280 SDLoc DL(Op); 3281 SDValue Src = Op.getOperand(0); 3282 MVT EltVT = VT.getVectorElementType(); 3283 MVT SrcVT = Src.getSimpleValueType(); 3284 MVT SrcEltVT = SrcVT.getVectorElementType(); 3285 unsigned EltSize = EltVT.getSizeInBits(); 3286 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3287 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3288 "Unexpected vector element types"); 3289 3290 bool IsInt2FP = SrcEltVT.isInteger(); 3291 // Widening conversions 3292 if (EltSize > (2 * SrcEltSize)) { 3293 if (IsInt2FP) { 3294 // Do a regular integer sign/zero extension then convert to float. 3295 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), 3296 VT.getVectorElementCount()); 3297 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3298 ? ISD::ZERO_EXTEND 3299 : ISD::SIGN_EXTEND; 3300 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3301 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3302 } 3303 // FP2Int 3304 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3305 // Do one doubling fp_extend then complete the operation by converting 3306 // to int. 3307 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3308 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3309 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3310 } 3311 3312 // Narrowing conversions 3313 if (SrcEltSize > (2 * EltSize)) { 3314 if (IsInt2FP) { 3315 // One narrowing int_to_fp, then an fp_round. 3316 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3317 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3318 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3319 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3320 } 3321 // FP2Int 3322 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3323 // representable by the integer, the result is poison. 3324 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 3325 VT.getVectorElementCount()); 3326 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3327 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3328 } 3329 3330 // Scalable vectors can exit here. Patterns will handle equally-sized 3331 // conversions halving/doubling ones. 3332 if (!VT.isFixedLengthVector()) 3333 return Op; 3334 3335 // For fixed-length vectors we lower to a custom "VL" node. 3336 unsigned RVVOpc = 0; 3337 switch (Op.getOpcode()) { 3338 default: 3339 llvm_unreachable("Impossible opcode"); 3340 case ISD::FP_TO_SINT: 3341 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3342 break; 3343 case ISD::FP_TO_UINT: 3344 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3345 break; 3346 case ISD::SINT_TO_FP: 3347 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3348 break; 3349 case ISD::UINT_TO_FP: 3350 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3351 break; 3352 } 3353 3354 MVT ContainerVT, SrcContainerVT; 3355 // Derive the reference container type from the larger vector type. 3356 if (SrcEltSize > EltSize) { 3357 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3358 ContainerVT = 3359 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3360 } else { 3361 ContainerVT = getContainerForFixedLengthVector(VT); 3362 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3363 } 3364 3365 SDValue Mask, VL; 3366 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3367 3368 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3369 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3370 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3371 } 3372 case ISD::FP_TO_SINT_SAT: 3373 case ISD::FP_TO_UINT_SAT: 3374 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3375 case ISD::FTRUNC: 3376 case ISD::FCEIL: 3377 case ISD::FFLOOR: 3378 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3379 case ISD::FROUND: 3380 return lowerFROUND(Op, DAG); 3381 case ISD::VECREDUCE_ADD: 3382 case ISD::VECREDUCE_UMAX: 3383 case ISD::VECREDUCE_SMAX: 3384 case ISD::VECREDUCE_UMIN: 3385 case ISD::VECREDUCE_SMIN: 3386 return lowerVECREDUCE(Op, DAG); 3387 case ISD::VECREDUCE_AND: 3388 case ISD::VECREDUCE_OR: 3389 case ISD::VECREDUCE_XOR: 3390 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3391 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3392 return lowerVECREDUCE(Op, DAG); 3393 case ISD::VECREDUCE_FADD: 3394 case ISD::VECREDUCE_SEQ_FADD: 3395 case ISD::VECREDUCE_FMIN: 3396 case ISD::VECREDUCE_FMAX: 3397 return lowerFPVECREDUCE(Op, DAG); 3398 case ISD::VP_REDUCE_ADD: 3399 case ISD::VP_REDUCE_UMAX: 3400 case ISD::VP_REDUCE_SMAX: 3401 case ISD::VP_REDUCE_UMIN: 3402 case ISD::VP_REDUCE_SMIN: 3403 case ISD::VP_REDUCE_FADD: 3404 case ISD::VP_REDUCE_SEQ_FADD: 3405 case ISD::VP_REDUCE_FMIN: 3406 case ISD::VP_REDUCE_FMAX: 3407 return lowerVPREDUCE(Op, DAG); 3408 case ISD::VP_REDUCE_AND: 3409 case ISD::VP_REDUCE_OR: 3410 case ISD::VP_REDUCE_XOR: 3411 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3412 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3413 return lowerVPREDUCE(Op, DAG); 3414 case ISD::INSERT_SUBVECTOR: 3415 return lowerINSERT_SUBVECTOR(Op, DAG); 3416 case ISD::EXTRACT_SUBVECTOR: 3417 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3418 case ISD::STEP_VECTOR: 3419 return lowerSTEP_VECTOR(Op, DAG); 3420 case ISD::VECTOR_REVERSE: 3421 return lowerVECTOR_REVERSE(Op, DAG); 3422 case ISD::VECTOR_SPLICE: 3423 return lowerVECTOR_SPLICE(Op, DAG); 3424 case ISD::BUILD_VECTOR: 3425 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3426 case ISD::SPLAT_VECTOR: 3427 if (Op.getValueType().getVectorElementType() == MVT::i1) 3428 return lowerVectorMaskSplat(Op, DAG); 3429 return SDValue(); 3430 case ISD::VECTOR_SHUFFLE: 3431 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3432 case ISD::CONCAT_VECTORS: { 3433 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3434 // better than going through the stack, as the default expansion does. 3435 SDLoc DL(Op); 3436 MVT VT = Op.getSimpleValueType(); 3437 unsigned NumOpElts = 3438 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3439 SDValue Vec = DAG.getUNDEF(VT); 3440 for (const auto &OpIdx : enumerate(Op->ops())) { 3441 SDValue SubVec = OpIdx.value(); 3442 // Don't insert undef subvectors. 3443 if (SubVec.isUndef()) 3444 continue; 3445 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3446 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3447 } 3448 return Vec; 3449 } 3450 case ISD::LOAD: 3451 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3452 return V; 3453 if (Op.getValueType().isFixedLengthVector()) 3454 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3455 return Op; 3456 case ISD::STORE: 3457 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3458 return V; 3459 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3460 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3461 return Op; 3462 case ISD::MLOAD: 3463 case ISD::VP_LOAD: 3464 return lowerMaskedLoad(Op, DAG); 3465 case ISD::MSTORE: 3466 case ISD::VP_STORE: 3467 return lowerMaskedStore(Op, DAG); 3468 case ISD::SETCC: 3469 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3470 case ISD::ADD: 3471 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3472 case ISD::SUB: 3473 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3474 case ISD::MUL: 3475 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3476 case ISD::MULHS: 3477 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3478 case ISD::MULHU: 3479 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3480 case ISD::AND: 3481 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3482 RISCVISD::AND_VL); 3483 case ISD::OR: 3484 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3485 RISCVISD::OR_VL); 3486 case ISD::XOR: 3487 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3488 RISCVISD::XOR_VL); 3489 case ISD::SDIV: 3490 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3491 case ISD::SREM: 3492 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3493 case ISD::UDIV: 3494 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3495 case ISD::UREM: 3496 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3497 case ISD::SHL: 3498 case ISD::SRA: 3499 case ISD::SRL: 3500 if (Op.getSimpleValueType().isFixedLengthVector()) 3501 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3502 // This can be called for an i32 shift amount that needs to be promoted. 3503 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3504 "Unexpected custom legalisation"); 3505 return SDValue(); 3506 case ISD::SADDSAT: 3507 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3508 case ISD::UADDSAT: 3509 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3510 case ISD::SSUBSAT: 3511 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3512 case ISD::USUBSAT: 3513 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3514 case ISD::FADD: 3515 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3516 case ISD::FSUB: 3517 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3518 case ISD::FMUL: 3519 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3520 case ISD::FDIV: 3521 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3522 case ISD::FNEG: 3523 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3524 case ISD::FABS: 3525 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3526 case ISD::FSQRT: 3527 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3528 case ISD::FMA: 3529 return lowerToScalableOp(Op, DAG, RISCVISD::VFMADD_VL); 3530 case ISD::SMIN: 3531 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3532 case ISD::SMAX: 3533 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3534 case ISD::UMIN: 3535 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3536 case ISD::UMAX: 3537 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3538 case ISD::FMINNUM: 3539 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3540 case ISD::FMAXNUM: 3541 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3542 case ISD::ABS: 3543 return lowerABS(Op, DAG); 3544 case ISD::CTLZ_ZERO_UNDEF: 3545 case ISD::CTTZ_ZERO_UNDEF: 3546 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3547 case ISD::VSELECT: 3548 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3549 case ISD::FCOPYSIGN: 3550 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3551 case ISD::MGATHER: 3552 case ISD::VP_GATHER: 3553 return lowerMaskedGather(Op, DAG); 3554 case ISD::MSCATTER: 3555 case ISD::VP_SCATTER: 3556 return lowerMaskedScatter(Op, DAG); 3557 case ISD::FLT_ROUNDS_: 3558 return lowerGET_ROUNDING(Op, DAG); 3559 case ISD::SET_ROUNDING: 3560 return lowerSET_ROUNDING(Op, DAG); 3561 case ISD::EH_DWARF_CFA: 3562 return lowerEH_DWARF_CFA(Op, DAG); 3563 case ISD::VP_SELECT: 3564 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3565 case ISD::VP_MERGE: 3566 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3567 case ISD::VP_ADD: 3568 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3569 case ISD::VP_SUB: 3570 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3571 case ISD::VP_MUL: 3572 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3573 case ISD::VP_SDIV: 3574 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3575 case ISD::VP_UDIV: 3576 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3577 case ISD::VP_SREM: 3578 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3579 case ISD::VP_UREM: 3580 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3581 case ISD::VP_AND: 3582 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3583 case ISD::VP_OR: 3584 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3585 case ISD::VP_XOR: 3586 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3587 case ISD::VP_ASHR: 3588 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3589 case ISD::VP_LSHR: 3590 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3591 case ISD::VP_SHL: 3592 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3593 case ISD::VP_FADD: 3594 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3595 case ISD::VP_FSUB: 3596 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3597 case ISD::VP_FMUL: 3598 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3599 case ISD::VP_FDIV: 3600 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3601 case ISD::VP_FNEG: 3602 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3603 case ISD::VP_FMA: 3604 return lowerVPOp(Op, DAG, RISCVISD::VFMADD_VL); 3605 case ISD::VP_SIGN_EXTEND: 3606 case ISD::VP_ZERO_EXTEND: 3607 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3608 return lowerVPExtMaskOp(Op, DAG); 3609 return lowerVPOp(Op, DAG, 3610 Op.getOpcode() == ISD::VP_SIGN_EXTEND 3611 ? RISCVISD::VSEXT_VL 3612 : RISCVISD::VZEXT_VL); 3613 case ISD::VP_TRUNCATE: 3614 return lowerVectorTruncLike(Op, DAG); 3615 case ISD::VP_FP_EXTEND: 3616 case ISD::VP_FP_ROUND: 3617 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3618 case ISD::VP_FPTOSI: 3619 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL); 3620 case ISD::VP_FPTOUI: 3621 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL); 3622 case ISD::VP_SITOFP: 3623 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL); 3624 case ISD::VP_UITOFP: 3625 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL); 3626 case ISD::VP_SETCC: 3627 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3628 return lowerVPSetCCMaskOp(Op, DAG); 3629 return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL); 3630 } 3631 } 3632 3633 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3634 SelectionDAG &DAG, unsigned Flags) { 3635 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3636 } 3637 3638 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3639 SelectionDAG &DAG, unsigned Flags) { 3640 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3641 Flags); 3642 } 3643 3644 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3645 SelectionDAG &DAG, unsigned Flags) { 3646 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3647 N->getOffset(), Flags); 3648 } 3649 3650 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3651 SelectionDAG &DAG, unsigned Flags) { 3652 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3653 } 3654 3655 template <class NodeTy> 3656 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3657 bool IsLocal) const { 3658 SDLoc DL(N); 3659 EVT Ty = getPointerTy(DAG.getDataLayout()); 3660 3661 if (isPositionIndependent()) { 3662 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3663 if (IsLocal) 3664 // Use PC-relative addressing to access the symbol. This generates the 3665 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3666 // %pcrel_lo(auipc)). 3667 return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr); 3668 3669 // Use PC-relative addressing to access the GOT for this symbol, then load 3670 // the address from the GOT. This generates the pattern (PseudoLA sym), 3671 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3672 MachineFunction &MF = DAG.getMachineFunction(); 3673 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3674 MachinePointerInfo::getGOT(MF), 3675 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3676 MachineMemOperand::MOInvariant, 3677 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3678 SDValue Load = 3679 DAG.getMemIntrinsicNode(RISCVISD::LA, DL, DAG.getVTList(Ty, MVT::Other), 3680 {DAG.getEntryNode(), Addr}, Ty, MemOp); 3681 return Load; 3682 } 3683 3684 switch (getTargetMachine().getCodeModel()) { 3685 default: 3686 report_fatal_error("Unsupported code model for lowering"); 3687 case CodeModel::Small: { 3688 // Generate a sequence for accessing addresses within the first 2 GiB of 3689 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3690 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3691 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3692 SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi); 3693 return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNHi, AddrLo); 3694 } 3695 case CodeModel::Medium: { 3696 // Generate a sequence for accessing addresses within any 2GiB range within 3697 // the address space. This generates the pattern (PseudoLLA sym), which 3698 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3699 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3700 return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr); 3701 } 3702 } 3703 } 3704 3705 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3706 SelectionDAG &DAG) const { 3707 SDLoc DL(Op); 3708 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3709 assert(N->getOffset() == 0 && "unexpected offset in global node"); 3710 3711 const GlobalValue *GV = N->getGlobal(); 3712 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3713 return getAddr(N, DAG, IsLocal); 3714 } 3715 3716 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3717 SelectionDAG &DAG) const { 3718 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3719 3720 return getAddr(N, DAG); 3721 } 3722 3723 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3724 SelectionDAG &DAG) const { 3725 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3726 3727 return getAddr(N, DAG); 3728 } 3729 3730 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3731 SelectionDAG &DAG) const { 3732 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3733 3734 return getAddr(N, DAG); 3735 } 3736 3737 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3738 SelectionDAG &DAG, 3739 bool UseGOT) const { 3740 SDLoc DL(N); 3741 EVT Ty = getPointerTy(DAG.getDataLayout()); 3742 const GlobalValue *GV = N->getGlobal(); 3743 MVT XLenVT = Subtarget.getXLenVT(); 3744 3745 if (UseGOT) { 3746 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3747 // load the address from the GOT and add the thread pointer. This generates 3748 // the pattern (PseudoLA_TLS_IE sym), which expands to 3749 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3750 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3751 MachineFunction &MF = DAG.getMachineFunction(); 3752 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3753 MachinePointerInfo::getGOT(MF), 3754 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3755 MachineMemOperand::MOInvariant, 3756 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3757 SDValue Load = DAG.getMemIntrinsicNode( 3758 RISCVISD::LA_TLS_IE, DL, DAG.getVTList(Ty, MVT::Other), 3759 {DAG.getEntryNode(), Addr}, Ty, MemOp); 3760 3761 // Add the thread pointer. 3762 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3763 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3764 } 3765 3766 // Generate a sequence for accessing the address relative to the thread 3767 // pointer, with the appropriate adjustment for the thread pointer offset. 3768 // This generates the pattern 3769 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3770 SDValue AddrHi = 3771 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3772 SDValue AddrAdd = 3773 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3774 SDValue AddrLo = 3775 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3776 3777 SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi); 3778 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3779 SDValue MNAdd = 3780 DAG.getNode(RISCVISD::ADD_TPREL, DL, Ty, MNHi, TPReg, AddrAdd); 3781 return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNAdd, AddrLo); 3782 } 3783 3784 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3785 SelectionDAG &DAG) const { 3786 SDLoc DL(N); 3787 EVT Ty = getPointerTy(DAG.getDataLayout()); 3788 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3789 const GlobalValue *GV = N->getGlobal(); 3790 3791 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3792 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3793 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3794 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3795 SDValue Load = DAG.getNode(RISCVISD::LA_TLS_GD, DL, Ty, Addr); 3796 3797 // Prepare argument list to generate call. 3798 ArgListTy Args; 3799 ArgListEntry Entry; 3800 Entry.Node = Load; 3801 Entry.Ty = CallTy; 3802 Args.push_back(Entry); 3803 3804 // Setup call to __tls_get_addr. 3805 TargetLowering::CallLoweringInfo CLI(DAG); 3806 CLI.setDebugLoc(DL) 3807 .setChain(DAG.getEntryNode()) 3808 .setLibCallee(CallingConv::C, CallTy, 3809 DAG.getExternalSymbol("__tls_get_addr", Ty), 3810 std::move(Args)); 3811 3812 return LowerCallTo(CLI).first; 3813 } 3814 3815 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3816 SelectionDAG &DAG) const { 3817 SDLoc DL(Op); 3818 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3819 assert(N->getOffset() == 0 && "unexpected offset in global node"); 3820 3821 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3822 3823 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3824 CallingConv::GHC) 3825 report_fatal_error("In GHC calling convention TLS is not supported"); 3826 3827 SDValue Addr; 3828 switch (Model) { 3829 case TLSModel::LocalExec: 3830 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3831 break; 3832 case TLSModel::InitialExec: 3833 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3834 break; 3835 case TLSModel::LocalDynamic: 3836 case TLSModel::GeneralDynamic: 3837 Addr = getDynamicTLSAddr(N, DAG); 3838 break; 3839 } 3840 3841 return Addr; 3842 } 3843 3844 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3845 SDValue CondV = Op.getOperand(0); 3846 SDValue TrueV = Op.getOperand(1); 3847 SDValue FalseV = Op.getOperand(2); 3848 SDLoc DL(Op); 3849 MVT VT = Op.getSimpleValueType(); 3850 MVT XLenVT = Subtarget.getXLenVT(); 3851 3852 // Lower vector SELECTs to VSELECTs by splatting the condition. 3853 if (VT.isVector()) { 3854 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3855 SDValue CondSplat = VT.isScalableVector() 3856 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3857 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3858 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3859 } 3860 3861 // If the result type is XLenVT and CondV is the output of a SETCC node 3862 // which also operated on XLenVT inputs, then merge the SETCC node into the 3863 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3864 // compare+branch instructions. i.e.: 3865 // (select (setcc lhs, rhs, cc), truev, falsev) 3866 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3867 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3868 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3869 SDValue LHS = CondV.getOperand(0); 3870 SDValue RHS = CondV.getOperand(1); 3871 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3872 ISD::CondCode CCVal = CC->get(); 3873 3874 // Special case for a select of 2 constants that have a diffence of 1. 3875 // Normally this is done by DAGCombine, but if the select is introduced by 3876 // type legalization or op legalization, we miss it. Restricting to SETLT 3877 // case for now because that is what signed saturating add/sub need. 3878 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3879 // but we would probably want to swap the true/false values if the condition 3880 // is SETGE/SETLE to avoid an XORI. 3881 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3882 CCVal == ISD::SETLT) { 3883 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3884 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3885 if (TrueVal - 1 == FalseVal) 3886 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3887 if (TrueVal + 1 == FalseVal) 3888 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3889 } 3890 3891 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3892 3893 SDValue TargetCC = DAG.getCondCode(CCVal); 3894 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3895 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3896 } 3897 3898 // Otherwise: 3899 // (select condv, truev, falsev) 3900 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3901 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3902 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3903 3904 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3905 3906 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3907 } 3908 3909 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3910 SDValue CondV = Op.getOperand(1); 3911 SDLoc DL(Op); 3912 MVT XLenVT = Subtarget.getXLenVT(); 3913 3914 if (CondV.getOpcode() == ISD::SETCC && 3915 CondV.getOperand(0).getValueType() == XLenVT) { 3916 SDValue LHS = CondV.getOperand(0); 3917 SDValue RHS = CondV.getOperand(1); 3918 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3919 3920 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3921 3922 SDValue TargetCC = DAG.getCondCode(CCVal); 3923 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3924 LHS, RHS, TargetCC, Op.getOperand(2)); 3925 } 3926 3927 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3928 CondV, DAG.getConstant(0, DL, XLenVT), 3929 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3930 } 3931 3932 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3933 MachineFunction &MF = DAG.getMachineFunction(); 3934 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3935 3936 SDLoc DL(Op); 3937 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3938 getPointerTy(MF.getDataLayout())); 3939 3940 // vastart just stores the address of the VarArgsFrameIndex slot into the 3941 // memory location argument. 3942 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3943 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3944 MachinePointerInfo(SV)); 3945 } 3946 3947 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3948 SelectionDAG &DAG) const { 3949 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3950 MachineFunction &MF = DAG.getMachineFunction(); 3951 MachineFrameInfo &MFI = MF.getFrameInfo(); 3952 MFI.setFrameAddressIsTaken(true); 3953 Register FrameReg = RI.getFrameRegister(MF); 3954 int XLenInBytes = Subtarget.getXLen() / 8; 3955 3956 EVT VT = Op.getValueType(); 3957 SDLoc DL(Op); 3958 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3959 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3960 while (Depth--) { 3961 int Offset = -(XLenInBytes * 2); 3962 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3963 DAG.getIntPtrConstant(Offset, DL)); 3964 FrameAddr = 3965 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3966 } 3967 return FrameAddr; 3968 } 3969 3970 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3971 SelectionDAG &DAG) const { 3972 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3973 MachineFunction &MF = DAG.getMachineFunction(); 3974 MachineFrameInfo &MFI = MF.getFrameInfo(); 3975 MFI.setReturnAddressIsTaken(true); 3976 MVT XLenVT = Subtarget.getXLenVT(); 3977 int XLenInBytes = Subtarget.getXLen() / 8; 3978 3979 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3980 return SDValue(); 3981 3982 EVT VT = Op.getValueType(); 3983 SDLoc DL(Op); 3984 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3985 if (Depth) { 3986 int Off = -XLenInBytes; 3987 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3988 SDValue Offset = DAG.getConstant(Off, DL, VT); 3989 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3990 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3991 MachinePointerInfo()); 3992 } 3993 3994 // Return the value of the return address register, marking it an implicit 3995 // live-in. 3996 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3997 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3998 } 3999 4000 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 4001 SelectionDAG &DAG) const { 4002 SDLoc DL(Op); 4003 SDValue Lo = Op.getOperand(0); 4004 SDValue Hi = Op.getOperand(1); 4005 SDValue Shamt = Op.getOperand(2); 4006 EVT VT = Lo.getValueType(); 4007 4008 // if Shamt-XLEN < 0: // Shamt < XLEN 4009 // Lo = Lo << Shamt 4010 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 4011 // else: 4012 // Lo = 0 4013 // Hi = Lo << (Shamt-XLEN) 4014 4015 SDValue Zero = DAG.getConstant(0, DL, VT); 4016 SDValue One = DAG.getConstant(1, DL, VT); 4017 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4018 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4019 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4020 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4021 4022 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 4023 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 4024 SDValue ShiftRightLo = 4025 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 4026 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 4027 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 4028 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 4029 4030 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4031 4032 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 4033 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4034 4035 SDValue Parts[2] = {Lo, Hi}; 4036 return DAG.getMergeValues(Parts, DL); 4037 } 4038 4039 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 4040 bool IsSRA) const { 4041 SDLoc DL(Op); 4042 SDValue Lo = Op.getOperand(0); 4043 SDValue Hi = Op.getOperand(1); 4044 SDValue Shamt = Op.getOperand(2); 4045 EVT VT = Lo.getValueType(); 4046 4047 // SRA expansion: 4048 // if Shamt-XLEN < 0: // Shamt < XLEN 4049 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4050 // Hi = Hi >>s Shamt 4051 // else: 4052 // Lo = Hi >>s (Shamt-XLEN); 4053 // Hi = Hi >>s (XLEN-1) 4054 // 4055 // SRL expansion: 4056 // if Shamt-XLEN < 0: // Shamt < XLEN 4057 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4058 // Hi = Hi >>u Shamt 4059 // else: 4060 // Lo = Hi >>u (Shamt-XLEN); 4061 // Hi = 0; 4062 4063 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 4064 4065 SDValue Zero = DAG.getConstant(0, DL, VT); 4066 SDValue One = DAG.getConstant(1, DL, VT); 4067 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4068 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4069 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4070 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4071 4072 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 4073 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 4074 SDValue ShiftLeftHi = 4075 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 4076 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 4077 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 4078 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 4079 SDValue HiFalse = 4080 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 4081 4082 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4083 4084 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 4085 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4086 4087 SDValue Parts[2] = {Lo, Hi}; 4088 return DAG.getMergeValues(Parts, DL); 4089 } 4090 4091 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 4092 // legal equivalently-sized i8 type, so we can use that as a go-between. 4093 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4094 SelectionDAG &DAG) const { 4095 SDLoc DL(Op); 4096 MVT VT = Op.getSimpleValueType(); 4097 SDValue SplatVal = Op.getOperand(0); 4098 // All-zeros or all-ones splats are handled specially. 4099 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4100 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4101 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4102 } 4103 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4104 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4105 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4106 } 4107 MVT XLenVT = Subtarget.getXLenVT(); 4108 assert(SplatVal.getValueType() == XLenVT && 4109 "Unexpected type for i1 splat value"); 4110 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4111 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4112 DAG.getConstant(1, DL, XLenVT)); 4113 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4114 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4115 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4116 } 4117 4118 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4119 // illegal (currently only vXi64 RV32). 4120 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4121 // them to VMV_V_X_VL. 4122 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4123 SelectionDAG &DAG) const { 4124 SDLoc DL(Op); 4125 MVT VecVT = Op.getSimpleValueType(); 4126 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4127 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4128 4129 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4130 SDValue Lo = Op.getOperand(0); 4131 SDValue Hi = Op.getOperand(1); 4132 4133 if (VecVT.isFixedLengthVector()) { 4134 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4135 SDLoc DL(Op); 4136 SDValue Mask, VL; 4137 std::tie(Mask, VL) = 4138 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4139 4140 SDValue Res = 4141 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4142 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4143 } 4144 4145 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4146 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4147 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4148 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4149 // node in order to try and match RVV vector/scalar instructions. 4150 if ((LoC >> 31) == HiC) 4151 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4152 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4153 } 4154 4155 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4156 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4157 isa<ConstantSDNode>(Hi.getOperand(1)) && 4158 Hi.getConstantOperandVal(1) == 31) 4159 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4160 DAG.getRegister(RISCV::X0, MVT::i32)); 4161 4162 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4163 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4164 DAG.getUNDEF(VecVT), Lo, Hi, 4165 DAG.getRegister(RISCV::X0, MVT::i32)); 4166 } 4167 4168 // Custom-lower extensions from mask vectors by using a vselect either with 1 4169 // for zero/any-extension or -1 for sign-extension: 4170 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4171 // Note that any-extension is lowered identically to zero-extension. 4172 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4173 int64_t ExtTrueVal) const { 4174 SDLoc DL(Op); 4175 MVT VecVT = Op.getSimpleValueType(); 4176 SDValue Src = Op.getOperand(0); 4177 // Only custom-lower extensions from mask types 4178 assert(Src.getValueType().isVector() && 4179 Src.getValueType().getVectorElementType() == MVT::i1); 4180 4181 if (VecVT.isScalableVector()) { 4182 SDValue SplatZero = DAG.getConstant(0, DL, VecVT); 4183 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT); 4184 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4185 } 4186 4187 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4188 MVT I1ContainerVT = 4189 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4190 4191 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4192 4193 SDValue Mask, VL; 4194 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4195 4196 MVT XLenVT = Subtarget.getXLenVT(); 4197 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4198 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4199 4200 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4201 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4202 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4203 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4204 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4205 SplatTrueVal, SplatZero, VL); 4206 4207 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4208 } 4209 4210 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4211 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4212 MVT ExtVT = Op.getSimpleValueType(); 4213 // Only custom-lower extensions from fixed-length vector types. 4214 if (!ExtVT.isFixedLengthVector()) 4215 return Op; 4216 MVT VT = Op.getOperand(0).getSimpleValueType(); 4217 // Grab the canonical container type for the extended type. Infer the smaller 4218 // type from that to ensure the same number of vector elements, as we know 4219 // the LMUL will be sufficient to hold the smaller type. 4220 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4221 // Get the extended container type manually to ensure the same number of 4222 // vector elements between source and dest. 4223 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4224 ContainerExtVT.getVectorElementCount()); 4225 4226 SDValue Op1 = 4227 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4228 4229 SDLoc DL(Op); 4230 SDValue Mask, VL; 4231 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4232 4233 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4234 4235 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4236 } 4237 4238 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4239 // setcc operation: 4240 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4241 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op, 4242 SelectionDAG &DAG) const { 4243 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4244 SDLoc DL(Op); 4245 EVT MaskVT = Op.getValueType(); 4246 // Only expect to custom-lower truncations to mask types 4247 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4248 "Unexpected type for vector mask lowering"); 4249 SDValue Src = Op.getOperand(0); 4250 MVT VecVT = Src.getSimpleValueType(); 4251 SDValue Mask, VL; 4252 if (IsVPTrunc) { 4253 Mask = Op.getOperand(1); 4254 VL = Op.getOperand(2); 4255 } 4256 // If this is a fixed vector, we need to convert it to a scalable vector. 4257 MVT ContainerVT = VecVT; 4258 4259 if (VecVT.isFixedLengthVector()) { 4260 ContainerVT = getContainerForFixedLengthVector(VecVT); 4261 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4262 if (IsVPTrunc) { 4263 MVT MaskContainerVT = 4264 getContainerForFixedLengthVector(Mask.getSimpleValueType()); 4265 Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget); 4266 } 4267 } 4268 4269 if (!IsVPTrunc) { 4270 std::tie(Mask, VL) = 4271 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4272 } 4273 4274 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4275 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4276 4277 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4278 DAG.getUNDEF(ContainerVT), SplatOne, VL); 4279 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4280 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4281 4282 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4283 SDValue Trunc = 4284 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4285 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4286 DAG.getCondCode(ISD::SETNE), Mask, VL); 4287 if (MaskVT.isFixedLengthVector()) 4288 Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4289 return Trunc; 4290 } 4291 4292 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op, 4293 SelectionDAG &DAG) const { 4294 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4295 SDLoc DL(Op); 4296 4297 MVT VT = Op.getSimpleValueType(); 4298 // Only custom-lower vector truncates 4299 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4300 4301 // Truncates to mask types are handled differently 4302 if (VT.getVectorElementType() == MVT::i1) 4303 return lowerVectorMaskTruncLike(Op, DAG); 4304 4305 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 4306 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 4307 // truncate by one power of two at a time. 4308 MVT DstEltVT = VT.getVectorElementType(); 4309 4310 SDValue Src = Op.getOperand(0); 4311 MVT SrcVT = Src.getSimpleValueType(); 4312 MVT SrcEltVT = SrcVT.getVectorElementType(); 4313 4314 assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) && 4315 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 4316 "Unexpected vector truncate lowering"); 4317 4318 MVT ContainerVT = SrcVT; 4319 SDValue Mask, VL; 4320 if (IsVPTrunc) { 4321 Mask = Op.getOperand(1); 4322 VL = Op.getOperand(2); 4323 } 4324 if (SrcVT.isFixedLengthVector()) { 4325 ContainerVT = getContainerForFixedLengthVector(SrcVT); 4326 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4327 if (IsVPTrunc) { 4328 MVT MaskVT = getMaskTypeFor(ContainerVT); 4329 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4330 } 4331 } 4332 4333 SDValue Result = Src; 4334 if (!IsVPTrunc) { 4335 std::tie(Mask, VL) = 4336 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4337 } 4338 4339 LLVMContext &Context = *DAG.getContext(); 4340 const ElementCount Count = ContainerVT.getVectorElementCount(); 4341 do { 4342 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 4343 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 4344 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 4345 Mask, VL); 4346 } while (SrcEltVT != DstEltVT); 4347 4348 if (SrcVT.isFixedLengthVector()) 4349 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4350 4351 return Result; 4352 } 4353 4354 SDValue 4355 RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op, 4356 SelectionDAG &DAG) const { 4357 bool IsVP = 4358 Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND; 4359 bool IsExtend = 4360 Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND; 4361 // RVV can only do truncate fp to types half the size as the source. We 4362 // custom-lower f64->f16 rounds via RVV's round-to-odd float 4363 // conversion instruction. 4364 SDLoc DL(Op); 4365 MVT VT = Op.getSimpleValueType(); 4366 4367 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4368 4369 SDValue Src = Op.getOperand(0); 4370 MVT SrcVT = Src.getSimpleValueType(); 4371 4372 bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 || 4373 SrcVT.getVectorElementType() != MVT::f16); 4374 bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 || 4375 SrcVT.getVectorElementType() != MVT::f64); 4376 4377 bool IsDirectConv = IsDirectExtend || IsDirectTrunc; 4378 4379 // Prepare any fixed-length vector operands. 4380 MVT ContainerVT = VT; 4381 SDValue Mask, VL; 4382 if (IsVP) { 4383 Mask = Op.getOperand(1); 4384 VL = Op.getOperand(2); 4385 } 4386 if (VT.isFixedLengthVector()) { 4387 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 4388 ContainerVT = 4389 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 4390 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 4391 if (IsVP) { 4392 MVT MaskVT = getMaskTypeFor(ContainerVT); 4393 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4394 } 4395 } 4396 4397 if (!IsVP) 4398 std::tie(Mask, VL) = 4399 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4400 4401 unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL; 4402 4403 if (IsDirectConv) { 4404 Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL); 4405 if (VT.isFixedLengthVector()) 4406 Src = convertFromScalableVector(VT, Src, DAG, Subtarget); 4407 return Src; 4408 } 4409 4410 unsigned InterConvOpc = 4411 IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL; 4412 4413 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 4414 SDValue IntermediateConv = 4415 DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL); 4416 SDValue Result = 4417 DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL); 4418 if (VT.isFixedLengthVector()) 4419 return convertFromScalableVector(VT, Result, DAG, Subtarget); 4420 return Result; 4421 } 4422 4423 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4424 // first position of a vector, and that vector is slid up to the insert index. 4425 // By limiting the active vector length to index+1 and merging with the 4426 // original vector (with an undisturbed tail policy for elements >= VL), we 4427 // achieve the desired result of leaving all elements untouched except the one 4428 // at VL-1, which is replaced with the desired value. 4429 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4430 SelectionDAG &DAG) const { 4431 SDLoc DL(Op); 4432 MVT VecVT = Op.getSimpleValueType(); 4433 SDValue Vec = Op.getOperand(0); 4434 SDValue Val = Op.getOperand(1); 4435 SDValue Idx = Op.getOperand(2); 4436 4437 if (VecVT.getVectorElementType() == MVT::i1) { 4438 // FIXME: For now we just promote to an i8 vector and insert into that, 4439 // but this is probably not optimal. 4440 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4441 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4442 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4443 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4444 } 4445 4446 MVT ContainerVT = VecVT; 4447 // If the operand is a fixed-length vector, convert to a scalable one. 4448 if (VecVT.isFixedLengthVector()) { 4449 ContainerVT = getContainerForFixedLengthVector(VecVT); 4450 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4451 } 4452 4453 MVT XLenVT = Subtarget.getXLenVT(); 4454 4455 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4456 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4457 // Even i64-element vectors on RV32 can be lowered without scalar 4458 // legalization if the most-significant 32 bits of the value are not affected 4459 // by the sign-extension of the lower 32 bits. 4460 // TODO: We could also catch sign extensions of a 32-bit value. 4461 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4462 const auto *CVal = cast<ConstantSDNode>(Val); 4463 if (isInt<32>(CVal->getSExtValue())) { 4464 IsLegalInsert = true; 4465 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4466 } 4467 } 4468 4469 SDValue Mask, VL; 4470 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4471 4472 SDValue ValInVec; 4473 4474 if (IsLegalInsert) { 4475 unsigned Opc = 4476 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4477 if (isNullConstant(Idx)) { 4478 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4479 if (!VecVT.isFixedLengthVector()) 4480 return Vec; 4481 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4482 } 4483 ValInVec = 4484 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4485 } else { 4486 // On RV32, i64-element vectors must be specially handled to place the 4487 // value at element 0, by using two vslide1up instructions in sequence on 4488 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4489 // this. 4490 SDValue One = DAG.getConstant(1, DL, XLenVT); 4491 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4492 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4493 MVT I32ContainerVT = 4494 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4495 SDValue I32Mask = 4496 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4497 // Limit the active VL to two. 4498 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4499 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4500 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4501 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4502 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4503 // First slide in the hi value, then the lo in underneath it. 4504 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4505 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4506 I32Mask, InsertI64VL); 4507 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4508 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4509 I32Mask, InsertI64VL); 4510 // Bitcast back to the right container type. 4511 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4512 } 4513 4514 // Now that the value is in a vector, slide it into position. 4515 SDValue InsertVL = 4516 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4517 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4518 ValInVec, Idx, Mask, InsertVL); 4519 if (!VecVT.isFixedLengthVector()) 4520 return Slideup; 4521 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4522 } 4523 4524 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4525 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4526 // types this is done using VMV_X_S to allow us to glean information about the 4527 // sign bits of the result. 4528 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4529 SelectionDAG &DAG) const { 4530 SDLoc DL(Op); 4531 SDValue Idx = Op.getOperand(1); 4532 SDValue Vec = Op.getOperand(0); 4533 EVT EltVT = Op.getValueType(); 4534 MVT VecVT = Vec.getSimpleValueType(); 4535 MVT XLenVT = Subtarget.getXLenVT(); 4536 4537 if (VecVT.getVectorElementType() == MVT::i1) { 4538 if (VecVT.isFixedLengthVector()) { 4539 unsigned NumElts = VecVT.getVectorNumElements(); 4540 if (NumElts >= 8) { 4541 MVT WideEltVT; 4542 unsigned WidenVecLen; 4543 SDValue ExtractElementIdx; 4544 SDValue ExtractBitIdx; 4545 unsigned MaxEEW = Subtarget.getELEN(); 4546 MVT LargestEltVT = MVT::getIntegerVT( 4547 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4548 if (NumElts <= LargestEltVT.getSizeInBits()) { 4549 assert(isPowerOf2_32(NumElts) && 4550 "the number of elements should be power of 2"); 4551 WideEltVT = MVT::getIntegerVT(NumElts); 4552 WidenVecLen = 1; 4553 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4554 ExtractBitIdx = Idx; 4555 } else { 4556 WideEltVT = LargestEltVT; 4557 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4558 // extract element index = index / element width 4559 ExtractElementIdx = DAG.getNode( 4560 ISD::SRL, DL, XLenVT, Idx, 4561 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4562 // mask bit index = index % element width 4563 ExtractBitIdx = DAG.getNode( 4564 ISD::AND, DL, XLenVT, Idx, 4565 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4566 } 4567 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4568 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4569 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4570 Vec, ExtractElementIdx); 4571 // Extract the bit from GPR. 4572 SDValue ShiftRight = 4573 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4574 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4575 DAG.getConstant(1, DL, XLenVT)); 4576 } 4577 } 4578 // Otherwise, promote to an i8 vector and extract from that. 4579 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4580 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4581 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4582 } 4583 4584 // If this is a fixed vector, we need to convert it to a scalable vector. 4585 MVT ContainerVT = VecVT; 4586 if (VecVT.isFixedLengthVector()) { 4587 ContainerVT = getContainerForFixedLengthVector(VecVT); 4588 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4589 } 4590 4591 // If the index is 0, the vector is already in the right position. 4592 if (!isNullConstant(Idx)) { 4593 // Use a VL of 1 to avoid processing more elements than we need. 4594 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4595 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 4596 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4597 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4598 } 4599 4600 if (!EltVT.isInteger()) { 4601 // Floating-point extracts are handled in TableGen. 4602 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4603 DAG.getConstant(0, DL, XLenVT)); 4604 } 4605 4606 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4607 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4608 } 4609 4610 // Some RVV intrinsics may claim that they want an integer operand to be 4611 // promoted or expanded. 4612 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG, 4613 const RISCVSubtarget &Subtarget) { 4614 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4615 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4616 "Unexpected opcode"); 4617 4618 if (!Subtarget.hasVInstructions()) 4619 return SDValue(); 4620 4621 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4622 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4623 SDLoc DL(Op); 4624 4625 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4626 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4627 if (!II || !II->hasScalarOperand()) 4628 return SDValue(); 4629 4630 unsigned SplatOp = II->ScalarOperand + 1 + HasChain; 4631 assert(SplatOp < Op.getNumOperands()); 4632 4633 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4634 SDValue &ScalarOp = Operands[SplatOp]; 4635 MVT OpVT = ScalarOp.getSimpleValueType(); 4636 MVT XLenVT = Subtarget.getXLenVT(); 4637 4638 // If this isn't a scalar, or its type is XLenVT we're done. 4639 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4640 return SDValue(); 4641 4642 // Simplest case is that the operand needs to be promoted to XLenVT. 4643 if (OpVT.bitsLT(XLenVT)) { 4644 // If the operand is a constant, sign extend to increase our chances 4645 // of being able to use a .vi instruction. ANY_EXTEND would become a 4646 // a zero extend and the simm5 check in isel would fail. 4647 // FIXME: Should we ignore the upper bits in isel instead? 4648 unsigned ExtOpc = 4649 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4650 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4651 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4652 } 4653 4654 // Use the previous operand to get the vXi64 VT. The result might be a mask 4655 // VT for compares. Using the previous operand assumes that the previous 4656 // operand will never have a smaller element size than a scalar operand and 4657 // that a widening operation never uses SEW=64. 4658 // NOTE: If this fails the below assert, we can probably just find the 4659 // element count from any operand or result and use it to construct the VT. 4660 assert(II->ScalarOperand > 0 && "Unexpected splat operand!"); 4661 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4662 4663 // The more complex case is when the scalar is larger than XLenVT. 4664 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4665 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4666 4667 // If this is a sign-extended 32-bit value, we can truncate it and rely on the 4668 // instruction to sign-extend since SEW>XLEN. 4669 if (DAG.ComputeNumSignBits(ScalarOp) > 32) { 4670 ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp); 4671 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4672 } 4673 4674 switch (IntNo) { 4675 case Intrinsic::riscv_vslide1up: 4676 case Intrinsic::riscv_vslide1down: 4677 case Intrinsic::riscv_vslide1up_mask: 4678 case Intrinsic::riscv_vslide1down_mask: { 4679 // We need to special case these when the scalar is larger than XLen. 4680 unsigned NumOps = Op.getNumOperands(); 4681 bool IsMasked = NumOps == 7; 4682 4683 // Convert the vector source to the equivalent nxvXi32 vector. 4684 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4685 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4686 4687 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4688 DAG.getConstant(0, DL, XLenVT)); 4689 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4690 DAG.getConstant(1, DL, XLenVT)); 4691 4692 // Double the VL since we halved SEW. 4693 SDValue AVL = getVLOperand(Op); 4694 SDValue I32VL; 4695 4696 // Optimize for constant AVL 4697 if (isa<ConstantSDNode>(AVL)) { 4698 unsigned EltSize = VT.getScalarSizeInBits(); 4699 unsigned MinSize = VT.getSizeInBits().getKnownMinValue(); 4700 4701 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 4702 unsigned MaxVLMAX = 4703 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 4704 4705 unsigned VectorBitsMin = Subtarget.getRealMinVLen(); 4706 unsigned MinVLMAX = 4707 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize); 4708 4709 uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue(); 4710 if (AVLInt <= MinVLMAX) { 4711 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT); 4712 } else if (AVLInt >= 2 * MaxVLMAX) { 4713 // Just set vl to VLMAX in this situation 4714 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT); 4715 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4716 unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits()); 4717 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4718 SDValue SETVLMAX = DAG.getTargetConstant( 4719 Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32); 4720 I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW, 4721 LMUL); 4722 } else { 4723 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl 4724 // is related to the hardware implementation. 4725 // So let the following code handle 4726 } 4727 } 4728 if (!I32VL) { 4729 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT); 4730 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4731 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits()); 4732 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4733 SDValue SETVL = 4734 DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32); 4735 // Using vsetvli instruction to get actually used length which related to 4736 // the hardware implementation 4737 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL, 4738 SEW, LMUL); 4739 I32VL = 4740 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4741 } 4742 4743 SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG); 4744 4745 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4746 // instructions. 4747 SDValue Passthru; 4748 if (IsMasked) 4749 Passthru = DAG.getUNDEF(I32VT); 4750 else 4751 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4752 4753 if (IntNo == Intrinsic::riscv_vslide1up || 4754 IntNo == Intrinsic::riscv_vslide1up_mask) { 4755 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4756 ScalarHi, I32Mask, I32VL); 4757 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4758 ScalarLo, I32Mask, I32VL); 4759 } else { 4760 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4761 ScalarLo, I32Mask, I32VL); 4762 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4763 ScalarHi, I32Mask, I32VL); 4764 } 4765 4766 // Convert back to nxvXi64. 4767 Vec = DAG.getBitcast(VT, Vec); 4768 4769 if (!IsMasked) 4770 return Vec; 4771 // Apply mask after the operation. 4772 SDValue Mask = Operands[NumOps - 3]; 4773 SDValue MaskedOff = Operands[1]; 4774 // Assume Policy operand is the last operand. 4775 uint64_t Policy = 4776 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4777 // We don't need to select maskedoff if it's undef. 4778 if (MaskedOff.isUndef()) 4779 return Vec; 4780 // TAMU 4781 if (Policy == RISCVII::TAIL_AGNOSTIC) 4782 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4783 AVL); 4784 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4785 // It's fine because vmerge does not care mask policy. 4786 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, 4787 AVL); 4788 } 4789 } 4790 4791 // We need to convert the scalar to a splat vector. 4792 SDValue VL = getVLOperand(Op); 4793 assert(VL.getValueType() == XLenVT); 4794 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4795 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4796 } 4797 4798 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4799 SelectionDAG &DAG) const { 4800 unsigned IntNo = Op.getConstantOperandVal(0); 4801 SDLoc DL(Op); 4802 MVT XLenVT = Subtarget.getXLenVT(); 4803 4804 switch (IntNo) { 4805 default: 4806 break; // Don't custom lower most intrinsics. 4807 case Intrinsic::thread_pointer: { 4808 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4809 return DAG.getRegister(RISCV::X4, PtrVT); 4810 } 4811 case Intrinsic::riscv_orc_b: 4812 case Intrinsic::riscv_brev8: { 4813 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4814 unsigned Opc = 4815 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4816 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4817 DAG.getConstant(7, DL, XLenVT)); 4818 } 4819 case Intrinsic::riscv_grev: 4820 case Intrinsic::riscv_gorc: { 4821 unsigned Opc = 4822 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4823 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4824 } 4825 case Intrinsic::riscv_zip: 4826 case Intrinsic::riscv_unzip: { 4827 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4828 // For i32 the immediate is 15. For i64 the immediate is 31. 4829 unsigned Opc = 4830 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4831 unsigned BitWidth = Op.getValueSizeInBits(); 4832 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4833 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4834 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4835 } 4836 case Intrinsic::riscv_shfl: 4837 case Intrinsic::riscv_unshfl: { 4838 unsigned Opc = 4839 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4840 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4841 } 4842 case Intrinsic::riscv_bcompress: 4843 case Intrinsic::riscv_bdecompress: { 4844 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4845 : RISCVISD::BDECOMPRESS; 4846 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4847 } 4848 case Intrinsic::riscv_bfp: 4849 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4850 Op.getOperand(2)); 4851 case Intrinsic::riscv_fsl: 4852 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4853 Op.getOperand(2), Op.getOperand(3)); 4854 case Intrinsic::riscv_fsr: 4855 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4856 Op.getOperand(2), Op.getOperand(3)); 4857 case Intrinsic::riscv_vmv_x_s: 4858 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4859 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4860 Op.getOperand(1)); 4861 case Intrinsic::riscv_vmv_v_x: 4862 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4863 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4864 Subtarget); 4865 case Intrinsic::riscv_vfmv_v_f: 4866 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4867 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4868 case Intrinsic::riscv_vmv_s_x: { 4869 SDValue Scalar = Op.getOperand(2); 4870 4871 if (Scalar.getValueType().bitsLE(XLenVT)) { 4872 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4873 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4874 Op.getOperand(1), Scalar, Op.getOperand(3)); 4875 } 4876 4877 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4878 4879 // This is an i64 value that lives in two scalar registers. We have to 4880 // insert this in a convoluted way. First we build vXi64 splat containing 4881 // the two values that we assemble using some bit math. Next we'll use 4882 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4883 // to merge element 0 from our splat into the source vector. 4884 // FIXME: This is probably not the best way to do this, but it is 4885 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4886 // point. 4887 // sw lo, (a0) 4888 // sw hi, 4(a0) 4889 // vlse vX, (a0) 4890 // 4891 // vid.v vVid 4892 // vmseq.vx mMask, vVid, 0 4893 // vmerge.vvm vDest, vSrc, vVal, mMask 4894 MVT VT = Op.getSimpleValueType(); 4895 SDValue Vec = Op.getOperand(1); 4896 SDValue VL = getVLOperand(Op); 4897 4898 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4899 if (Op.getOperand(1).isUndef()) 4900 return SplattedVal; 4901 SDValue SplattedIdx = 4902 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4903 DAG.getConstant(0, DL, MVT::i32), VL); 4904 4905 MVT MaskVT = getMaskTypeFor(VT); 4906 SDValue Mask = getAllOnesMask(VT, VL, DL, DAG); 4907 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4908 SDValue SelectCond = 4909 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4910 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4911 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4912 Vec, VL); 4913 } 4914 } 4915 4916 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4917 } 4918 4919 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4920 SelectionDAG &DAG) const { 4921 unsigned IntNo = Op.getConstantOperandVal(1); 4922 switch (IntNo) { 4923 default: 4924 break; 4925 case Intrinsic::riscv_masked_strided_load: { 4926 SDLoc DL(Op); 4927 MVT XLenVT = Subtarget.getXLenVT(); 4928 4929 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4930 // the selection of the masked intrinsics doesn't do this for us. 4931 SDValue Mask = Op.getOperand(5); 4932 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4933 4934 MVT VT = Op->getSimpleValueType(0); 4935 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4936 4937 SDValue PassThru = Op.getOperand(2); 4938 if (!IsUnmasked) { 4939 MVT MaskVT = getMaskTypeFor(ContainerVT); 4940 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4941 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4942 } 4943 4944 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4945 4946 SDValue IntID = DAG.getTargetConstant( 4947 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4948 XLenVT); 4949 4950 auto *Load = cast<MemIntrinsicSDNode>(Op); 4951 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4952 if (IsUnmasked) 4953 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4954 else 4955 Ops.push_back(PassThru); 4956 Ops.push_back(Op.getOperand(3)); // Ptr 4957 Ops.push_back(Op.getOperand(4)); // Stride 4958 if (!IsUnmasked) 4959 Ops.push_back(Mask); 4960 Ops.push_back(VL); 4961 if (!IsUnmasked) { 4962 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4963 Ops.push_back(Policy); 4964 } 4965 4966 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4967 SDValue Result = 4968 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4969 Load->getMemoryVT(), Load->getMemOperand()); 4970 SDValue Chain = Result.getValue(1); 4971 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4972 return DAG.getMergeValues({Result, Chain}, DL); 4973 } 4974 case Intrinsic::riscv_seg2_load: 4975 case Intrinsic::riscv_seg3_load: 4976 case Intrinsic::riscv_seg4_load: 4977 case Intrinsic::riscv_seg5_load: 4978 case Intrinsic::riscv_seg6_load: 4979 case Intrinsic::riscv_seg7_load: 4980 case Intrinsic::riscv_seg8_load: { 4981 SDLoc DL(Op); 4982 static const Intrinsic::ID VlsegInts[7] = { 4983 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 4984 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 4985 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 4986 Intrinsic::riscv_vlseg8}; 4987 unsigned NF = Op->getNumValues() - 1; 4988 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 4989 MVT XLenVT = Subtarget.getXLenVT(); 4990 MVT VT = Op->getSimpleValueType(0); 4991 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4992 4993 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4994 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 4995 auto *Load = cast<MemIntrinsicSDNode>(Op); 4996 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 4997 ContainerVTs.push_back(MVT::Other); 4998 SDVTList VTs = DAG.getVTList(ContainerVTs); 4999 SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID}; 5000 Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT)); 5001 Ops.push_back(Op.getOperand(2)); 5002 Ops.push_back(VL); 5003 SDValue Result = 5004 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5005 Load->getMemoryVT(), Load->getMemOperand()); 5006 SmallVector<SDValue, 9> Results; 5007 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 5008 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 5009 DAG, Subtarget)); 5010 Results.push_back(Result.getValue(NF)); 5011 return DAG.getMergeValues(Results, DL); 5012 } 5013 } 5014 5015 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 5016 } 5017 5018 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 5019 SelectionDAG &DAG) const { 5020 unsigned IntNo = Op.getConstantOperandVal(1); 5021 switch (IntNo) { 5022 default: 5023 break; 5024 case Intrinsic::riscv_masked_strided_store: { 5025 SDLoc DL(Op); 5026 MVT XLenVT = Subtarget.getXLenVT(); 5027 5028 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5029 // the selection of the masked intrinsics doesn't do this for us. 5030 SDValue Mask = Op.getOperand(5); 5031 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5032 5033 SDValue Val = Op.getOperand(2); 5034 MVT VT = Val.getSimpleValueType(); 5035 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5036 5037 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5038 if (!IsUnmasked) { 5039 MVT MaskVT = getMaskTypeFor(ContainerVT); 5040 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5041 } 5042 5043 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5044 5045 SDValue IntID = DAG.getTargetConstant( 5046 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 5047 XLenVT); 5048 5049 auto *Store = cast<MemIntrinsicSDNode>(Op); 5050 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 5051 Ops.push_back(Val); 5052 Ops.push_back(Op.getOperand(3)); // Ptr 5053 Ops.push_back(Op.getOperand(4)); // Stride 5054 if (!IsUnmasked) 5055 Ops.push_back(Mask); 5056 Ops.push_back(VL); 5057 5058 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 5059 Ops, Store->getMemoryVT(), 5060 Store->getMemOperand()); 5061 } 5062 } 5063 5064 return SDValue(); 5065 } 5066 5067 static MVT getLMUL1VT(MVT VT) { 5068 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 5069 "Unexpected vector MVT"); 5070 return MVT::getScalableVectorVT( 5071 VT.getVectorElementType(), 5072 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 5073 } 5074 5075 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 5076 switch (ISDOpcode) { 5077 default: 5078 llvm_unreachable("Unhandled reduction"); 5079 case ISD::VECREDUCE_ADD: 5080 return RISCVISD::VECREDUCE_ADD_VL; 5081 case ISD::VECREDUCE_UMAX: 5082 return RISCVISD::VECREDUCE_UMAX_VL; 5083 case ISD::VECREDUCE_SMAX: 5084 return RISCVISD::VECREDUCE_SMAX_VL; 5085 case ISD::VECREDUCE_UMIN: 5086 return RISCVISD::VECREDUCE_UMIN_VL; 5087 case ISD::VECREDUCE_SMIN: 5088 return RISCVISD::VECREDUCE_SMIN_VL; 5089 case ISD::VECREDUCE_AND: 5090 return RISCVISD::VECREDUCE_AND_VL; 5091 case ISD::VECREDUCE_OR: 5092 return RISCVISD::VECREDUCE_OR_VL; 5093 case ISD::VECREDUCE_XOR: 5094 return RISCVISD::VECREDUCE_XOR_VL; 5095 } 5096 } 5097 5098 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 5099 SelectionDAG &DAG, 5100 bool IsVP) const { 5101 SDLoc DL(Op); 5102 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 5103 MVT VecVT = Vec.getSimpleValueType(); 5104 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 5105 Op.getOpcode() == ISD::VECREDUCE_OR || 5106 Op.getOpcode() == ISD::VECREDUCE_XOR || 5107 Op.getOpcode() == ISD::VP_REDUCE_AND || 5108 Op.getOpcode() == ISD::VP_REDUCE_OR || 5109 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5110 "Unexpected reduction lowering"); 5111 5112 MVT XLenVT = Subtarget.getXLenVT(); 5113 assert(Op.getValueType() == XLenVT && 5114 "Expected reduction output to be legalized to XLenVT"); 5115 5116 MVT ContainerVT = VecVT; 5117 if (VecVT.isFixedLengthVector()) { 5118 ContainerVT = getContainerForFixedLengthVector(VecVT); 5119 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5120 } 5121 5122 SDValue Mask, VL; 5123 if (IsVP) { 5124 Mask = Op.getOperand(2); 5125 VL = Op.getOperand(3); 5126 } else { 5127 std::tie(Mask, VL) = 5128 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5129 } 5130 5131 unsigned BaseOpc; 5132 ISD::CondCode CC; 5133 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5134 5135 switch (Op.getOpcode()) { 5136 default: 5137 llvm_unreachable("Unhandled reduction"); 5138 case ISD::VECREDUCE_AND: 5139 case ISD::VP_REDUCE_AND: { 5140 // vcpop ~x == 0 5141 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5142 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5143 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5144 CC = ISD::SETEQ; 5145 BaseOpc = ISD::AND; 5146 break; 5147 } 5148 case ISD::VECREDUCE_OR: 5149 case ISD::VP_REDUCE_OR: 5150 // vcpop x != 0 5151 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5152 CC = ISD::SETNE; 5153 BaseOpc = ISD::OR; 5154 break; 5155 case ISD::VECREDUCE_XOR: 5156 case ISD::VP_REDUCE_XOR: { 5157 // ((vcpop x) & 1) != 0 5158 SDValue One = DAG.getConstant(1, DL, XLenVT); 5159 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5160 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5161 CC = ISD::SETNE; 5162 BaseOpc = ISD::XOR; 5163 break; 5164 } 5165 } 5166 5167 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5168 5169 if (!IsVP) 5170 return SetCC; 5171 5172 // Now include the start value in the operation. 5173 // Note that we must return the start value when no elements are operated 5174 // upon. The vcpop instructions we've emitted in each case above will return 5175 // 0 for an inactive vector, and so we've already received the neutral value: 5176 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5177 // can simply include the start value. 5178 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5179 } 5180 5181 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5182 SelectionDAG &DAG) const { 5183 SDLoc DL(Op); 5184 SDValue Vec = Op.getOperand(0); 5185 EVT VecEVT = Vec.getValueType(); 5186 5187 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5188 5189 // Due to ordering in legalize types we may have a vector type that needs to 5190 // be split. Do that manually so we can get down to a legal type. 5191 while (getTypeAction(*DAG.getContext(), VecEVT) == 5192 TargetLowering::TypeSplitVector) { 5193 SDValue Lo, Hi; 5194 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5195 VecEVT = Lo.getValueType(); 5196 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5197 } 5198 5199 // TODO: The type may need to be widened rather than split. Or widened before 5200 // it can be split. 5201 if (!isTypeLegal(VecEVT)) 5202 return SDValue(); 5203 5204 MVT VecVT = VecEVT.getSimpleVT(); 5205 MVT VecEltVT = VecVT.getVectorElementType(); 5206 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5207 5208 MVT ContainerVT = VecVT; 5209 if (VecVT.isFixedLengthVector()) { 5210 ContainerVT = getContainerForFixedLengthVector(VecVT); 5211 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5212 } 5213 5214 MVT M1VT = getLMUL1VT(ContainerVT); 5215 MVT XLenVT = Subtarget.getXLenVT(); 5216 5217 SDValue Mask, VL; 5218 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5219 5220 SDValue NeutralElem = 5221 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5222 SDValue IdentitySplat = 5223 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5224 M1VT, DL, DAG, Subtarget); 5225 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5226 IdentitySplat, Mask, VL); 5227 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5228 DAG.getConstant(0, DL, XLenVT)); 5229 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5230 } 5231 5232 // Given a reduction op, this function returns the matching reduction opcode, 5233 // the vector SDValue and the scalar SDValue required to lower this to a 5234 // RISCVISD node. 5235 static std::tuple<unsigned, SDValue, SDValue> 5236 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5237 SDLoc DL(Op); 5238 auto Flags = Op->getFlags(); 5239 unsigned Opcode = Op.getOpcode(); 5240 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5241 switch (Opcode) { 5242 default: 5243 llvm_unreachable("Unhandled reduction"); 5244 case ISD::VECREDUCE_FADD: { 5245 // Use positive zero if we can. It is cheaper to materialize. 5246 SDValue Zero = 5247 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5248 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5249 } 5250 case ISD::VECREDUCE_SEQ_FADD: 5251 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5252 Op.getOperand(0)); 5253 case ISD::VECREDUCE_FMIN: 5254 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5255 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5256 case ISD::VECREDUCE_FMAX: 5257 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5258 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5259 } 5260 } 5261 5262 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5263 SelectionDAG &DAG) const { 5264 SDLoc DL(Op); 5265 MVT VecEltVT = Op.getSimpleValueType(); 5266 5267 unsigned RVVOpcode; 5268 SDValue VectorVal, ScalarVal; 5269 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5270 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5271 MVT VecVT = VectorVal.getSimpleValueType(); 5272 5273 MVT ContainerVT = VecVT; 5274 if (VecVT.isFixedLengthVector()) { 5275 ContainerVT = getContainerForFixedLengthVector(VecVT); 5276 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5277 } 5278 5279 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5280 MVT XLenVT = Subtarget.getXLenVT(); 5281 5282 SDValue Mask, VL; 5283 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5284 5285 SDValue ScalarSplat = 5286 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5287 M1VT, DL, DAG, Subtarget); 5288 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5289 VectorVal, ScalarSplat, Mask, VL); 5290 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5291 DAG.getConstant(0, DL, XLenVT)); 5292 } 5293 5294 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5295 switch (ISDOpcode) { 5296 default: 5297 llvm_unreachable("Unhandled reduction"); 5298 case ISD::VP_REDUCE_ADD: 5299 return RISCVISD::VECREDUCE_ADD_VL; 5300 case ISD::VP_REDUCE_UMAX: 5301 return RISCVISD::VECREDUCE_UMAX_VL; 5302 case ISD::VP_REDUCE_SMAX: 5303 return RISCVISD::VECREDUCE_SMAX_VL; 5304 case ISD::VP_REDUCE_UMIN: 5305 return RISCVISD::VECREDUCE_UMIN_VL; 5306 case ISD::VP_REDUCE_SMIN: 5307 return RISCVISD::VECREDUCE_SMIN_VL; 5308 case ISD::VP_REDUCE_AND: 5309 return RISCVISD::VECREDUCE_AND_VL; 5310 case ISD::VP_REDUCE_OR: 5311 return RISCVISD::VECREDUCE_OR_VL; 5312 case ISD::VP_REDUCE_XOR: 5313 return RISCVISD::VECREDUCE_XOR_VL; 5314 case ISD::VP_REDUCE_FADD: 5315 return RISCVISD::VECREDUCE_FADD_VL; 5316 case ISD::VP_REDUCE_SEQ_FADD: 5317 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5318 case ISD::VP_REDUCE_FMAX: 5319 return RISCVISD::VECREDUCE_FMAX_VL; 5320 case ISD::VP_REDUCE_FMIN: 5321 return RISCVISD::VECREDUCE_FMIN_VL; 5322 } 5323 } 5324 5325 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5326 SelectionDAG &DAG) const { 5327 SDLoc DL(Op); 5328 SDValue Vec = Op.getOperand(1); 5329 EVT VecEVT = Vec.getValueType(); 5330 5331 // TODO: The type may need to be widened rather than split. Or widened before 5332 // it can be split. 5333 if (!isTypeLegal(VecEVT)) 5334 return SDValue(); 5335 5336 MVT VecVT = VecEVT.getSimpleVT(); 5337 MVT VecEltVT = VecVT.getVectorElementType(); 5338 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5339 5340 MVT ContainerVT = VecVT; 5341 if (VecVT.isFixedLengthVector()) { 5342 ContainerVT = getContainerForFixedLengthVector(VecVT); 5343 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5344 } 5345 5346 SDValue VL = Op.getOperand(3); 5347 SDValue Mask = Op.getOperand(2); 5348 5349 MVT M1VT = getLMUL1VT(ContainerVT); 5350 MVT XLenVT = Subtarget.getXLenVT(); 5351 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5352 5353 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5354 DAG.getConstant(1, DL, XLenVT), M1VT, 5355 DL, DAG, Subtarget); 5356 SDValue Reduction = 5357 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5358 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5359 DAG.getConstant(0, DL, XLenVT)); 5360 if (!VecVT.isInteger()) 5361 return Elt0; 5362 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5363 } 5364 5365 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5366 SelectionDAG &DAG) const { 5367 SDValue Vec = Op.getOperand(0); 5368 SDValue SubVec = Op.getOperand(1); 5369 MVT VecVT = Vec.getSimpleValueType(); 5370 MVT SubVecVT = SubVec.getSimpleValueType(); 5371 5372 SDLoc DL(Op); 5373 MVT XLenVT = Subtarget.getXLenVT(); 5374 unsigned OrigIdx = Op.getConstantOperandVal(2); 5375 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5376 5377 // We don't have the ability to slide mask vectors up indexed by their i1 5378 // elements; the smallest we can do is i8. Often we are able to bitcast to 5379 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5380 // into a scalable one, we might not necessarily have enough scalable 5381 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5382 if (SubVecVT.getVectorElementType() == MVT::i1 && 5383 (OrigIdx != 0 || !Vec.isUndef())) { 5384 if (VecVT.getVectorMinNumElements() >= 8 && 5385 SubVecVT.getVectorMinNumElements() >= 8) { 5386 assert(OrigIdx % 8 == 0 && "Invalid index"); 5387 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5388 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5389 "Unexpected mask vector lowering"); 5390 OrigIdx /= 8; 5391 SubVecVT = 5392 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5393 SubVecVT.isScalableVector()); 5394 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5395 VecVT.isScalableVector()); 5396 Vec = DAG.getBitcast(VecVT, Vec); 5397 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5398 } else { 5399 // We can't slide this mask vector up indexed by its i1 elements. 5400 // This poses a problem when we wish to insert a scalable vector which 5401 // can't be re-expressed as a larger type. Just choose the slow path and 5402 // extend to a larger type, then truncate back down. 5403 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5404 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5405 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5406 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5407 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5408 Op.getOperand(2)); 5409 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5410 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5411 } 5412 } 5413 5414 // If the subvector vector is a fixed-length type, we cannot use subregister 5415 // manipulation to simplify the codegen; we don't know which register of a 5416 // LMUL group contains the specific subvector as we only know the minimum 5417 // register size. Therefore we must slide the vector group up the full 5418 // amount. 5419 if (SubVecVT.isFixedLengthVector()) { 5420 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5421 return Op; 5422 MVT ContainerVT = VecVT; 5423 if (VecVT.isFixedLengthVector()) { 5424 ContainerVT = getContainerForFixedLengthVector(VecVT); 5425 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5426 } 5427 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5428 DAG.getUNDEF(ContainerVT), SubVec, 5429 DAG.getConstant(0, DL, XLenVT)); 5430 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5431 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5432 return DAG.getBitcast(Op.getValueType(), SubVec); 5433 } 5434 SDValue Mask = 5435 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5436 // Set the vector length to only the number of elements we care about. Note 5437 // that for slideup this includes the offset. 5438 SDValue VL = 5439 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5440 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5441 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5442 SubVec, SlideupAmt, Mask, VL); 5443 if (VecVT.isFixedLengthVector()) 5444 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5445 return DAG.getBitcast(Op.getValueType(), Slideup); 5446 } 5447 5448 unsigned SubRegIdx, RemIdx; 5449 std::tie(SubRegIdx, RemIdx) = 5450 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5451 VecVT, SubVecVT, OrigIdx, TRI); 5452 5453 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5454 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5455 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5456 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5457 5458 // 1. If the Idx has been completely eliminated and this subvector's size is 5459 // a vector register or a multiple thereof, or the surrounding elements are 5460 // undef, then this is a subvector insert which naturally aligns to a vector 5461 // register. These can easily be handled using subregister manipulation. 5462 // 2. If the subvector is smaller than a vector register, then the insertion 5463 // must preserve the undisturbed elements of the register. We do this by 5464 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5465 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5466 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5467 // LMUL=1 type back into the larger vector (resolving to another subregister 5468 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5469 // to avoid allocating a large register group to hold our subvector. 5470 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5471 return Op; 5472 5473 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5474 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5475 // (in our case undisturbed). This means we can set up a subvector insertion 5476 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5477 // size of the subvector. 5478 MVT InterSubVT = VecVT; 5479 SDValue AlignedExtract = Vec; 5480 unsigned AlignedIdx = OrigIdx - RemIdx; 5481 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5482 InterSubVT = getLMUL1VT(VecVT); 5483 // Extract a subvector equal to the nearest full vector register type. This 5484 // should resolve to a EXTRACT_SUBREG instruction. 5485 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5486 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5487 } 5488 5489 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5490 // For scalable vectors this must be further multiplied by vscale. 5491 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5492 5493 SDValue Mask, VL; 5494 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5495 5496 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5497 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5498 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5499 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5500 5501 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5502 DAG.getUNDEF(InterSubVT), SubVec, 5503 DAG.getConstant(0, DL, XLenVT)); 5504 5505 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5506 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5507 5508 // If required, insert this subvector back into the correct vector register. 5509 // This should resolve to an INSERT_SUBREG instruction. 5510 if (VecVT.bitsGT(InterSubVT)) 5511 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5512 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5513 5514 // We might have bitcast from a mask type: cast back to the original type if 5515 // required. 5516 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5517 } 5518 5519 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5520 SelectionDAG &DAG) const { 5521 SDValue Vec = Op.getOperand(0); 5522 MVT SubVecVT = Op.getSimpleValueType(); 5523 MVT VecVT = Vec.getSimpleValueType(); 5524 5525 SDLoc DL(Op); 5526 MVT XLenVT = Subtarget.getXLenVT(); 5527 unsigned OrigIdx = Op.getConstantOperandVal(1); 5528 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5529 5530 // We don't have the ability to slide mask vectors down indexed by their i1 5531 // elements; the smallest we can do is i8. Often we are able to bitcast to 5532 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5533 // from a scalable one, we might not necessarily have enough scalable 5534 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5535 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5536 if (VecVT.getVectorMinNumElements() >= 8 && 5537 SubVecVT.getVectorMinNumElements() >= 8) { 5538 assert(OrigIdx % 8 == 0 && "Invalid index"); 5539 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5540 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5541 "Unexpected mask vector lowering"); 5542 OrigIdx /= 8; 5543 SubVecVT = 5544 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5545 SubVecVT.isScalableVector()); 5546 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5547 VecVT.isScalableVector()); 5548 Vec = DAG.getBitcast(VecVT, Vec); 5549 } else { 5550 // We can't slide this mask vector down, indexed by its i1 elements. 5551 // This poses a problem when we wish to extract a scalable vector which 5552 // can't be re-expressed as a larger type. Just choose the slow path and 5553 // extend to a larger type, then truncate back down. 5554 // TODO: We could probably improve this when extracting certain fixed 5555 // from fixed, where we can extract as i8 and shift the correct element 5556 // right to reach the desired subvector? 5557 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5558 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5559 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5560 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5561 Op.getOperand(1)); 5562 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5563 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5564 } 5565 } 5566 5567 // If the subvector vector is a fixed-length type, we cannot use subregister 5568 // manipulation to simplify the codegen; we don't know which register of a 5569 // LMUL group contains the specific subvector as we only know the minimum 5570 // register size. Therefore we must slide the vector group down the full 5571 // amount. 5572 if (SubVecVT.isFixedLengthVector()) { 5573 // With an index of 0 this is a cast-like subvector, which can be performed 5574 // with subregister operations. 5575 if (OrigIdx == 0) 5576 return Op; 5577 MVT ContainerVT = VecVT; 5578 if (VecVT.isFixedLengthVector()) { 5579 ContainerVT = getContainerForFixedLengthVector(VecVT); 5580 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5581 } 5582 SDValue Mask = 5583 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5584 // Set the vector length to only the number of elements we care about. This 5585 // avoids sliding down elements we're going to discard straight away. 5586 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5587 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5588 SDValue Slidedown = 5589 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5590 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5591 // Now we can use a cast-like subvector extract to get the result. 5592 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5593 DAG.getConstant(0, DL, XLenVT)); 5594 return DAG.getBitcast(Op.getValueType(), Slidedown); 5595 } 5596 5597 unsigned SubRegIdx, RemIdx; 5598 std::tie(SubRegIdx, RemIdx) = 5599 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5600 VecVT, SubVecVT, OrigIdx, TRI); 5601 5602 // If the Idx has been completely eliminated then this is a subvector extract 5603 // which naturally aligns to a vector register. These can easily be handled 5604 // using subregister manipulation. 5605 if (RemIdx == 0) 5606 return Op; 5607 5608 // Else we must shift our vector register directly to extract the subvector. 5609 // Do this using VSLIDEDOWN. 5610 5611 // If the vector type is an LMUL-group type, extract a subvector equal to the 5612 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5613 // instruction. 5614 MVT InterSubVT = VecVT; 5615 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5616 InterSubVT = getLMUL1VT(VecVT); 5617 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5618 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5619 } 5620 5621 // Slide this vector register down by the desired number of elements in order 5622 // to place the desired subvector starting at element 0. 5623 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5624 // For scalable vectors this must be further multiplied by vscale. 5625 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5626 5627 SDValue Mask, VL; 5628 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5629 SDValue Slidedown = 5630 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5631 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5632 5633 // Now the vector is in the right position, extract our final subvector. This 5634 // should resolve to a COPY. 5635 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5636 DAG.getConstant(0, DL, XLenVT)); 5637 5638 // We might have bitcast from a mask type: cast back to the original type if 5639 // required. 5640 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5641 } 5642 5643 // Lower step_vector to the vid instruction. Any non-identity step value must 5644 // be accounted for my manual expansion. 5645 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5646 SelectionDAG &DAG) const { 5647 SDLoc DL(Op); 5648 MVT VT = Op.getSimpleValueType(); 5649 MVT XLenVT = Subtarget.getXLenVT(); 5650 SDValue Mask, VL; 5651 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5652 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5653 uint64_t StepValImm = Op.getConstantOperandVal(0); 5654 if (StepValImm != 1) { 5655 if (isPowerOf2_64(StepValImm)) { 5656 SDValue StepVal = 5657 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5658 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5659 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5660 } else { 5661 SDValue StepVal = lowerScalarSplat( 5662 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5663 VL, VT, DL, DAG, Subtarget); 5664 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5665 } 5666 } 5667 return StepVec; 5668 } 5669 5670 // Implement vector_reverse using vrgather.vv with indices determined by 5671 // subtracting the id of each element from (VLMAX-1). This will convert 5672 // the indices like so: 5673 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5674 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5675 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5676 SelectionDAG &DAG) const { 5677 SDLoc DL(Op); 5678 MVT VecVT = Op.getSimpleValueType(); 5679 if (VecVT.getVectorElementType() == MVT::i1) { 5680 MVT WidenVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 5681 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenVT, Op.getOperand(0)); 5682 SDValue Op2 = DAG.getNode(ISD::VECTOR_REVERSE, DL, WidenVT, Op1); 5683 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Op2); 5684 } 5685 unsigned EltSize = VecVT.getScalarSizeInBits(); 5686 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5687 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 5688 unsigned MaxVLMAX = 5689 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 5690 5691 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5692 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5693 5694 // If this is SEW=8 and VLMAX is potentially more than 256, we need 5695 // to use vrgatherei16.vv. 5696 // TODO: It's also possible to use vrgatherei16.vv for other types to 5697 // decrease register width for the index calculation. 5698 if (MaxVLMAX > 256 && EltSize == 8) { 5699 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5700 // Reverse each half, then reassemble them in reverse order. 5701 // NOTE: It's also possible that after splitting that VLMAX no longer 5702 // requires vrgatherei16.vv. 5703 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5704 SDValue Lo, Hi; 5705 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5706 EVT LoVT, HiVT; 5707 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5708 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5709 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5710 // Reassemble the low and high pieces reversed. 5711 // FIXME: This is a CONCAT_VECTORS. 5712 SDValue Res = 5713 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5714 DAG.getIntPtrConstant(0, DL)); 5715 return DAG.getNode( 5716 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5717 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5718 } 5719 5720 // Just promote the int type to i16 which will double the LMUL. 5721 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5722 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5723 } 5724 5725 MVT XLenVT = Subtarget.getXLenVT(); 5726 SDValue Mask, VL; 5727 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5728 5729 // Calculate VLMAX-1 for the desired SEW. 5730 unsigned MinElts = VecVT.getVectorMinNumElements(); 5731 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5732 DAG.getConstant(MinElts, DL, XLenVT)); 5733 SDValue VLMinus1 = 5734 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5735 5736 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5737 bool IsRV32E64 = 5738 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5739 SDValue SplatVL; 5740 if (!IsRV32E64) 5741 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5742 else 5743 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5744 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5745 5746 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5747 SDValue Indices = 5748 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5749 5750 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, 5751 DAG.getUNDEF(VecVT), VL); 5752 } 5753 5754 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5755 SelectionDAG &DAG) const { 5756 SDLoc DL(Op); 5757 SDValue V1 = Op.getOperand(0); 5758 SDValue V2 = Op.getOperand(1); 5759 MVT XLenVT = Subtarget.getXLenVT(); 5760 MVT VecVT = Op.getSimpleValueType(); 5761 5762 unsigned MinElts = VecVT.getVectorMinNumElements(); 5763 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5764 DAG.getConstant(MinElts, DL, XLenVT)); 5765 5766 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5767 SDValue DownOffset, UpOffset; 5768 if (ImmValue >= 0) { 5769 // The operand is a TargetConstant, we need to rebuild it as a regular 5770 // constant. 5771 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5772 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5773 } else { 5774 // The operand is a TargetConstant, we need to rebuild it as a regular 5775 // constant rather than negating the original operand. 5776 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5777 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5778 } 5779 5780 SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG); 5781 5782 SDValue SlideDown = 5783 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5784 DownOffset, TrueMask, UpOffset); 5785 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5786 TrueMask, 5787 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 5788 } 5789 5790 SDValue 5791 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5792 SelectionDAG &DAG) const { 5793 SDLoc DL(Op); 5794 auto *Load = cast<LoadSDNode>(Op); 5795 5796 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5797 Load->getMemoryVT(), 5798 *Load->getMemOperand()) && 5799 "Expecting a correctly-aligned load"); 5800 5801 MVT VT = Op.getSimpleValueType(); 5802 MVT XLenVT = Subtarget.getXLenVT(); 5803 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5804 5805 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5806 5807 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5808 SDValue IntID = DAG.getTargetConstant( 5809 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 5810 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 5811 if (!IsMaskOp) 5812 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5813 Ops.push_back(Load->getBasePtr()); 5814 Ops.push_back(VL); 5815 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5816 SDValue NewLoad = 5817 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5818 Load->getMemoryVT(), Load->getMemOperand()); 5819 5820 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5821 return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL); 5822 } 5823 5824 SDValue 5825 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5826 SelectionDAG &DAG) const { 5827 SDLoc DL(Op); 5828 auto *Store = cast<StoreSDNode>(Op); 5829 5830 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5831 Store->getMemoryVT(), 5832 *Store->getMemOperand()) && 5833 "Expecting a correctly-aligned store"); 5834 5835 SDValue StoreVal = Store->getValue(); 5836 MVT VT = StoreVal.getSimpleValueType(); 5837 MVT XLenVT = Subtarget.getXLenVT(); 5838 5839 // If the size less than a byte, we need to pad with zeros to make a byte. 5840 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5841 VT = MVT::v8i1; 5842 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5843 DAG.getConstant(0, DL, VT), StoreVal, 5844 DAG.getIntPtrConstant(0, DL)); 5845 } 5846 5847 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5848 5849 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5850 5851 SDValue NewValue = 5852 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5853 5854 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5855 SDValue IntID = DAG.getTargetConstant( 5856 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 5857 return DAG.getMemIntrinsicNode( 5858 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 5859 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 5860 Store->getMemoryVT(), Store->getMemOperand()); 5861 } 5862 5863 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5864 SelectionDAG &DAG) const { 5865 SDLoc DL(Op); 5866 MVT VT = Op.getSimpleValueType(); 5867 5868 const auto *MemSD = cast<MemSDNode>(Op); 5869 EVT MemVT = MemSD->getMemoryVT(); 5870 MachineMemOperand *MMO = MemSD->getMemOperand(); 5871 SDValue Chain = MemSD->getChain(); 5872 SDValue BasePtr = MemSD->getBasePtr(); 5873 5874 SDValue Mask, PassThru, VL; 5875 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5876 Mask = VPLoad->getMask(); 5877 PassThru = DAG.getUNDEF(VT); 5878 VL = VPLoad->getVectorLength(); 5879 } else { 5880 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5881 Mask = MLoad->getMask(); 5882 PassThru = MLoad->getPassThru(); 5883 } 5884 5885 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5886 5887 MVT XLenVT = Subtarget.getXLenVT(); 5888 5889 MVT ContainerVT = VT; 5890 if (VT.isFixedLengthVector()) { 5891 ContainerVT = getContainerForFixedLengthVector(VT); 5892 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5893 if (!IsUnmasked) { 5894 MVT MaskVT = getMaskTypeFor(ContainerVT); 5895 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5896 } 5897 } 5898 5899 if (!VL) 5900 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5901 5902 unsigned IntID = 5903 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5904 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5905 if (IsUnmasked) 5906 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5907 else 5908 Ops.push_back(PassThru); 5909 Ops.push_back(BasePtr); 5910 if (!IsUnmasked) 5911 Ops.push_back(Mask); 5912 Ops.push_back(VL); 5913 if (!IsUnmasked) 5914 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5915 5916 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5917 5918 SDValue Result = 5919 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5920 Chain = Result.getValue(1); 5921 5922 if (VT.isFixedLengthVector()) 5923 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5924 5925 return DAG.getMergeValues({Result, Chain}, DL); 5926 } 5927 5928 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5929 SelectionDAG &DAG) const { 5930 SDLoc DL(Op); 5931 5932 const auto *MemSD = cast<MemSDNode>(Op); 5933 EVT MemVT = MemSD->getMemoryVT(); 5934 MachineMemOperand *MMO = MemSD->getMemOperand(); 5935 SDValue Chain = MemSD->getChain(); 5936 SDValue BasePtr = MemSD->getBasePtr(); 5937 SDValue Val, Mask, VL; 5938 5939 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5940 Val = VPStore->getValue(); 5941 Mask = VPStore->getMask(); 5942 VL = VPStore->getVectorLength(); 5943 } else { 5944 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5945 Val = MStore->getValue(); 5946 Mask = MStore->getMask(); 5947 } 5948 5949 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5950 5951 MVT VT = Val.getSimpleValueType(); 5952 MVT XLenVT = Subtarget.getXLenVT(); 5953 5954 MVT ContainerVT = VT; 5955 if (VT.isFixedLengthVector()) { 5956 ContainerVT = getContainerForFixedLengthVector(VT); 5957 5958 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5959 if (!IsUnmasked) { 5960 MVT MaskVT = getMaskTypeFor(ContainerVT); 5961 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5962 } 5963 } 5964 5965 if (!VL) 5966 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5967 5968 unsigned IntID = 5969 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5970 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5971 Ops.push_back(Val); 5972 Ops.push_back(BasePtr); 5973 if (!IsUnmasked) 5974 Ops.push_back(Mask); 5975 Ops.push_back(VL); 5976 5977 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5978 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5979 } 5980 5981 SDValue 5982 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5983 SelectionDAG &DAG) const { 5984 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5985 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5986 5987 MVT VT = Op.getSimpleValueType(); 5988 5989 SDValue Op1 = 5990 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5991 SDValue Op2 = 5992 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5993 5994 SDLoc DL(Op); 5995 SDValue VL = 5996 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5997 5998 MVT MaskVT = getMaskTypeFor(ContainerVT); 5999 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 6000 6001 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 6002 Op.getOperand(2), Mask, VL); 6003 6004 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 6005 } 6006 6007 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 6008 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 6009 MVT VT = Op.getSimpleValueType(); 6010 6011 if (VT.getVectorElementType() == MVT::i1) 6012 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 6013 6014 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 6015 } 6016 6017 SDValue 6018 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 6019 SelectionDAG &DAG) const { 6020 unsigned Opc; 6021 switch (Op.getOpcode()) { 6022 default: llvm_unreachable("Unexpected opcode!"); 6023 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 6024 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 6025 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 6026 } 6027 6028 return lowerToScalableOp(Op, DAG, Opc); 6029 } 6030 6031 // Lower vector ABS to smax(X, sub(0, X)). 6032 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 6033 SDLoc DL(Op); 6034 MVT VT = Op.getSimpleValueType(); 6035 SDValue X = Op.getOperand(0); 6036 6037 assert(VT.isFixedLengthVector() && "Unexpected type"); 6038 6039 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6040 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 6041 6042 SDValue Mask, VL; 6043 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6044 6045 SDValue SplatZero = DAG.getNode( 6046 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 6047 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 6048 SDValue NegX = 6049 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 6050 SDValue Max = 6051 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 6052 6053 return convertFromScalableVector(VT, Max, DAG, Subtarget); 6054 } 6055 6056 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 6057 SDValue Op, SelectionDAG &DAG) const { 6058 SDLoc DL(Op); 6059 MVT VT = Op.getSimpleValueType(); 6060 SDValue Mag = Op.getOperand(0); 6061 SDValue Sign = Op.getOperand(1); 6062 assert(Mag.getValueType() == Sign.getValueType() && 6063 "Can only handle COPYSIGN with matching types."); 6064 6065 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6066 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 6067 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 6068 6069 SDValue Mask, VL; 6070 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6071 6072 SDValue CopySign = 6073 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 6074 6075 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 6076 } 6077 6078 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 6079 SDValue Op, SelectionDAG &DAG) const { 6080 MVT VT = Op.getSimpleValueType(); 6081 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6082 6083 MVT I1ContainerVT = 6084 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6085 6086 SDValue CC = 6087 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 6088 SDValue Op1 = 6089 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 6090 SDValue Op2 = 6091 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 6092 6093 SDLoc DL(Op); 6094 SDValue Mask, VL; 6095 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6096 6097 SDValue Select = 6098 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 6099 6100 return convertFromScalableVector(VT, Select, DAG, Subtarget); 6101 } 6102 6103 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 6104 unsigned NewOpc, 6105 bool HasMask) const { 6106 MVT VT = Op.getSimpleValueType(); 6107 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6108 6109 // Create list of operands by converting existing ones to scalable types. 6110 SmallVector<SDValue, 6> Ops; 6111 for (const SDValue &V : Op->op_values()) { 6112 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6113 6114 // Pass through non-vector operands. 6115 if (!V.getValueType().isVector()) { 6116 Ops.push_back(V); 6117 continue; 6118 } 6119 6120 // "cast" fixed length vector to a scalable vector. 6121 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6122 "Only fixed length vectors are supported!"); 6123 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6124 } 6125 6126 SDLoc DL(Op); 6127 SDValue Mask, VL; 6128 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6129 if (HasMask) 6130 Ops.push_back(Mask); 6131 Ops.push_back(VL); 6132 6133 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6134 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6135 } 6136 6137 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6138 // * Operands of each node are assumed to be in the same order. 6139 // * The EVL operand is promoted from i32 to i64 on RV64. 6140 // * Fixed-length vectors are converted to their scalable-vector container 6141 // types. 6142 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6143 unsigned RISCVISDOpc) const { 6144 SDLoc DL(Op); 6145 MVT VT = Op.getSimpleValueType(); 6146 SmallVector<SDValue, 4> Ops; 6147 6148 for (const auto &OpIdx : enumerate(Op->ops())) { 6149 SDValue V = OpIdx.value(); 6150 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6151 // Pass through operands which aren't fixed-length vectors. 6152 if (!V.getValueType().isFixedLengthVector()) { 6153 Ops.push_back(V); 6154 continue; 6155 } 6156 // "cast" fixed length vector to a scalable vector. 6157 MVT OpVT = V.getSimpleValueType(); 6158 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6159 assert(useRVVForFixedLengthVectorVT(OpVT) && 6160 "Only fixed length vectors are supported!"); 6161 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6162 } 6163 6164 if (!VT.isFixedLengthVector()) 6165 return DAG.getNode(RISCVISDOpc, DL, VT, Ops, Op->getFlags()); 6166 6167 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6168 6169 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops, Op->getFlags()); 6170 6171 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6172 } 6173 6174 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op, 6175 SelectionDAG &DAG) const { 6176 SDLoc DL(Op); 6177 MVT VT = Op.getSimpleValueType(); 6178 6179 SDValue Src = Op.getOperand(0); 6180 // NOTE: Mask is dropped. 6181 SDValue VL = Op.getOperand(2); 6182 6183 MVT ContainerVT = VT; 6184 if (VT.isFixedLengthVector()) { 6185 ContainerVT = getContainerForFixedLengthVector(VT); 6186 MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6187 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6188 } 6189 6190 MVT XLenVT = Subtarget.getXLenVT(); 6191 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6192 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6193 DAG.getUNDEF(ContainerVT), Zero, VL); 6194 6195 SDValue SplatValue = DAG.getConstant( 6196 Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT); 6197 SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6198 DAG.getUNDEF(ContainerVT), SplatValue, VL); 6199 6200 SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src, 6201 Splat, ZeroSplat, VL); 6202 if (!VT.isFixedLengthVector()) 6203 return Result; 6204 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6205 } 6206 6207 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op, 6208 SelectionDAG &DAG) const { 6209 SDLoc DL(Op); 6210 MVT VT = Op.getSimpleValueType(); 6211 6212 SDValue Op1 = Op.getOperand(0); 6213 SDValue Op2 = Op.getOperand(1); 6214 ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 6215 // NOTE: Mask is dropped. 6216 SDValue VL = Op.getOperand(4); 6217 6218 MVT ContainerVT = VT; 6219 if (VT.isFixedLengthVector()) { 6220 ContainerVT = getContainerForFixedLengthVector(VT); 6221 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6222 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6223 } 6224 6225 SDValue Result; 6226 SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 6227 6228 switch (Condition) { 6229 default: 6230 break; 6231 // X != Y --> (X^Y) 6232 case ISD::SETNE: 6233 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6234 break; 6235 // X == Y --> ~(X^Y) 6236 case ISD::SETEQ: { 6237 SDValue Temp = 6238 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6239 Result = 6240 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL); 6241 break; 6242 } 6243 // X >s Y --> X == 0 & Y == 1 --> ~X & Y 6244 // X <u Y --> X == 0 & Y == 1 --> ~X & Y 6245 case ISD::SETGT: 6246 case ISD::SETULT: { 6247 SDValue Temp = 6248 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6249 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL); 6250 break; 6251 } 6252 // X <s Y --> X == 1 & Y == 0 --> ~Y & X 6253 // X >u Y --> X == 1 & Y == 0 --> ~Y & X 6254 case ISD::SETLT: 6255 case ISD::SETUGT: { 6256 SDValue Temp = 6257 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6258 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL); 6259 break; 6260 } 6261 // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 6262 // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 6263 case ISD::SETGE: 6264 case ISD::SETULE: { 6265 SDValue Temp = 6266 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6267 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL); 6268 break; 6269 } 6270 // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 6271 // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 6272 case ISD::SETLE: 6273 case ISD::SETUGE: { 6274 SDValue Temp = 6275 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6276 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL); 6277 break; 6278 } 6279 } 6280 6281 if (!VT.isFixedLengthVector()) 6282 return Result; 6283 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6284 } 6285 6286 // Lower Floating-Point/Integer Type-Convert VP SDNodes 6287 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG, 6288 unsigned RISCVISDOpc) const { 6289 SDLoc DL(Op); 6290 6291 SDValue Src = Op.getOperand(0); 6292 SDValue Mask = Op.getOperand(1); 6293 SDValue VL = Op.getOperand(2); 6294 6295 MVT DstVT = Op.getSimpleValueType(); 6296 MVT SrcVT = Src.getSimpleValueType(); 6297 if (DstVT.isFixedLengthVector()) { 6298 DstVT = getContainerForFixedLengthVector(DstVT); 6299 SrcVT = getContainerForFixedLengthVector(SrcVT); 6300 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6301 MVT MaskVT = getMaskTypeFor(DstVT); 6302 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6303 } 6304 6305 unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL || 6306 RISCVISDOpc == RISCVISD::FP_TO_SINT_VL) 6307 ? RISCVISD::VSEXT_VL 6308 : RISCVISD::VZEXT_VL; 6309 6310 unsigned DstEltSize = DstVT.getScalarSizeInBits(); 6311 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 6312 6313 SDValue Result; 6314 if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion. 6315 if (SrcVT.isInteger()) { 6316 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6317 6318 // Do we need to do any pre-widening before converting? 6319 if (SrcEltSize == 1) { 6320 MVT IntVT = DstVT.changeVectorElementTypeToInteger(); 6321 MVT XLenVT = Subtarget.getXLenVT(); 6322 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6323 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6324 DAG.getUNDEF(IntVT), Zero, VL); 6325 SDValue One = DAG.getConstant( 6326 RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT); 6327 SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6328 DAG.getUNDEF(IntVT), One, VL); 6329 Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat, 6330 ZeroSplat, VL); 6331 } else if (DstEltSize > (2 * SrcEltSize)) { 6332 // Widen before converting. 6333 MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2), 6334 DstVT.getVectorElementCount()); 6335 Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL); 6336 } 6337 6338 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6339 } else { 6340 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6341 "Wrong input/output vector types"); 6342 6343 // Convert f16 to f32 then convert f32 to i64. 6344 if (DstEltSize > (2 * SrcEltSize)) { 6345 assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6346 MVT InterimFVT = 6347 MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6348 Src = 6349 DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL); 6350 } 6351 6352 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6353 } 6354 } else { // Narrowing + Conversion 6355 if (SrcVT.isInteger()) { 6356 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6357 // First do a narrowing convert to an FP type half the size, then round 6358 // the FP type to a small FP type if needed. 6359 6360 MVT InterimFVT = DstVT; 6361 if (SrcEltSize > (2 * DstEltSize)) { 6362 assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!"); 6363 assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6364 InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6365 } 6366 6367 Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL); 6368 6369 if (InterimFVT != DstVT) { 6370 Src = Result; 6371 Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL); 6372 } 6373 } else { 6374 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6375 "Wrong input/output vector types"); 6376 // First do a narrowing conversion to an integer half the size, then 6377 // truncate if needed. 6378 6379 if (DstEltSize == 1) { 6380 // First convert to the same size integer, then convert to mask using 6381 // setcc. 6382 assert(SrcEltSize >= 16 && "Unexpected FP type!"); 6383 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize), 6384 DstVT.getVectorElementCount()); 6385 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6386 6387 // Compare the integer result to 0. The integer should be 0 or 1/-1, 6388 // otherwise the conversion was undefined. 6389 MVT XLenVT = Subtarget.getXLenVT(); 6390 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 6391 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT, 6392 DAG.getUNDEF(InterimIVT), SplatZero); 6393 Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero, 6394 DAG.getCondCode(ISD::SETNE), Mask, VL); 6395 } else { 6396 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6397 DstVT.getVectorElementCount()); 6398 6399 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6400 6401 while (InterimIVT != DstVT) { 6402 SrcEltSize /= 2; 6403 Src = Result; 6404 InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6405 DstVT.getVectorElementCount()); 6406 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT, 6407 Src, Mask, VL); 6408 } 6409 } 6410 } 6411 } 6412 6413 MVT VT = Op.getSimpleValueType(); 6414 if (!VT.isFixedLengthVector()) 6415 return Result; 6416 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6417 } 6418 6419 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6420 unsigned MaskOpc, 6421 unsigned VecOpc) const { 6422 MVT VT = Op.getSimpleValueType(); 6423 if (VT.getVectorElementType() != MVT::i1) 6424 return lowerVPOp(Op, DAG, VecOpc); 6425 6426 // It is safe to drop mask parameter as masked-off elements are undef. 6427 SDValue Op1 = Op->getOperand(0); 6428 SDValue Op2 = Op->getOperand(1); 6429 SDValue VL = Op->getOperand(3); 6430 6431 MVT ContainerVT = VT; 6432 const bool IsFixed = VT.isFixedLengthVector(); 6433 if (IsFixed) { 6434 ContainerVT = getContainerForFixedLengthVector(VT); 6435 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6436 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6437 } 6438 6439 SDLoc DL(Op); 6440 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6441 if (!IsFixed) 6442 return Val; 6443 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6444 } 6445 6446 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6447 // matched to a RVV indexed load. The RVV indexed load instructions only 6448 // support the "unsigned unscaled" addressing mode; indices are implicitly 6449 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6450 // signed or scaled indexing is extended to the XLEN value type and scaled 6451 // accordingly. 6452 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6453 SelectionDAG &DAG) const { 6454 SDLoc DL(Op); 6455 MVT VT = Op.getSimpleValueType(); 6456 6457 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6458 EVT MemVT = MemSD->getMemoryVT(); 6459 MachineMemOperand *MMO = MemSD->getMemOperand(); 6460 SDValue Chain = MemSD->getChain(); 6461 SDValue BasePtr = MemSD->getBasePtr(); 6462 6463 ISD::LoadExtType LoadExtType; 6464 SDValue Index, Mask, PassThru, VL; 6465 6466 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6467 Index = VPGN->getIndex(); 6468 Mask = VPGN->getMask(); 6469 PassThru = DAG.getUNDEF(VT); 6470 VL = VPGN->getVectorLength(); 6471 // VP doesn't support extending loads. 6472 LoadExtType = ISD::NON_EXTLOAD; 6473 } else { 6474 // Else it must be a MGATHER. 6475 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6476 Index = MGN->getIndex(); 6477 Mask = MGN->getMask(); 6478 PassThru = MGN->getPassThru(); 6479 LoadExtType = MGN->getExtensionType(); 6480 } 6481 6482 MVT IndexVT = Index.getSimpleValueType(); 6483 MVT XLenVT = Subtarget.getXLenVT(); 6484 6485 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6486 "Unexpected VTs!"); 6487 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6488 // Targets have to explicitly opt-in for extending vector loads. 6489 assert(LoadExtType == ISD::NON_EXTLOAD && 6490 "Unexpected extending MGATHER/VP_GATHER"); 6491 (void)LoadExtType; 6492 6493 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6494 // the selection of the masked intrinsics doesn't do this for us. 6495 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6496 6497 MVT ContainerVT = VT; 6498 if (VT.isFixedLengthVector()) { 6499 ContainerVT = getContainerForFixedLengthVector(VT); 6500 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6501 ContainerVT.getVectorElementCount()); 6502 6503 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6504 6505 if (!IsUnmasked) { 6506 MVT MaskVT = getMaskTypeFor(ContainerVT); 6507 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6508 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6509 } 6510 } 6511 6512 if (!VL) 6513 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6514 6515 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6516 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6517 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6518 VL); 6519 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6520 TrueMask, VL); 6521 } 6522 6523 unsigned IntID = 6524 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6525 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6526 if (IsUnmasked) 6527 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6528 else 6529 Ops.push_back(PassThru); 6530 Ops.push_back(BasePtr); 6531 Ops.push_back(Index); 6532 if (!IsUnmasked) 6533 Ops.push_back(Mask); 6534 Ops.push_back(VL); 6535 if (!IsUnmasked) 6536 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6537 6538 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6539 SDValue Result = 6540 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6541 Chain = Result.getValue(1); 6542 6543 if (VT.isFixedLengthVector()) 6544 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6545 6546 return DAG.getMergeValues({Result, Chain}, DL); 6547 } 6548 6549 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6550 // matched to a RVV indexed store. The RVV indexed store instructions only 6551 // support the "unsigned unscaled" addressing mode; indices are implicitly 6552 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6553 // signed or scaled indexing is extended to the XLEN value type and scaled 6554 // accordingly. 6555 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6556 SelectionDAG &DAG) const { 6557 SDLoc DL(Op); 6558 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6559 EVT MemVT = MemSD->getMemoryVT(); 6560 MachineMemOperand *MMO = MemSD->getMemOperand(); 6561 SDValue Chain = MemSD->getChain(); 6562 SDValue BasePtr = MemSD->getBasePtr(); 6563 6564 bool IsTruncatingStore = false; 6565 SDValue Index, Mask, Val, VL; 6566 6567 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6568 Index = VPSN->getIndex(); 6569 Mask = VPSN->getMask(); 6570 Val = VPSN->getValue(); 6571 VL = VPSN->getVectorLength(); 6572 // VP doesn't support truncating stores. 6573 IsTruncatingStore = false; 6574 } else { 6575 // Else it must be a MSCATTER. 6576 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6577 Index = MSN->getIndex(); 6578 Mask = MSN->getMask(); 6579 Val = MSN->getValue(); 6580 IsTruncatingStore = MSN->isTruncatingStore(); 6581 } 6582 6583 MVT VT = Val.getSimpleValueType(); 6584 MVT IndexVT = Index.getSimpleValueType(); 6585 MVT XLenVT = Subtarget.getXLenVT(); 6586 6587 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6588 "Unexpected VTs!"); 6589 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6590 // Targets have to explicitly opt-in for extending vector loads and 6591 // truncating vector stores. 6592 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6593 (void)IsTruncatingStore; 6594 6595 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6596 // the selection of the masked intrinsics doesn't do this for us. 6597 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6598 6599 MVT ContainerVT = VT; 6600 if (VT.isFixedLengthVector()) { 6601 ContainerVT = getContainerForFixedLengthVector(VT); 6602 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6603 ContainerVT.getVectorElementCount()); 6604 6605 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6606 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6607 6608 if (!IsUnmasked) { 6609 MVT MaskVT = getMaskTypeFor(ContainerVT); 6610 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6611 } 6612 } 6613 6614 if (!VL) 6615 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6616 6617 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6618 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6619 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6620 VL); 6621 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6622 TrueMask, VL); 6623 } 6624 6625 unsigned IntID = 6626 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6627 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6628 Ops.push_back(Val); 6629 Ops.push_back(BasePtr); 6630 Ops.push_back(Index); 6631 if (!IsUnmasked) 6632 Ops.push_back(Mask); 6633 Ops.push_back(VL); 6634 6635 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6636 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6637 } 6638 6639 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6640 SelectionDAG &DAG) const { 6641 const MVT XLenVT = Subtarget.getXLenVT(); 6642 SDLoc DL(Op); 6643 SDValue Chain = Op->getOperand(0); 6644 SDValue SysRegNo = DAG.getTargetConstant( 6645 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6646 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6647 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6648 6649 // Encoding used for rounding mode in RISCV differs from that used in 6650 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6651 // table, which consists of a sequence of 4-bit fields, each representing 6652 // corresponding FLT_ROUNDS mode. 6653 static const int Table = 6654 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6655 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6656 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6657 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6658 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6659 6660 SDValue Shift = 6661 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6662 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6663 DAG.getConstant(Table, DL, XLenVT), Shift); 6664 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6665 DAG.getConstant(7, DL, XLenVT)); 6666 6667 return DAG.getMergeValues({Masked, Chain}, DL); 6668 } 6669 6670 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6671 SelectionDAG &DAG) const { 6672 const MVT XLenVT = Subtarget.getXLenVT(); 6673 SDLoc DL(Op); 6674 SDValue Chain = Op->getOperand(0); 6675 SDValue RMValue = Op->getOperand(1); 6676 SDValue SysRegNo = DAG.getTargetConstant( 6677 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6678 6679 // Encoding used for rounding mode in RISCV differs from that used in 6680 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6681 // a table, which consists of a sequence of 4-bit fields, each representing 6682 // corresponding RISCV mode. 6683 static const unsigned Table = 6684 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6685 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6686 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6687 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6688 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6689 6690 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6691 DAG.getConstant(2, DL, XLenVT)); 6692 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6693 DAG.getConstant(Table, DL, XLenVT), Shift); 6694 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6695 DAG.getConstant(0x7, DL, XLenVT)); 6696 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6697 RMValue); 6698 } 6699 6700 SDValue RISCVTargetLowering::lowerEH_DWARF_CFA(SDValue Op, 6701 SelectionDAG &DAG) const { 6702 MachineFunction &MF = DAG.getMachineFunction(); 6703 6704 bool isRISCV64 = Subtarget.is64Bit(); 6705 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6706 6707 int FI = MF.getFrameInfo().CreateFixedObject(isRISCV64 ? 8 : 4, 0, false); 6708 return DAG.getFrameIndex(FI, PtrVT); 6709 } 6710 6711 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6712 switch (IntNo) { 6713 default: 6714 llvm_unreachable("Unexpected Intrinsic"); 6715 case Intrinsic::riscv_bcompress: 6716 return RISCVISD::BCOMPRESSW; 6717 case Intrinsic::riscv_bdecompress: 6718 return RISCVISD::BDECOMPRESSW; 6719 case Intrinsic::riscv_bfp: 6720 return RISCVISD::BFPW; 6721 case Intrinsic::riscv_fsl: 6722 return RISCVISD::FSLW; 6723 case Intrinsic::riscv_fsr: 6724 return RISCVISD::FSRW; 6725 } 6726 } 6727 6728 // Converts the given intrinsic to a i64 operation with any extension. 6729 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6730 unsigned IntNo) { 6731 SDLoc DL(N); 6732 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6733 // Deal with the Instruction Operands 6734 SmallVector<SDValue, 3> NewOps; 6735 for (SDValue Op : drop_begin(N->ops())) 6736 // Promote the operand to i64 type 6737 NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op)); 6738 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps); 6739 // ReplaceNodeResults requires we maintain the same type for the return value. 6740 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6741 } 6742 6743 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6744 // form of the given Opcode. 6745 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6746 switch (Opcode) { 6747 default: 6748 llvm_unreachable("Unexpected opcode"); 6749 case ISD::SHL: 6750 return RISCVISD::SLLW; 6751 case ISD::SRA: 6752 return RISCVISD::SRAW; 6753 case ISD::SRL: 6754 return RISCVISD::SRLW; 6755 case ISD::SDIV: 6756 return RISCVISD::DIVW; 6757 case ISD::UDIV: 6758 return RISCVISD::DIVUW; 6759 case ISD::UREM: 6760 return RISCVISD::REMUW; 6761 case ISD::ROTL: 6762 return RISCVISD::ROLW; 6763 case ISD::ROTR: 6764 return RISCVISD::RORW; 6765 } 6766 } 6767 6768 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6769 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6770 // otherwise be promoted to i64, making it difficult to select the 6771 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6772 // type i8/i16/i32 is lost. 6773 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6774 unsigned ExtOpc = ISD::ANY_EXTEND) { 6775 SDLoc DL(N); 6776 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6777 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6778 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6779 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6780 // ReplaceNodeResults requires we maintain the same type for the return value. 6781 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6782 } 6783 6784 // Converts the given 32-bit operation to a i64 operation with signed extension 6785 // semantic to reduce the signed extension instructions. 6786 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6787 SDLoc DL(N); 6788 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6789 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6790 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6791 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6792 DAG.getValueType(MVT::i32)); 6793 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6794 } 6795 6796 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6797 SmallVectorImpl<SDValue> &Results, 6798 SelectionDAG &DAG) const { 6799 SDLoc DL(N); 6800 switch (N->getOpcode()) { 6801 default: 6802 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6803 case ISD::STRICT_FP_TO_SINT: 6804 case ISD::STRICT_FP_TO_UINT: 6805 case ISD::FP_TO_SINT: 6806 case ISD::FP_TO_UINT: { 6807 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6808 "Unexpected custom legalisation"); 6809 bool IsStrict = N->isStrictFPOpcode(); 6810 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6811 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6812 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6813 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6814 TargetLowering::TypeSoftenFloat) { 6815 if (!isTypeLegal(Op0.getValueType())) 6816 return; 6817 if (IsStrict) { 6818 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6819 : RISCVISD::STRICT_FCVT_WU_RV64; 6820 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6821 SDValue Res = DAG.getNode( 6822 Opc, DL, VTs, N->getOperand(0), Op0, 6823 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6824 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6825 Results.push_back(Res.getValue(1)); 6826 return; 6827 } 6828 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6829 SDValue Res = 6830 DAG.getNode(Opc, DL, MVT::i64, Op0, 6831 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6832 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6833 return; 6834 } 6835 // If the FP type needs to be softened, emit a library call using the 'si' 6836 // version. If we left it to default legalization we'd end up with 'di'. If 6837 // the FP type doesn't need to be softened just let generic type 6838 // legalization promote the result type. 6839 RTLIB::Libcall LC; 6840 if (IsSigned) 6841 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6842 else 6843 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6844 MakeLibCallOptions CallOptions; 6845 EVT OpVT = Op0.getValueType(); 6846 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6847 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6848 SDValue Result; 6849 std::tie(Result, Chain) = 6850 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6851 Results.push_back(Result); 6852 if (IsStrict) 6853 Results.push_back(Chain); 6854 break; 6855 } 6856 case ISD::READCYCLECOUNTER: { 6857 assert(!Subtarget.is64Bit() && 6858 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6859 6860 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6861 SDValue RCW = 6862 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6863 6864 Results.push_back( 6865 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6866 Results.push_back(RCW.getValue(2)); 6867 break; 6868 } 6869 case ISD::MUL: { 6870 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6871 unsigned XLen = Subtarget.getXLen(); 6872 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6873 if (Size > XLen) { 6874 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6875 SDValue LHS = N->getOperand(0); 6876 SDValue RHS = N->getOperand(1); 6877 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6878 6879 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6880 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6881 // We need exactly one side to be unsigned. 6882 if (LHSIsU == RHSIsU) 6883 return; 6884 6885 auto MakeMULPair = [&](SDValue S, SDValue U) { 6886 MVT XLenVT = Subtarget.getXLenVT(); 6887 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6888 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6889 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6890 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6891 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6892 }; 6893 6894 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6895 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6896 6897 // The other operand should be signed, but still prefer MULH when 6898 // possible. 6899 if (RHSIsU && LHSIsS && !RHSIsS) 6900 Results.push_back(MakeMULPair(LHS, RHS)); 6901 else if (LHSIsU && RHSIsS && !LHSIsS) 6902 Results.push_back(MakeMULPair(RHS, LHS)); 6903 6904 return; 6905 } 6906 LLVM_FALLTHROUGH; 6907 } 6908 case ISD::ADD: 6909 case ISD::SUB: 6910 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6911 "Unexpected custom legalisation"); 6912 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6913 break; 6914 case ISD::SHL: 6915 case ISD::SRA: 6916 case ISD::SRL: 6917 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6918 "Unexpected custom legalisation"); 6919 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6920 // If we can use a BSET instruction, allow default promotion to apply. 6921 if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() && 6922 isOneConstant(N->getOperand(0))) 6923 break; 6924 Results.push_back(customLegalizeToWOp(N, DAG)); 6925 break; 6926 } 6927 6928 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6929 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6930 // shift amount. 6931 if (N->getOpcode() == ISD::SHL) { 6932 SDLoc DL(N); 6933 SDValue NewOp0 = 6934 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6935 SDValue NewOp1 = 6936 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6937 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6938 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6939 DAG.getValueType(MVT::i32)); 6940 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6941 } 6942 6943 break; 6944 case ISD::ROTL: 6945 case ISD::ROTR: 6946 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6947 "Unexpected custom legalisation"); 6948 Results.push_back(customLegalizeToWOp(N, DAG)); 6949 break; 6950 case ISD::CTTZ: 6951 case ISD::CTTZ_ZERO_UNDEF: 6952 case ISD::CTLZ: 6953 case ISD::CTLZ_ZERO_UNDEF: { 6954 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6955 "Unexpected custom legalisation"); 6956 6957 SDValue NewOp0 = 6958 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6959 bool IsCTZ = 6960 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6961 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6962 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6963 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6964 return; 6965 } 6966 case ISD::SDIV: 6967 case ISD::UDIV: 6968 case ISD::UREM: { 6969 MVT VT = N->getSimpleValueType(0); 6970 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6971 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6972 "Unexpected custom legalisation"); 6973 // Don't promote division/remainder by constant since we should expand those 6974 // to multiply by magic constant. 6975 // FIXME: What if the expansion is disabled for minsize. 6976 if (N->getOperand(1).getOpcode() == ISD::Constant) 6977 return; 6978 6979 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6980 // the upper 32 bits. For other types we need to sign or zero extend 6981 // based on the opcode. 6982 unsigned ExtOpc = ISD::ANY_EXTEND; 6983 if (VT != MVT::i32) 6984 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6985 : ISD::ZERO_EXTEND; 6986 6987 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6988 break; 6989 } 6990 case ISD::UADDO: 6991 case ISD::USUBO: { 6992 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6993 "Unexpected custom legalisation"); 6994 bool IsAdd = N->getOpcode() == ISD::UADDO; 6995 // Create an ADDW or SUBW. 6996 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6997 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6998 SDValue Res = 6999 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 7000 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 7001 DAG.getValueType(MVT::i32)); 7002 7003 SDValue Overflow; 7004 if (IsAdd && isOneConstant(RHS)) { 7005 // Special case uaddo X, 1 overflowed if the addition result is 0. 7006 // The general case (X + C) < C is not necessarily beneficial. Although we 7007 // reduce the live range of X, we may introduce the materialization of 7008 // constant C, especially when the setcc result is used by branch. We have 7009 // no compare with constant and branch instructions. 7010 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, 7011 DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ); 7012 } else { 7013 // Sign extend the LHS and perform an unsigned compare with the ADDW 7014 // result. Since the inputs are sign extended from i32, this is equivalent 7015 // to comparing the lower 32 bits. 7016 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 7017 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 7018 IsAdd ? ISD::SETULT : ISD::SETUGT); 7019 } 7020 7021 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7022 Results.push_back(Overflow); 7023 return; 7024 } 7025 case ISD::UADDSAT: 7026 case ISD::USUBSAT: { 7027 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7028 "Unexpected custom legalisation"); 7029 if (Subtarget.hasStdExtZbb()) { 7030 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 7031 // sign extend allows overflow of the lower 32 bits to be detected on 7032 // the promoted size. 7033 SDValue LHS = 7034 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 7035 SDValue RHS = 7036 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 7037 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 7038 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7039 return; 7040 } 7041 7042 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 7043 // promotion for UADDO/USUBO. 7044 Results.push_back(expandAddSubSat(N, DAG)); 7045 return; 7046 } 7047 case ISD::ABS: { 7048 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7049 "Unexpected custom legalisation"); 7050 7051 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 7052 7053 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7054 7055 // Freeze the source so we can increase it's use count. 7056 Src = DAG.getFreeze(Src); 7057 7058 // Copy sign bit to all bits using the sraiw pattern. 7059 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 7060 DAG.getValueType(MVT::i32)); 7061 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 7062 DAG.getConstant(31, DL, MVT::i64)); 7063 7064 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 7065 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 7066 7067 // NOTE: The result is only required to be anyextended, but sext is 7068 // consistent with type legalization of sub. 7069 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 7070 DAG.getValueType(MVT::i32)); 7071 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 7072 return; 7073 } 7074 case ISD::BITCAST: { 7075 EVT VT = N->getValueType(0); 7076 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 7077 SDValue Op0 = N->getOperand(0); 7078 EVT Op0VT = Op0.getValueType(); 7079 MVT XLenVT = Subtarget.getXLenVT(); 7080 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 7081 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 7082 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 7083 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 7084 Subtarget.hasStdExtF()) { 7085 SDValue FPConv = 7086 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 7087 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 7088 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 7089 isTypeLegal(Op0VT)) { 7090 // Custom-legalize bitcasts from fixed-length vector types to illegal 7091 // scalar types in order to improve codegen. Bitcast the vector to a 7092 // one-element vector type whose element type is the same as the result 7093 // type, and extract the first element. 7094 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 7095 if (isTypeLegal(BVT)) { 7096 SDValue BVec = DAG.getBitcast(BVT, Op0); 7097 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 7098 DAG.getConstant(0, DL, XLenVT))); 7099 } 7100 } 7101 break; 7102 } 7103 case RISCVISD::GREV: 7104 case RISCVISD::GORC: 7105 case RISCVISD::SHFL: { 7106 MVT VT = N->getSimpleValueType(0); 7107 MVT XLenVT = Subtarget.getXLenVT(); 7108 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) && 7109 "Unexpected custom legalisation"); 7110 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 7111 assert((Subtarget.hasStdExtZbp() || 7112 (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV && 7113 N->getConstantOperandVal(1) == 7)) && 7114 "Unexpected extension"); 7115 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7116 SDValue NewOp1 = 7117 DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1)); 7118 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1); 7119 // ReplaceNodeResults requires we maintain the same type for the return 7120 // value. 7121 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes)); 7122 break; 7123 } 7124 case ISD::BSWAP: 7125 case ISD::BITREVERSE: { 7126 MVT VT = N->getSimpleValueType(0); 7127 MVT XLenVT = Subtarget.getXLenVT(); 7128 assert((VT == MVT::i8 || VT == MVT::i16 || 7129 (VT == MVT::i32 && Subtarget.is64Bit())) && 7130 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 7131 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7132 unsigned Imm = VT.getSizeInBits() - 1; 7133 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 7134 if (N->getOpcode() == ISD::BSWAP) 7135 Imm &= ~0x7U; 7136 SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0, 7137 DAG.getConstant(Imm, DL, XLenVT)); 7138 // ReplaceNodeResults requires we maintain the same type for the return 7139 // value. 7140 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 7141 break; 7142 } 7143 case ISD::FSHL: 7144 case ISD::FSHR: { 7145 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7146 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 7147 SDValue NewOp0 = 7148 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7149 SDValue NewOp1 = 7150 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7151 SDValue NewShAmt = 7152 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7153 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 7154 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 7155 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 7156 DAG.getConstant(0x1f, DL, MVT::i64)); 7157 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 7158 // instruction use different orders. fshl will return its first operand for 7159 // shift of zero, fshr will return its second operand. fsl and fsr both 7160 // return rs1 so the ISD nodes need to have different operand orders. 7161 // Shift amount is in rs2. 7162 unsigned Opc = RISCVISD::FSLW; 7163 if (N->getOpcode() == ISD::FSHR) { 7164 std::swap(NewOp0, NewOp1); 7165 Opc = RISCVISD::FSRW; 7166 } 7167 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 7168 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 7169 break; 7170 } 7171 case ISD::EXTRACT_VECTOR_ELT: { 7172 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 7173 // type is illegal (currently only vXi64 RV32). 7174 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 7175 // transferred to the destination register. We issue two of these from the 7176 // upper- and lower- halves of the SEW-bit vector element, slid down to the 7177 // first element. 7178 SDValue Vec = N->getOperand(0); 7179 SDValue Idx = N->getOperand(1); 7180 7181 // The vector type hasn't been legalized yet so we can't issue target 7182 // specific nodes if it needs legalization. 7183 // FIXME: We would manually legalize if it's important. 7184 if (!isTypeLegal(Vec.getValueType())) 7185 return; 7186 7187 MVT VecVT = Vec.getSimpleValueType(); 7188 7189 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 7190 VecVT.getVectorElementType() == MVT::i64 && 7191 "Unexpected EXTRACT_VECTOR_ELT legalization"); 7192 7193 // If this is a fixed vector, we need to convert it to a scalable vector. 7194 MVT ContainerVT = VecVT; 7195 if (VecVT.isFixedLengthVector()) { 7196 ContainerVT = getContainerForFixedLengthVector(VecVT); 7197 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 7198 } 7199 7200 MVT XLenVT = Subtarget.getXLenVT(); 7201 7202 // Use a VL of 1 to avoid processing more elements than we need. 7203 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7204 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 7205 7206 // Unless the index is known to be 0, we must slide the vector down to get 7207 // the desired element into index 0. 7208 if (!isNullConstant(Idx)) { 7209 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 7210 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 7211 } 7212 7213 // Extract the lower XLEN bits of the correct vector element. 7214 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7215 7216 // To extract the upper XLEN bits of the vector element, shift the first 7217 // element right by 32 bits and re-extract the lower XLEN bits. 7218 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 7219 DAG.getUNDEF(ContainerVT), 7220 DAG.getConstant(32, DL, XLenVT), VL); 7221 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 7222 ThirtyTwoV, Mask, VL); 7223 7224 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7225 7226 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7227 break; 7228 } 7229 case ISD::INTRINSIC_WO_CHAIN: { 7230 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7231 switch (IntNo) { 7232 default: 7233 llvm_unreachable( 7234 "Don't know how to custom type legalize this intrinsic!"); 7235 case Intrinsic::riscv_grev: 7236 case Intrinsic::riscv_gorc: { 7237 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7238 "Unexpected custom legalisation"); 7239 SDValue NewOp1 = 7240 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7241 SDValue NewOp2 = 7242 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7243 unsigned Opc = 7244 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 7245 // If the control is a constant, promote the node by clearing any extra 7246 // bits bits in the control. isel will form greviw/gorciw if the result is 7247 // sign extended. 7248 if (isa<ConstantSDNode>(NewOp2)) { 7249 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7250 DAG.getConstant(0x1f, DL, MVT::i64)); 7251 Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 7252 } 7253 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7254 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7255 break; 7256 } 7257 case Intrinsic::riscv_bcompress: 7258 case Intrinsic::riscv_bdecompress: 7259 case Intrinsic::riscv_bfp: 7260 case Intrinsic::riscv_fsl: 7261 case Intrinsic::riscv_fsr: { 7262 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7263 "Unexpected custom legalisation"); 7264 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 7265 break; 7266 } 7267 case Intrinsic::riscv_orc_b: { 7268 // Lower to the GORCI encoding for orc.b with the operand extended. 7269 SDValue NewOp = 7270 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7271 SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp, 7272 DAG.getConstant(7, DL, MVT::i64)); 7273 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7274 return; 7275 } 7276 case Intrinsic::riscv_shfl: 7277 case Intrinsic::riscv_unshfl: { 7278 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7279 "Unexpected custom legalisation"); 7280 SDValue NewOp1 = 7281 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7282 SDValue NewOp2 = 7283 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7284 unsigned Opc = 7285 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 7286 // There is no (UN)SHFLIW. If the control word is a constant, we can use 7287 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 7288 // will be shuffled the same way as the lower 32 bit half, but the two 7289 // halves won't cross. 7290 if (isa<ConstantSDNode>(NewOp2)) { 7291 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7292 DAG.getConstant(0xf, DL, MVT::i64)); 7293 Opc = 7294 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 7295 } 7296 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7297 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7298 break; 7299 } 7300 case Intrinsic::riscv_vmv_x_s: { 7301 EVT VT = N->getValueType(0); 7302 MVT XLenVT = Subtarget.getXLenVT(); 7303 if (VT.bitsLT(XLenVT)) { 7304 // Simple case just extract using vmv.x.s and truncate. 7305 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 7306 Subtarget.getXLenVT(), N->getOperand(1)); 7307 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 7308 return; 7309 } 7310 7311 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 7312 "Unexpected custom legalization"); 7313 7314 // We need to do the move in two steps. 7315 SDValue Vec = N->getOperand(1); 7316 MVT VecVT = Vec.getSimpleValueType(); 7317 7318 // First extract the lower XLEN bits of the element. 7319 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7320 7321 // To extract the upper XLEN bits of the vector element, shift the first 7322 // element right by 32 bits and re-extract the lower XLEN bits. 7323 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7324 SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG); 7325 7326 SDValue ThirtyTwoV = 7327 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 7328 DAG.getConstant(32, DL, XLenVT), VL); 7329 SDValue LShr32 = 7330 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 7331 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7332 7333 Results.push_back( 7334 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7335 break; 7336 } 7337 } 7338 break; 7339 } 7340 case ISD::VECREDUCE_ADD: 7341 case ISD::VECREDUCE_AND: 7342 case ISD::VECREDUCE_OR: 7343 case ISD::VECREDUCE_XOR: 7344 case ISD::VECREDUCE_SMAX: 7345 case ISD::VECREDUCE_UMAX: 7346 case ISD::VECREDUCE_SMIN: 7347 case ISD::VECREDUCE_UMIN: 7348 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 7349 Results.push_back(V); 7350 break; 7351 case ISD::VP_REDUCE_ADD: 7352 case ISD::VP_REDUCE_AND: 7353 case ISD::VP_REDUCE_OR: 7354 case ISD::VP_REDUCE_XOR: 7355 case ISD::VP_REDUCE_SMAX: 7356 case ISD::VP_REDUCE_UMAX: 7357 case ISD::VP_REDUCE_SMIN: 7358 case ISD::VP_REDUCE_UMIN: 7359 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 7360 Results.push_back(V); 7361 break; 7362 case ISD::FLT_ROUNDS_: { 7363 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7364 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7365 Results.push_back(Res.getValue(0)); 7366 Results.push_back(Res.getValue(1)); 7367 break; 7368 } 7369 } 7370 } 7371 7372 // A structure to hold one of the bit-manipulation patterns below. Together, a 7373 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7374 // (or (and (shl x, 1), 0xAAAAAAAA), 7375 // (and (srl x, 1), 0x55555555)) 7376 struct RISCVBitmanipPat { 7377 SDValue Op; 7378 unsigned ShAmt; 7379 bool IsSHL; 7380 7381 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7382 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7383 } 7384 }; 7385 7386 // Matches patterns of the form 7387 // (and (shl x, C2), (C1 << C2)) 7388 // (and (srl x, C2), C1) 7389 // (shl (and x, C1), C2) 7390 // (srl (and x, (C1 << C2)), C2) 7391 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7392 // The expected masks for each shift amount are specified in BitmanipMasks where 7393 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7394 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7395 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7396 // XLen is 64. 7397 static Optional<RISCVBitmanipPat> 7398 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7399 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7400 "Unexpected number of masks"); 7401 Optional<uint64_t> Mask; 7402 // Optionally consume a mask around the shift operation. 7403 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7404 Mask = Op.getConstantOperandVal(1); 7405 Op = Op.getOperand(0); 7406 } 7407 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7408 return None; 7409 bool IsSHL = Op.getOpcode() == ISD::SHL; 7410 7411 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7412 return None; 7413 uint64_t ShAmt = Op.getConstantOperandVal(1); 7414 7415 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7416 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7417 return None; 7418 // If we don't have enough masks for 64 bit, then we must be trying to 7419 // match SHFL so we're only allowed to shift 1/4 of the width. 7420 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7421 return None; 7422 7423 SDValue Src = Op.getOperand(0); 7424 7425 // The expected mask is shifted left when the AND is found around SHL 7426 // patterns. 7427 // ((x >> 1) & 0x55555555) 7428 // ((x << 1) & 0xAAAAAAAA) 7429 bool SHLExpMask = IsSHL; 7430 7431 if (!Mask) { 7432 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7433 // the mask is all ones: consume that now. 7434 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7435 Mask = Src.getConstantOperandVal(1); 7436 Src = Src.getOperand(0); 7437 // The expected mask is now in fact shifted left for SRL, so reverse the 7438 // decision. 7439 // ((x & 0xAAAAAAAA) >> 1) 7440 // ((x & 0x55555555) << 1) 7441 SHLExpMask = !SHLExpMask; 7442 } else { 7443 // Use a default shifted mask of all-ones if there's no AND, truncated 7444 // down to the expected width. This simplifies the logic later on. 7445 Mask = maskTrailingOnes<uint64_t>(Width); 7446 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7447 } 7448 } 7449 7450 unsigned MaskIdx = Log2_32(ShAmt); 7451 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7452 7453 if (SHLExpMask) 7454 ExpMask <<= ShAmt; 7455 7456 if (Mask != ExpMask) 7457 return None; 7458 7459 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7460 } 7461 7462 // Matches any of the following bit-manipulation patterns: 7463 // (and (shl x, 1), (0x55555555 << 1)) 7464 // (and (srl x, 1), 0x55555555) 7465 // (shl (and x, 0x55555555), 1) 7466 // (srl (and x, (0x55555555 << 1)), 1) 7467 // where the shift amount and mask may vary thus: 7468 // [1] = 0x55555555 / 0xAAAAAAAA 7469 // [2] = 0x33333333 / 0xCCCCCCCC 7470 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7471 // [8] = 0x00FF00FF / 0xFF00FF00 7472 // [16] = 0x0000FFFF / 0xFFFFFFFF 7473 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7474 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7475 // These are the unshifted masks which we use to match bit-manipulation 7476 // patterns. They may be shifted left in certain circumstances. 7477 static const uint64_t BitmanipMasks[] = { 7478 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7479 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7480 7481 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7482 } 7483 7484 // Try to fold (<bop> x, (reduction.<bop> vec, start)) 7485 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) { 7486 auto BinOpToRVVReduce = [](unsigned Opc) { 7487 switch (Opc) { 7488 default: 7489 llvm_unreachable("Unhandled binary to transfrom reduction"); 7490 case ISD::ADD: 7491 return RISCVISD::VECREDUCE_ADD_VL; 7492 case ISD::UMAX: 7493 return RISCVISD::VECREDUCE_UMAX_VL; 7494 case ISD::SMAX: 7495 return RISCVISD::VECREDUCE_SMAX_VL; 7496 case ISD::UMIN: 7497 return RISCVISD::VECREDUCE_UMIN_VL; 7498 case ISD::SMIN: 7499 return RISCVISD::VECREDUCE_SMIN_VL; 7500 case ISD::AND: 7501 return RISCVISD::VECREDUCE_AND_VL; 7502 case ISD::OR: 7503 return RISCVISD::VECREDUCE_OR_VL; 7504 case ISD::XOR: 7505 return RISCVISD::VECREDUCE_XOR_VL; 7506 case ISD::FADD: 7507 return RISCVISD::VECREDUCE_FADD_VL; 7508 case ISD::FMAXNUM: 7509 return RISCVISD::VECREDUCE_FMAX_VL; 7510 case ISD::FMINNUM: 7511 return RISCVISD::VECREDUCE_FMIN_VL; 7512 } 7513 }; 7514 7515 auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) { 7516 return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7517 isNullConstant(V.getOperand(1)) && 7518 V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc); 7519 }; 7520 7521 unsigned Opc = N->getOpcode(); 7522 unsigned ReduceIdx; 7523 if (IsReduction(N->getOperand(0), Opc)) 7524 ReduceIdx = 0; 7525 else if (IsReduction(N->getOperand(1), Opc)) 7526 ReduceIdx = 1; 7527 else 7528 return SDValue(); 7529 7530 // Skip if FADD disallows reassociation but the combiner needs. 7531 if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation()) 7532 return SDValue(); 7533 7534 SDValue Extract = N->getOperand(ReduceIdx); 7535 SDValue Reduce = Extract.getOperand(0); 7536 if (!Reduce.hasOneUse()) 7537 return SDValue(); 7538 7539 SDValue ScalarV = Reduce.getOperand(2); 7540 7541 // Make sure that ScalarV is a splat with VL=1. 7542 if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL && 7543 ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL && 7544 ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL) 7545 return SDValue(); 7546 7547 if (!isOneConstant(ScalarV.getOperand(2))) 7548 return SDValue(); 7549 7550 // TODO: Deal with value other than neutral element. 7551 auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) { 7552 if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() && 7553 isNullFPConstant(V)) 7554 return true; 7555 return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(), 7556 N->getFlags()) == V; 7557 }; 7558 7559 // Check the scalar of ScalarV is neutral element 7560 if (!IsRVVNeutralElement(N, ScalarV.getOperand(1))) 7561 return SDValue(); 7562 7563 if (!ScalarV.hasOneUse()) 7564 return SDValue(); 7565 7566 EVT SplatVT = ScalarV.getValueType(); 7567 SDValue NewStart = N->getOperand(1 - ReduceIdx); 7568 unsigned SplatOpc = RISCVISD::VFMV_S_F_VL; 7569 if (SplatVT.isInteger()) { 7570 auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode()); 7571 if (!C || C->isZero() || !isInt<5>(C->getSExtValue())) 7572 SplatOpc = RISCVISD::VMV_S_X_VL; 7573 else 7574 SplatOpc = RISCVISD::VMV_V_X_VL; 7575 } 7576 7577 SDValue NewScalarV = 7578 DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart, 7579 ScalarV.getOperand(2)); 7580 SDValue NewReduce = 7581 DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(), 7582 Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV, 7583 Reduce.getOperand(3), Reduce.getOperand(4)); 7584 return DAG.getNode(Extract.getOpcode(), SDLoc(Extract), 7585 Extract.getValueType(), NewReduce, Extract.getOperand(1)); 7586 } 7587 7588 // Match the following pattern as a GREVI(W) operation 7589 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7590 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7591 const RISCVSubtarget &Subtarget) { 7592 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7593 EVT VT = Op.getValueType(); 7594 7595 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7596 auto LHS = matchGREVIPat(Op.getOperand(0)); 7597 auto RHS = matchGREVIPat(Op.getOperand(1)); 7598 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7599 SDLoc DL(Op); 7600 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7601 DAG.getConstant(LHS->ShAmt, DL, VT)); 7602 } 7603 } 7604 return SDValue(); 7605 } 7606 7607 // Matches any the following pattern as a GORCI(W) operation 7608 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7609 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7610 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7611 // Note that with the variant of 3., 7612 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7613 // the inner pattern will first be matched as GREVI and then the outer 7614 // pattern will be matched to GORC via the first rule above. 7615 // 4. (or (rotl/rotr x, bitwidth/2), x) 7616 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7617 const RISCVSubtarget &Subtarget) { 7618 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7619 EVT VT = Op.getValueType(); 7620 7621 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7622 SDLoc DL(Op); 7623 SDValue Op0 = Op.getOperand(0); 7624 SDValue Op1 = Op.getOperand(1); 7625 7626 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7627 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7628 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7629 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7630 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7631 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7632 if ((Reverse.getOpcode() == ISD::ROTL || 7633 Reverse.getOpcode() == ISD::ROTR) && 7634 Reverse.getOperand(0) == X && 7635 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7636 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7637 if (RotAmt == (VT.getSizeInBits() / 2)) 7638 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7639 DAG.getConstant(RotAmt, DL, VT)); 7640 } 7641 return SDValue(); 7642 }; 7643 7644 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7645 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7646 return V; 7647 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7648 return V; 7649 7650 // OR is commutable so canonicalize its OR operand to the left 7651 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7652 std::swap(Op0, Op1); 7653 if (Op0.getOpcode() != ISD::OR) 7654 return SDValue(); 7655 SDValue OrOp0 = Op0.getOperand(0); 7656 SDValue OrOp1 = Op0.getOperand(1); 7657 auto LHS = matchGREVIPat(OrOp0); 7658 // OR is commutable so swap the operands and try again: x might have been 7659 // on the left 7660 if (!LHS) { 7661 std::swap(OrOp0, OrOp1); 7662 LHS = matchGREVIPat(OrOp0); 7663 } 7664 auto RHS = matchGREVIPat(Op1); 7665 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7666 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7667 DAG.getConstant(LHS->ShAmt, DL, VT)); 7668 } 7669 } 7670 return SDValue(); 7671 } 7672 7673 // Matches any of the following bit-manipulation patterns: 7674 // (and (shl x, 1), (0x22222222 << 1)) 7675 // (and (srl x, 1), 0x22222222) 7676 // (shl (and x, 0x22222222), 1) 7677 // (srl (and x, (0x22222222 << 1)), 1) 7678 // where the shift amount and mask may vary thus: 7679 // [1] = 0x22222222 / 0x44444444 7680 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7681 // [4] = 0x00F000F0 / 0x0F000F00 7682 // [8] = 0x0000FF00 / 0x00FF0000 7683 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7684 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7685 // These are the unshifted masks which we use to match bit-manipulation 7686 // patterns. They may be shifted left in certain circumstances. 7687 static const uint64_t BitmanipMasks[] = { 7688 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7689 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7690 7691 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7692 } 7693 7694 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7695 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7696 const RISCVSubtarget &Subtarget) { 7697 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7698 EVT VT = Op.getValueType(); 7699 7700 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7701 return SDValue(); 7702 7703 SDValue Op0 = Op.getOperand(0); 7704 SDValue Op1 = Op.getOperand(1); 7705 7706 // Or is commutable so canonicalize the second OR to the LHS. 7707 if (Op0.getOpcode() != ISD::OR) 7708 std::swap(Op0, Op1); 7709 if (Op0.getOpcode() != ISD::OR) 7710 return SDValue(); 7711 7712 // We found an inner OR, so our operands are the operands of the inner OR 7713 // and the other operand of the outer OR. 7714 SDValue A = Op0.getOperand(0); 7715 SDValue B = Op0.getOperand(1); 7716 SDValue C = Op1; 7717 7718 auto Match1 = matchSHFLPat(A); 7719 auto Match2 = matchSHFLPat(B); 7720 7721 // If neither matched, we failed. 7722 if (!Match1 && !Match2) 7723 return SDValue(); 7724 7725 // We had at least one match. if one failed, try the remaining C operand. 7726 if (!Match1) { 7727 std::swap(A, C); 7728 Match1 = matchSHFLPat(A); 7729 if (!Match1) 7730 return SDValue(); 7731 } else if (!Match2) { 7732 std::swap(B, C); 7733 Match2 = matchSHFLPat(B); 7734 if (!Match2) 7735 return SDValue(); 7736 } 7737 assert(Match1 && Match2); 7738 7739 // Make sure our matches pair up. 7740 if (!Match1->formsPairWith(*Match2)) 7741 return SDValue(); 7742 7743 // All the remains is to make sure C is an AND with the same input, that masks 7744 // out the bits that are being shuffled. 7745 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7746 C.getOperand(0) != Match1->Op) 7747 return SDValue(); 7748 7749 uint64_t Mask = C.getConstantOperandVal(1); 7750 7751 static const uint64_t BitmanipMasks[] = { 7752 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7753 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7754 }; 7755 7756 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7757 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7758 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7759 7760 if (Mask != ExpMask) 7761 return SDValue(); 7762 7763 SDLoc DL(Op); 7764 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7765 DAG.getConstant(Match1->ShAmt, DL, VT)); 7766 } 7767 7768 // Optimize (add (shl x, c0), (shl y, c1)) -> 7769 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7770 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7771 const RISCVSubtarget &Subtarget) { 7772 // Perform this optimization only in the zba extension. 7773 if (!Subtarget.hasStdExtZba()) 7774 return SDValue(); 7775 7776 // Skip for vector types and larger types. 7777 EVT VT = N->getValueType(0); 7778 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7779 return SDValue(); 7780 7781 // The two operand nodes must be SHL and have no other use. 7782 SDValue N0 = N->getOperand(0); 7783 SDValue N1 = N->getOperand(1); 7784 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7785 !N0->hasOneUse() || !N1->hasOneUse()) 7786 return SDValue(); 7787 7788 // Check c0 and c1. 7789 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7790 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7791 if (!N0C || !N1C) 7792 return SDValue(); 7793 int64_t C0 = N0C->getSExtValue(); 7794 int64_t C1 = N1C->getSExtValue(); 7795 if (C0 <= 0 || C1 <= 0) 7796 return SDValue(); 7797 7798 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7799 int64_t Bits = std::min(C0, C1); 7800 int64_t Diff = std::abs(C0 - C1); 7801 if (Diff != 1 && Diff != 2 && Diff != 3) 7802 return SDValue(); 7803 7804 // Build nodes. 7805 SDLoc DL(N); 7806 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7807 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7808 SDValue NA0 = 7809 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7810 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7811 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7812 } 7813 7814 // Combine 7815 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7816 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7817 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7818 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7819 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7820 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7821 // The grev patterns represents BSWAP. 7822 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7823 // off the grev. 7824 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7825 const RISCVSubtarget &Subtarget) { 7826 bool IsWInstruction = 7827 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7828 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7829 IsWInstruction) && 7830 "Unexpected opcode!"); 7831 SDValue Src = N->getOperand(0); 7832 EVT VT = N->getValueType(0); 7833 SDLoc DL(N); 7834 7835 if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV) 7836 return SDValue(); 7837 7838 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7839 !isa<ConstantSDNode>(Src.getOperand(1))) 7840 return SDValue(); 7841 7842 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7843 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7844 7845 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7846 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7847 unsigned ShAmt1 = N->getConstantOperandVal(1); 7848 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7849 if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7850 return SDValue(); 7851 7852 Src = Src.getOperand(0); 7853 7854 // Toggle bit the MSB of the shift. 7855 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7856 if (CombinedShAmt == 0) 7857 return Src; 7858 7859 SDValue Res = DAG.getNode( 7860 RISCVISD::GREV, DL, VT, Src, 7861 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7862 if (!IsWInstruction) 7863 return Res; 7864 7865 // Sign extend the result to match the behavior of the rotate. This will be 7866 // selected to GREVIW in isel. 7867 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res, 7868 DAG.getValueType(MVT::i32)); 7869 } 7870 7871 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7872 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7873 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7874 // not undo itself, but they are redundant. 7875 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7876 bool IsGORC = N->getOpcode() == RISCVISD::GORC; 7877 assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode"); 7878 SDValue Src = N->getOperand(0); 7879 7880 if (Src.getOpcode() != N->getOpcode()) 7881 return SDValue(); 7882 7883 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7884 !isa<ConstantSDNode>(Src.getOperand(1))) 7885 return SDValue(); 7886 7887 unsigned ShAmt1 = N->getConstantOperandVal(1); 7888 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7889 Src = Src.getOperand(0); 7890 7891 unsigned CombinedShAmt; 7892 if (IsGORC) 7893 CombinedShAmt = ShAmt1 | ShAmt2; 7894 else 7895 CombinedShAmt = ShAmt1 ^ ShAmt2; 7896 7897 if (CombinedShAmt == 0) 7898 return Src; 7899 7900 SDLoc DL(N); 7901 return DAG.getNode( 7902 N->getOpcode(), DL, N->getValueType(0), Src, 7903 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7904 } 7905 7906 // Combine a constant select operand into its use: 7907 // 7908 // (and (select cond, -1, c), x) 7909 // -> (select cond, x, (and x, c)) [AllOnes=1] 7910 // (or (select cond, 0, c), x) 7911 // -> (select cond, x, (or x, c)) [AllOnes=0] 7912 // (xor (select cond, 0, c), x) 7913 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7914 // (add (select cond, 0, c), x) 7915 // -> (select cond, x, (add x, c)) [AllOnes=0] 7916 // (sub x, (select cond, 0, c)) 7917 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7918 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7919 SelectionDAG &DAG, bool AllOnes) { 7920 EVT VT = N->getValueType(0); 7921 7922 // Skip vectors. 7923 if (VT.isVector()) 7924 return SDValue(); 7925 7926 if ((Slct.getOpcode() != ISD::SELECT && 7927 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7928 !Slct.hasOneUse()) 7929 return SDValue(); 7930 7931 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7932 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7933 }; 7934 7935 bool SwapSelectOps; 7936 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7937 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7938 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7939 SDValue NonConstantVal; 7940 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7941 SwapSelectOps = false; 7942 NonConstantVal = FalseVal; 7943 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7944 SwapSelectOps = true; 7945 NonConstantVal = TrueVal; 7946 } else 7947 return SDValue(); 7948 7949 // Slct is now know to be the desired identity constant when CC is true. 7950 TrueVal = OtherOp; 7951 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7952 // Unless SwapSelectOps says the condition should be false. 7953 if (SwapSelectOps) 7954 std::swap(TrueVal, FalseVal); 7955 7956 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7957 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7958 {Slct.getOperand(0), Slct.getOperand(1), 7959 Slct.getOperand(2), TrueVal, FalseVal}); 7960 7961 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7962 {Slct.getOperand(0), TrueVal, FalseVal}); 7963 } 7964 7965 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7966 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7967 bool AllOnes) { 7968 SDValue N0 = N->getOperand(0); 7969 SDValue N1 = N->getOperand(1); 7970 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7971 return Result; 7972 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7973 return Result; 7974 return SDValue(); 7975 } 7976 7977 // Transform (add (mul x, c0), c1) -> 7978 // (add (mul (add x, c1/c0), c0), c1%c0). 7979 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7980 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7981 // to an infinite loop in DAGCombine if transformed. 7982 // Or transform (add (mul x, c0), c1) -> 7983 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7984 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7985 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7986 // lead to an infinite loop in DAGCombine if transformed. 7987 // Or transform (add (mul x, c0), c1) -> 7988 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7989 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7990 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7991 // lead to an infinite loop in DAGCombine if transformed. 7992 // Or transform (add (mul x, c0), c1) -> 7993 // (mul (add x, c1/c0), c0). 7994 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7995 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7996 const RISCVSubtarget &Subtarget) { 7997 // Skip for vector types and larger types. 7998 EVT VT = N->getValueType(0); 7999 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 8000 return SDValue(); 8001 // The first operand node must be a MUL and has no other use. 8002 SDValue N0 = N->getOperand(0); 8003 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 8004 return SDValue(); 8005 // Check if c0 and c1 match above conditions. 8006 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8007 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8008 if (!N0C || !N1C) 8009 return SDValue(); 8010 // If N0C has multiple uses it's possible one of the cases in 8011 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 8012 // in an infinite loop. 8013 if (!N0C->hasOneUse()) 8014 return SDValue(); 8015 int64_t C0 = N0C->getSExtValue(); 8016 int64_t C1 = N1C->getSExtValue(); 8017 int64_t CA, CB; 8018 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 8019 return SDValue(); 8020 // Search for proper CA (non-zero) and CB that both are simm12. 8021 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 8022 !isInt<12>(C0 * (C1 / C0))) { 8023 CA = C1 / C0; 8024 CB = C1 % C0; 8025 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 8026 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 8027 CA = C1 / C0 + 1; 8028 CB = C1 % C0 - C0; 8029 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 8030 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 8031 CA = C1 / C0 - 1; 8032 CB = C1 % C0 + C0; 8033 } else 8034 return SDValue(); 8035 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 8036 SDLoc DL(N); 8037 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 8038 DAG.getConstant(CA, DL, VT)); 8039 SDValue New1 = 8040 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 8041 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 8042 } 8043 8044 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 8045 const RISCVSubtarget &Subtarget) { 8046 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 8047 return V; 8048 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 8049 return V; 8050 if (SDValue V = combineBinOpToReduce(N, DAG)) 8051 return V; 8052 // fold (add (select lhs, rhs, cc, 0, y), x) -> 8053 // (select lhs, rhs, cc, x, (add x, y)) 8054 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8055 } 8056 8057 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 8058 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 8059 // (select lhs, rhs, cc, x, (sub x, y)) 8060 SDValue N0 = N->getOperand(0); 8061 SDValue N1 = N->getOperand(1); 8062 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 8063 } 8064 8065 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG, 8066 const RISCVSubtarget &Subtarget) { 8067 SDValue N0 = N->getOperand(0); 8068 // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero 8069 // extending X. This is safe since we only need the LSB after the shift and 8070 // shift amounts larger than 31 would produce poison. If we wait until 8071 // type legalization, we'll create RISCVISD::SRLW and we can't recover it 8072 // to use a BEXT instruction. 8073 if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() && 8074 N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) && 8075 N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) && 8076 N0.hasOneUse()) { 8077 SDLoc DL(N); 8078 SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0)); 8079 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1)); 8080 SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1); 8081 SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl, 8082 DAG.getConstant(1, DL, MVT::i64)); 8083 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And); 8084 } 8085 8086 if (SDValue V = combineBinOpToReduce(N, DAG)) 8087 return V; 8088 8089 // fold (and (select lhs, rhs, cc, -1, y), x) -> 8090 // (select lhs, rhs, cc, x, (and x, y)) 8091 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 8092 } 8093 8094 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 8095 const RISCVSubtarget &Subtarget) { 8096 if (Subtarget.hasStdExtZbp()) { 8097 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 8098 return GREV; 8099 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 8100 return GORC; 8101 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 8102 return SHFL; 8103 } 8104 8105 if (SDValue V = combineBinOpToReduce(N, DAG)) 8106 return V; 8107 // fold (or (select cond, 0, y), x) -> 8108 // (select cond, x, (or x, y)) 8109 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8110 } 8111 8112 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 8113 SDValue N0 = N->getOperand(0); 8114 SDValue N1 = N->getOperand(1); 8115 8116 // fold (xor (sllw 1, x), -1) -> (rolw ~1, x) 8117 // NOTE: Assumes ROL being legal means ROLW is legal. 8118 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8119 if (N0.getOpcode() == RISCVISD::SLLW && 8120 isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) && 8121 TLI.isOperationLegal(ISD::ROTL, MVT::i64)) { 8122 SDLoc DL(N); 8123 return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64, 8124 DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1)); 8125 } 8126 8127 if (SDValue V = combineBinOpToReduce(N, DAG)) 8128 return V; 8129 // fold (xor (select cond, 0, y), x) -> 8130 // (select cond, x, (xor x, y)) 8131 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8132 } 8133 8134 static SDValue 8135 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 8136 const RISCVSubtarget &Subtarget) { 8137 SDValue Src = N->getOperand(0); 8138 EVT VT = N->getValueType(0); 8139 8140 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 8141 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8142 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 8143 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 8144 Src.getOperand(0)); 8145 8146 // Fold (i64 (sext_inreg (abs X), i32)) -> 8147 // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits. 8148 // The (sext_inreg (neg X), i32) will be selected to negw by isel. This 8149 // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user 8150 // of the (i32 (abs X)) is a sext or setcc or something else that causes type 8151 // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have 8152 // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg 8153 // may get combined into an earlier operation so we need to use 8154 // ComputeNumSignBits. 8155 // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for 8156 // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so 8157 // we can't assume that X has 33 sign bits. We must check. 8158 if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() && 8159 Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 && 8160 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 && 8161 DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) { 8162 SDLoc DL(N); 8163 SDValue Freeze = DAG.getFreeze(Src.getOperand(0)); 8164 SDValue Neg = 8165 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze); 8166 Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg, 8167 DAG.getValueType(MVT::i32)); 8168 return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg); 8169 } 8170 8171 return SDValue(); 8172 } 8173 8174 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 8175 // vwadd(u).vv/vx or vwsub(u).vv/vx. 8176 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 8177 bool Commute = false) { 8178 assert((N->getOpcode() == RISCVISD::ADD_VL || 8179 N->getOpcode() == RISCVISD::SUB_VL) && 8180 "Unexpected opcode"); 8181 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 8182 SDValue Op0 = N->getOperand(0); 8183 SDValue Op1 = N->getOperand(1); 8184 if (Commute) 8185 std::swap(Op0, Op1); 8186 8187 MVT VT = N->getSimpleValueType(0); 8188 8189 // Determine the narrow size for a widening add/sub. 8190 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8191 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8192 VT.getVectorElementCount()); 8193 8194 SDValue Mask = N->getOperand(2); 8195 SDValue VL = N->getOperand(3); 8196 8197 SDLoc DL(N); 8198 8199 // If the RHS is a sext or zext, we can form a widening op. 8200 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 8201 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 8202 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 8203 unsigned ExtOpc = Op1.getOpcode(); 8204 Op1 = Op1.getOperand(0); 8205 // Re-introduce narrower extends if needed. 8206 if (Op1.getValueType() != NarrowVT) 8207 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8208 8209 unsigned WOpc; 8210 if (ExtOpc == RISCVISD::VSEXT_VL) 8211 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 8212 else 8213 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 8214 8215 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 8216 } 8217 8218 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 8219 // sext/zext? 8220 8221 return SDValue(); 8222 } 8223 8224 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 8225 // vwsub(u).vv/vx. 8226 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 8227 SDValue Op0 = N->getOperand(0); 8228 SDValue Op1 = N->getOperand(1); 8229 SDValue Mask = N->getOperand(2); 8230 SDValue VL = N->getOperand(3); 8231 8232 MVT VT = N->getSimpleValueType(0); 8233 MVT NarrowVT = Op1.getSimpleValueType(); 8234 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 8235 8236 unsigned VOpc; 8237 switch (N->getOpcode()) { 8238 default: llvm_unreachable("Unexpected opcode"); 8239 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 8240 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 8241 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 8242 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 8243 } 8244 8245 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 8246 N->getOpcode() == RISCVISD::VWSUB_W_VL; 8247 8248 SDLoc DL(N); 8249 8250 // If the LHS is a sext or zext, we can narrow this op to the same size as 8251 // the RHS. 8252 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 8253 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 8254 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 8255 unsigned ExtOpc = Op0.getOpcode(); 8256 Op0 = Op0.getOperand(0); 8257 // Re-introduce narrower extends if needed. 8258 if (Op0.getValueType() != NarrowVT) 8259 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8260 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 8261 } 8262 8263 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 8264 N->getOpcode() == RISCVISD::VWADDU_W_VL; 8265 8266 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 8267 // to commute and use a vwadd(u).vx instead. 8268 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 8269 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 8270 Op0 = Op0.getOperand(1); 8271 8272 // See if have enough sign bits or zero bits in the scalar to use a 8273 // widening add/sub by splatting to smaller element size. 8274 unsigned EltBits = VT.getScalarSizeInBits(); 8275 unsigned ScalarBits = Op0.getValueSizeInBits(); 8276 // Make sure we're getting all element bits from the scalar register. 8277 // FIXME: Support implicit sign extension of vmv.v.x? 8278 if (ScalarBits < EltBits) 8279 return SDValue(); 8280 8281 if (IsSigned) { 8282 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 8283 return SDValue(); 8284 } else { 8285 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8286 if (!DAG.MaskedValueIsZero(Op0, Mask)) 8287 return SDValue(); 8288 } 8289 8290 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8291 DAG.getUNDEF(NarrowVT), Op0, VL); 8292 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 8293 } 8294 8295 return SDValue(); 8296 } 8297 8298 // Try to form VWMUL, VWMULU or VWMULSU. 8299 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 8300 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 8301 bool Commute) { 8302 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 8303 SDValue Op0 = N->getOperand(0); 8304 SDValue Op1 = N->getOperand(1); 8305 if (Commute) 8306 std::swap(Op0, Op1); 8307 8308 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 8309 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 8310 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 8311 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 8312 return SDValue(); 8313 8314 SDValue Mask = N->getOperand(2); 8315 SDValue VL = N->getOperand(3); 8316 8317 // Make sure the mask and VL match. 8318 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 8319 return SDValue(); 8320 8321 MVT VT = N->getSimpleValueType(0); 8322 8323 // Determine the narrow size for a widening multiply. 8324 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8325 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8326 VT.getVectorElementCount()); 8327 8328 SDLoc DL(N); 8329 8330 // See if the other operand is the same opcode. 8331 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 8332 if (!Op1.hasOneUse()) 8333 return SDValue(); 8334 8335 // Make sure the mask and VL match. 8336 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 8337 return SDValue(); 8338 8339 Op1 = Op1.getOperand(0); 8340 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 8341 // The operand is a splat of a scalar. 8342 8343 // The pasthru must be undef for tail agnostic 8344 if (!Op1.getOperand(0).isUndef()) 8345 return SDValue(); 8346 // The VL must be the same. 8347 if (Op1.getOperand(2) != VL) 8348 return SDValue(); 8349 8350 // Get the scalar value. 8351 Op1 = Op1.getOperand(1); 8352 8353 // See if have enough sign bits or zero bits in the scalar to use a 8354 // widening multiply by splatting to smaller element size. 8355 unsigned EltBits = VT.getScalarSizeInBits(); 8356 unsigned ScalarBits = Op1.getValueSizeInBits(); 8357 // Make sure we're getting all element bits from the scalar register. 8358 // FIXME: Support implicit sign extension of vmv.v.x? 8359 if (ScalarBits < EltBits) 8360 return SDValue(); 8361 8362 // If the LHS is a sign extend, try to use vwmul. 8363 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 8364 // Can use vwmul. 8365 } else { 8366 // Otherwise try to use vwmulu or vwmulsu. 8367 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8368 if (DAG.MaskedValueIsZero(Op1, Mask)) 8369 IsVWMULSU = IsSignExt; 8370 else 8371 return SDValue(); 8372 } 8373 8374 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8375 DAG.getUNDEF(NarrowVT), Op1, VL); 8376 } else 8377 return SDValue(); 8378 8379 Op0 = Op0.getOperand(0); 8380 8381 // Re-introduce narrower extends if needed. 8382 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 8383 if (Op0.getValueType() != NarrowVT) 8384 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8385 // vwmulsu requires second operand to be zero extended. 8386 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 8387 if (Op1.getValueType() != NarrowVT) 8388 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8389 8390 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 8391 if (!IsVWMULSU) 8392 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 8393 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 8394 } 8395 8396 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 8397 switch (Op.getOpcode()) { 8398 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 8399 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 8400 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 8401 case ISD::FCEIL: return RISCVFPRndMode::RUP; 8402 case ISD::FROUND: return RISCVFPRndMode::RMM; 8403 } 8404 8405 return RISCVFPRndMode::Invalid; 8406 } 8407 8408 // Fold 8409 // (fp_to_int (froundeven X)) -> fcvt X, rne 8410 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 8411 // (fp_to_int (ffloor X)) -> fcvt X, rdn 8412 // (fp_to_int (fceil X)) -> fcvt X, rup 8413 // (fp_to_int (fround X)) -> fcvt X, rmm 8414 static SDValue performFP_TO_INTCombine(SDNode *N, 8415 TargetLowering::DAGCombinerInfo &DCI, 8416 const RISCVSubtarget &Subtarget) { 8417 SelectionDAG &DAG = DCI.DAG; 8418 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8419 MVT XLenVT = Subtarget.getXLenVT(); 8420 8421 // Only handle XLen or i32 types. Other types narrower than XLen will 8422 // eventually be legalized to XLenVT. 8423 EVT VT = N->getValueType(0); 8424 if (VT != MVT::i32 && VT != XLenVT) 8425 return SDValue(); 8426 8427 SDValue Src = N->getOperand(0); 8428 8429 // Ensure the FP type is also legal. 8430 if (!TLI.isTypeLegal(Src.getValueType())) 8431 return SDValue(); 8432 8433 // Don't do this for f16 with Zfhmin and not Zfh. 8434 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8435 return SDValue(); 8436 8437 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8438 if (FRM == RISCVFPRndMode::Invalid) 8439 return SDValue(); 8440 8441 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8442 8443 unsigned Opc; 8444 if (VT == XLenVT) 8445 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8446 else 8447 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8448 8449 SDLoc DL(N); 8450 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 8451 DAG.getTargetConstant(FRM, DL, XLenVT)); 8452 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 8453 } 8454 8455 // Fold 8456 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 8457 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 8458 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8459 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8460 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8461 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8462 TargetLowering::DAGCombinerInfo &DCI, 8463 const RISCVSubtarget &Subtarget) { 8464 SelectionDAG &DAG = DCI.DAG; 8465 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8466 MVT XLenVT = Subtarget.getXLenVT(); 8467 8468 // Only handle XLen types. Other types narrower than XLen will eventually be 8469 // legalized to XLenVT. 8470 EVT DstVT = N->getValueType(0); 8471 if (DstVT != XLenVT) 8472 return SDValue(); 8473 8474 SDValue Src = N->getOperand(0); 8475 8476 // Ensure the FP type is also legal. 8477 if (!TLI.isTypeLegal(Src.getValueType())) 8478 return SDValue(); 8479 8480 // Don't do this for f16 with Zfhmin and not Zfh. 8481 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8482 return SDValue(); 8483 8484 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8485 8486 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8487 if (FRM == RISCVFPRndMode::Invalid) 8488 return SDValue(); 8489 8490 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8491 8492 unsigned Opc; 8493 if (SatVT == DstVT) 8494 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8495 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8496 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8497 else 8498 return SDValue(); 8499 // FIXME: Support other SatVTs by clamping before or after the conversion. 8500 8501 Src = Src.getOperand(0); 8502 8503 SDLoc DL(N); 8504 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8505 DAG.getTargetConstant(FRM, DL, XLenVT)); 8506 8507 // RISCV FP-to-int conversions saturate to the destination register size, but 8508 // don't produce 0 for nan. 8509 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8510 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8511 } 8512 8513 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is 8514 // smaller than XLenVT. 8515 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG, 8516 const RISCVSubtarget &Subtarget) { 8517 assert(Subtarget.hasStdExtZbkb() && "Unexpected extension"); 8518 8519 SDValue Src = N->getOperand(0); 8520 if (Src.getOpcode() != ISD::BSWAP) 8521 return SDValue(); 8522 8523 EVT VT = N->getValueType(0); 8524 if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() || 8525 !isPowerOf2_32(VT.getSizeInBits())) 8526 return SDValue(); 8527 8528 SDLoc DL(N); 8529 return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0), 8530 DAG.getConstant(7, DL, VT)); 8531 } 8532 8533 // Convert from one FMA opcode to another based on whether we are negating the 8534 // multiply result and/or the accumulator. 8535 // NOTE: Only supports RVV operations with VL. 8536 static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc) { 8537 assert((NegMul || NegAcc) && "Not negating anything?"); 8538 8539 // Negating the multiply result changes ADD<->SUB and toggles 'N'. 8540 if (NegMul) { 8541 // clang-format off 8542 switch (Opcode) { 8543 default: llvm_unreachable("Unexpected opcode"); 8544 case RISCVISD::VFMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break; 8545 case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFMADD_VL; break; 8546 case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFMSUB_VL; break; 8547 case RISCVISD::VFMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break; 8548 } 8549 // clang-format on 8550 } 8551 8552 // Negating the accumulator changes ADD<->SUB. 8553 if (NegAcc) { 8554 // clang-format off 8555 switch (Opcode) { 8556 default: llvm_unreachable("Unexpected opcode"); 8557 case RISCVISD::VFMADD_VL: Opcode = RISCVISD::VFMSUB_VL; break; 8558 case RISCVISD::VFMSUB_VL: Opcode = RISCVISD::VFMADD_VL; break; 8559 case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break; 8560 case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break; 8561 } 8562 // clang-format on 8563 } 8564 8565 return Opcode; 8566 } 8567 8568 // Combine (sra (shl X, 32), 32 - C) -> (shl (sext_inreg X, i32), C) 8569 // FIXME: Should this be a generic combine? There's a similar combine on X86. 8570 // 8571 // Also try these folds where an add or sub is in the middle. 8572 // (sra (add (shl X, 32), C1), 32 - C) -> (shl (sext_inreg (add X, C1), C) 8573 // (sra (sub C1, (shl X, 32)), 32 - C) -> (shl (sext_inreg (sub C1, X), C) 8574 static SDValue performSRACombine(SDNode *N, SelectionDAG &DAG, 8575 const RISCVSubtarget &Subtarget) { 8576 assert(N->getOpcode() == ISD::SRA && "Unexpected opcode"); 8577 8578 if (N->getValueType(0) != MVT::i64 || !Subtarget.is64Bit()) 8579 return SDValue(); 8580 8581 auto *ShAmtC = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8582 if (!ShAmtC || ShAmtC->getZExtValue() > 32) 8583 return SDValue(); 8584 8585 SDValue N0 = N->getOperand(0); 8586 8587 SDValue Shl; 8588 ConstantSDNode *AddC = nullptr; 8589 8590 // We might have an ADD or SUB between the SRA and SHL. 8591 bool IsAdd = N0.getOpcode() == ISD::ADD; 8592 if ((IsAdd || N0.getOpcode() == ISD::SUB)) { 8593 if (!N0.hasOneUse()) 8594 return SDValue(); 8595 // Other operand needs to be a constant we can modify. 8596 AddC = dyn_cast<ConstantSDNode>(N0.getOperand(IsAdd ? 1 : 0)); 8597 if (!AddC) 8598 return SDValue(); 8599 8600 // AddC needs to have at least 32 trailing zeros. 8601 if (AddC->getAPIntValue().countTrailingZeros() < 32) 8602 return SDValue(); 8603 8604 Shl = N0.getOperand(IsAdd ? 0 : 1); 8605 } else { 8606 // Not an ADD or SUB. 8607 Shl = N0; 8608 } 8609 8610 // Look for a shift left by 32. 8611 if (Shl.getOpcode() != ISD::SHL || !Shl.hasOneUse() || 8612 !isa<ConstantSDNode>(Shl.getOperand(1)) || 8613 Shl.getConstantOperandVal(1) != 32) 8614 return SDValue(); 8615 8616 SDLoc DL(N); 8617 SDValue In = Shl.getOperand(0); 8618 8619 // If we looked through an ADD or SUB, we need to rebuild it with the shifted 8620 // constant. 8621 if (AddC) { 8622 SDValue ShiftedAddC = 8623 DAG.getConstant(AddC->getAPIntValue().lshr(32), DL, MVT::i64); 8624 if (IsAdd) 8625 In = DAG.getNode(ISD::ADD, DL, MVT::i64, In, ShiftedAddC); 8626 else 8627 In = DAG.getNode(ISD::SUB, DL, MVT::i64, ShiftedAddC, In); 8628 } 8629 8630 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, In, 8631 DAG.getValueType(MVT::i32)); 8632 if (ShAmtC->getZExtValue() == 32) 8633 return SExt; 8634 8635 return DAG.getNode( 8636 ISD::SHL, DL, MVT::i64, SExt, 8637 DAG.getConstant(32 - ShAmtC->getZExtValue(), DL, MVT::i64)); 8638 } 8639 8640 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8641 DAGCombinerInfo &DCI) const { 8642 SelectionDAG &DAG = DCI.DAG; 8643 8644 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8645 // bits are demanded. N will be added to the Worklist if it was not deleted. 8646 // Caller should return SDValue(N, 0) if this returns true. 8647 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8648 SDValue Op = N->getOperand(OpNo); 8649 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8650 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8651 return false; 8652 8653 if (N->getOpcode() != ISD::DELETED_NODE) 8654 DCI.AddToWorklist(N); 8655 return true; 8656 }; 8657 8658 switch (N->getOpcode()) { 8659 default: 8660 break; 8661 case RISCVISD::SplitF64: { 8662 SDValue Op0 = N->getOperand(0); 8663 // If the input to SplitF64 is just BuildPairF64 then the operation is 8664 // redundant. Instead, use BuildPairF64's operands directly. 8665 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8666 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8667 8668 if (Op0->isUndef()) { 8669 SDValue Lo = DAG.getUNDEF(MVT::i32); 8670 SDValue Hi = DAG.getUNDEF(MVT::i32); 8671 return DCI.CombineTo(N, Lo, Hi); 8672 } 8673 8674 SDLoc DL(N); 8675 8676 // It's cheaper to materialise two 32-bit integers than to load a double 8677 // from the constant pool and transfer it to integer registers through the 8678 // stack. 8679 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8680 APInt V = C->getValueAPF().bitcastToAPInt(); 8681 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8682 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8683 return DCI.CombineTo(N, Lo, Hi); 8684 } 8685 8686 // This is a target-specific version of a DAGCombine performed in 8687 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8688 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8689 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8690 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8691 !Op0.getNode()->hasOneUse()) 8692 break; 8693 SDValue NewSplitF64 = 8694 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8695 Op0.getOperand(0)); 8696 SDValue Lo = NewSplitF64.getValue(0); 8697 SDValue Hi = NewSplitF64.getValue(1); 8698 APInt SignBit = APInt::getSignMask(32); 8699 if (Op0.getOpcode() == ISD::FNEG) { 8700 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8701 DAG.getConstant(SignBit, DL, MVT::i32)); 8702 return DCI.CombineTo(N, Lo, NewHi); 8703 } 8704 assert(Op0.getOpcode() == ISD::FABS); 8705 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8706 DAG.getConstant(~SignBit, DL, MVT::i32)); 8707 return DCI.CombineTo(N, Lo, NewHi); 8708 } 8709 case RISCVISD::SLLW: 8710 case RISCVISD::SRAW: 8711 case RISCVISD::SRLW: { 8712 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8713 if (SimplifyDemandedLowBitsHelper(0, 32) || 8714 SimplifyDemandedLowBitsHelper(1, 5)) 8715 return SDValue(N, 0); 8716 8717 break; 8718 } 8719 case ISD::ROTR: 8720 case ISD::ROTL: 8721 case RISCVISD::RORW: 8722 case RISCVISD::ROLW: { 8723 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8724 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8725 if (SimplifyDemandedLowBitsHelper(0, 32) || 8726 SimplifyDemandedLowBitsHelper(1, 5)) 8727 return SDValue(N, 0); 8728 } 8729 8730 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8731 } 8732 case RISCVISD::CLZW: 8733 case RISCVISD::CTZW: { 8734 // Only the lower 32 bits of the first operand are read 8735 if (SimplifyDemandedLowBitsHelper(0, 32)) 8736 return SDValue(N, 0); 8737 break; 8738 } 8739 case RISCVISD::GREV: 8740 case RISCVISD::GORC: { 8741 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8742 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8743 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8744 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8745 return SDValue(N, 0); 8746 8747 return combineGREVI_GORCI(N, DAG); 8748 } 8749 case RISCVISD::GREVW: 8750 case RISCVISD::GORCW: { 8751 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8752 if (SimplifyDemandedLowBitsHelper(0, 32) || 8753 SimplifyDemandedLowBitsHelper(1, 5)) 8754 return SDValue(N, 0); 8755 8756 break; 8757 } 8758 case RISCVISD::SHFL: 8759 case RISCVISD::UNSHFL: { 8760 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8761 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8762 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8763 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8764 return SDValue(N, 0); 8765 8766 break; 8767 } 8768 case RISCVISD::SHFLW: 8769 case RISCVISD::UNSHFLW: { 8770 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8771 if (SimplifyDemandedLowBitsHelper(0, 32) || 8772 SimplifyDemandedLowBitsHelper(1, 4)) 8773 return SDValue(N, 0); 8774 8775 break; 8776 } 8777 case RISCVISD::BCOMPRESSW: 8778 case RISCVISD::BDECOMPRESSW: { 8779 // Only the lower 32 bits of LHS and RHS are read. 8780 if (SimplifyDemandedLowBitsHelper(0, 32) || 8781 SimplifyDemandedLowBitsHelper(1, 32)) 8782 return SDValue(N, 0); 8783 8784 break; 8785 } 8786 case RISCVISD::FSR: 8787 case RISCVISD::FSL: 8788 case RISCVISD::FSRW: 8789 case RISCVISD::FSLW: { 8790 bool IsWInstruction = 8791 N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW; 8792 unsigned BitWidth = 8793 IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits(); 8794 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8795 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 8796 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1)) 8797 return SDValue(N, 0); 8798 8799 break; 8800 } 8801 case RISCVISD::FMV_X_ANYEXTH: 8802 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8803 SDLoc DL(N); 8804 SDValue Op0 = N->getOperand(0); 8805 MVT VT = N->getSimpleValueType(0); 8806 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8807 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8808 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8809 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8810 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8811 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8812 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8813 assert(Op0.getOperand(0).getValueType() == VT && 8814 "Unexpected value type!"); 8815 return Op0.getOperand(0); 8816 } 8817 8818 // This is a target-specific version of a DAGCombine performed in 8819 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8820 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8821 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8822 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8823 !Op0.getNode()->hasOneUse()) 8824 break; 8825 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8826 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8827 APInt SignBit = APInt::getSignMask(FPBits).sext(VT.getSizeInBits()); 8828 if (Op0.getOpcode() == ISD::FNEG) 8829 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8830 DAG.getConstant(SignBit, DL, VT)); 8831 8832 assert(Op0.getOpcode() == ISD::FABS); 8833 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8834 DAG.getConstant(~SignBit, DL, VT)); 8835 } 8836 case ISD::ADD: 8837 return performADDCombine(N, DAG, Subtarget); 8838 case ISD::SUB: 8839 return performSUBCombine(N, DAG); 8840 case ISD::AND: 8841 return performANDCombine(N, DAG, Subtarget); 8842 case ISD::OR: 8843 return performORCombine(N, DAG, Subtarget); 8844 case ISD::XOR: 8845 return performXORCombine(N, DAG); 8846 case ISD::FADD: 8847 case ISD::UMAX: 8848 case ISD::UMIN: 8849 case ISD::SMAX: 8850 case ISD::SMIN: 8851 case ISD::FMAXNUM: 8852 case ISD::FMINNUM: 8853 return combineBinOpToReduce(N, DAG); 8854 case ISD::SIGN_EXTEND_INREG: 8855 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 8856 case ISD::ZERO_EXTEND: 8857 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8858 // type legalization. This is safe because fp_to_uint produces poison if 8859 // it overflows. 8860 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8861 SDValue Src = N->getOperand(0); 8862 if (Src.getOpcode() == ISD::FP_TO_UINT && 8863 isTypeLegal(Src.getOperand(0).getValueType())) 8864 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8865 Src.getOperand(0)); 8866 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8867 isTypeLegal(Src.getOperand(1).getValueType())) { 8868 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8869 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8870 Src.getOperand(0), Src.getOperand(1)); 8871 DCI.CombineTo(N, Res); 8872 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8873 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8874 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8875 } 8876 } 8877 return SDValue(); 8878 case RISCVISD::SELECT_CC: { 8879 // Transform 8880 SDValue LHS = N->getOperand(0); 8881 SDValue RHS = N->getOperand(1); 8882 SDValue TrueV = N->getOperand(3); 8883 SDValue FalseV = N->getOperand(4); 8884 8885 // If the True and False values are the same, we don't need a select_cc. 8886 if (TrueV == FalseV) 8887 return TrueV; 8888 8889 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8890 if (!ISD::isIntEqualitySetCC(CCVal)) 8891 break; 8892 8893 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8894 // (select_cc X, Y, lt, trueV, falseV) 8895 // Sometimes the setcc is introduced after select_cc has been formed. 8896 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8897 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8898 // If we're looking for eq 0 instead of ne 0, we need to invert the 8899 // condition. 8900 bool Invert = CCVal == ISD::SETEQ; 8901 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8902 if (Invert) 8903 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8904 8905 SDLoc DL(N); 8906 RHS = LHS.getOperand(1); 8907 LHS = LHS.getOperand(0); 8908 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8909 8910 SDValue TargetCC = DAG.getCondCode(CCVal); 8911 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8912 {LHS, RHS, TargetCC, TrueV, FalseV}); 8913 } 8914 8915 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8916 // (select_cc X, Y, eq/ne, trueV, falseV) 8917 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8918 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8919 {LHS.getOperand(0), LHS.getOperand(1), 8920 N->getOperand(2), TrueV, FalseV}); 8921 // (select_cc X, 1, setne, trueV, falseV) -> 8922 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8923 // This can occur when legalizing some floating point comparisons. 8924 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8925 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8926 SDLoc DL(N); 8927 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8928 SDValue TargetCC = DAG.getCondCode(CCVal); 8929 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8930 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8931 {LHS, RHS, TargetCC, TrueV, FalseV}); 8932 } 8933 8934 break; 8935 } 8936 case RISCVISD::BR_CC: { 8937 SDValue LHS = N->getOperand(1); 8938 SDValue RHS = N->getOperand(2); 8939 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8940 if (!ISD::isIntEqualitySetCC(CCVal)) 8941 break; 8942 8943 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8944 // (br_cc X, Y, lt, dest) 8945 // Sometimes the setcc is introduced after br_cc has been formed. 8946 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8947 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8948 // If we're looking for eq 0 instead of ne 0, we need to invert the 8949 // condition. 8950 bool Invert = CCVal == ISD::SETEQ; 8951 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8952 if (Invert) 8953 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8954 8955 SDLoc DL(N); 8956 RHS = LHS.getOperand(1); 8957 LHS = LHS.getOperand(0); 8958 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8959 8960 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8961 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8962 N->getOperand(4)); 8963 } 8964 8965 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8966 // (br_cc X, Y, eq/ne, trueV, falseV) 8967 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8968 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8969 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8970 N->getOperand(3), N->getOperand(4)); 8971 8972 // (br_cc X, 1, setne, br_cc) -> 8973 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8974 // This can occur when legalizing some floating point comparisons. 8975 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8976 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8977 SDLoc DL(N); 8978 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8979 SDValue TargetCC = DAG.getCondCode(CCVal); 8980 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8981 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8982 N->getOperand(0), LHS, RHS, TargetCC, 8983 N->getOperand(4)); 8984 } 8985 break; 8986 } 8987 case ISD::BITREVERSE: 8988 return performBITREVERSECombine(N, DAG, Subtarget); 8989 case ISD::FP_TO_SINT: 8990 case ISD::FP_TO_UINT: 8991 return performFP_TO_INTCombine(N, DCI, Subtarget); 8992 case ISD::FP_TO_SINT_SAT: 8993 case ISD::FP_TO_UINT_SAT: 8994 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8995 case ISD::FCOPYSIGN: { 8996 EVT VT = N->getValueType(0); 8997 if (!VT.isVector()) 8998 break; 8999 // There is a form of VFSGNJ which injects the negated sign of its second 9000 // operand. Try and bubble any FNEG up after the extend/round to produce 9001 // this optimized pattern. Avoid modifying cases where FP_ROUND and 9002 // TRUNC=1. 9003 SDValue In2 = N->getOperand(1); 9004 // Avoid cases where the extend/round has multiple uses, as duplicating 9005 // those is typically more expensive than removing a fneg. 9006 if (!In2.hasOneUse()) 9007 break; 9008 if (In2.getOpcode() != ISD::FP_EXTEND && 9009 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 9010 break; 9011 In2 = In2.getOperand(0); 9012 if (In2.getOpcode() != ISD::FNEG) 9013 break; 9014 SDLoc DL(N); 9015 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 9016 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 9017 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 9018 } 9019 case ISD::MGATHER: 9020 case ISD::MSCATTER: 9021 case ISD::VP_GATHER: 9022 case ISD::VP_SCATTER: { 9023 if (!DCI.isBeforeLegalize()) 9024 break; 9025 SDValue Index, ScaleOp; 9026 bool IsIndexScaled = false; 9027 bool IsIndexSigned = false; 9028 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 9029 Index = VPGSN->getIndex(); 9030 ScaleOp = VPGSN->getScale(); 9031 IsIndexScaled = VPGSN->isIndexScaled(); 9032 IsIndexSigned = VPGSN->isIndexSigned(); 9033 } else { 9034 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 9035 Index = MGSN->getIndex(); 9036 ScaleOp = MGSN->getScale(); 9037 IsIndexScaled = MGSN->isIndexScaled(); 9038 IsIndexSigned = MGSN->isIndexSigned(); 9039 } 9040 EVT IndexVT = Index.getValueType(); 9041 MVT XLenVT = Subtarget.getXLenVT(); 9042 // RISCV indexed loads only support the "unsigned unscaled" addressing 9043 // mode, so anything else must be manually legalized. 9044 bool NeedsIdxLegalization = 9045 IsIndexScaled || 9046 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 9047 if (!NeedsIdxLegalization) 9048 break; 9049 9050 SDLoc DL(N); 9051 9052 // Any index legalization should first promote to XLenVT, so we don't lose 9053 // bits when scaling. This may create an illegal index type so we let 9054 // LLVM's legalization take care of the splitting. 9055 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 9056 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 9057 IndexVT = IndexVT.changeVectorElementType(XLenVT); 9058 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 9059 DL, IndexVT, Index); 9060 } 9061 9062 if (IsIndexScaled) { 9063 // Manually scale the indices. 9064 // TODO: Sanitize the scale operand here? 9065 // TODO: For VP nodes, should we use VP_SHL here? 9066 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 9067 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 9068 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 9069 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 9070 ScaleOp = DAG.getTargetConstant(1, DL, ScaleOp.getValueType()); 9071 } 9072 9073 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_SCALED; 9074 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 9075 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 9076 {VPGN->getChain(), VPGN->getBasePtr(), Index, 9077 ScaleOp, VPGN->getMask(), 9078 VPGN->getVectorLength()}, 9079 VPGN->getMemOperand(), NewIndexTy); 9080 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 9081 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 9082 {VPSN->getChain(), VPSN->getValue(), 9083 VPSN->getBasePtr(), Index, ScaleOp, 9084 VPSN->getMask(), VPSN->getVectorLength()}, 9085 VPSN->getMemOperand(), NewIndexTy); 9086 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 9087 return DAG.getMaskedGather( 9088 N->getVTList(), MGN->getMemoryVT(), DL, 9089 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 9090 MGN->getBasePtr(), Index, ScaleOp}, 9091 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 9092 const auto *MSN = cast<MaskedScatterSDNode>(N); 9093 return DAG.getMaskedScatter( 9094 N->getVTList(), MSN->getMemoryVT(), DL, 9095 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 9096 Index, ScaleOp}, 9097 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 9098 } 9099 case RISCVISD::SRA_VL: 9100 case RISCVISD::SRL_VL: 9101 case RISCVISD::SHL_VL: { 9102 SDValue ShAmt = N->getOperand(1); 9103 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 9104 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 9105 SDLoc DL(N); 9106 SDValue VL = N->getOperand(3); 9107 EVT VT = N->getValueType(0); 9108 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 9109 ShAmt.getOperand(1), VL); 9110 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 9111 N->getOperand(2), N->getOperand(3)); 9112 } 9113 break; 9114 } 9115 case ISD::SRA: 9116 if (SDValue V = performSRACombine(N, DAG, Subtarget)) 9117 return V; 9118 LLVM_FALLTHROUGH; 9119 case ISD::SRL: 9120 case ISD::SHL: { 9121 SDValue ShAmt = N->getOperand(1); 9122 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 9123 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 9124 SDLoc DL(N); 9125 EVT VT = N->getValueType(0); 9126 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 9127 ShAmt.getOperand(1), 9128 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 9129 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 9130 } 9131 break; 9132 } 9133 case RISCVISD::ADD_VL: 9134 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 9135 return V; 9136 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 9137 case RISCVISD::SUB_VL: 9138 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 9139 case RISCVISD::VWADD_W_VL: 9140 case RISCVISD::VWADDU_W_VL: 9141 case RISCVISD::VWSUB_W_VL: 9142 case RISCVISD::VWSUBU_W_VL: 9143 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 9144 case RISCVISD::MUL_VL: 9145 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 9146 return V; 9147 // Mul is commutative. 9148 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 9149 case RISCVISD::VFMADD_VL: 9150 case RISCVISD::VFNMADD_VL: 9151 case RISCVISD::VFMSUB_VL: 9152 case RISCVISD::VFNMSUB_VL: { 9153 // Fold FNEG_VL into FMA opcodes. 9154 SDValue A = N->getOperand(0); 9155 SDValue B = N->getOperand(1); 9156 SDValue C = N->getOperand(2); 9157 SDValue Mask = N->getOperand(3); 9158 SDValue VL = N->getOperand(4); 9159 9160 auto invertIfNegative = [&Mask, &VL](SDValue &V) { 9161 if (V.getOpcode() == RISCVISD::FNEG_VL && V.getOperand(1) == Mask && 9162 V.getOperand(2) == VL) { 9163 // Return the negated input. 9164 V = V.getOperand(0); 9165 return true; 9166 } 9167 9168 return false; 9169 }; 9170 9171 bool NegA = invertIfNegative(A); 9172 bool NegB = invertIfNegative(B); 9173 bool NegC = invertIfNegative(C); 9174 9175 // If no operands are negated, we're done. 9176 if (!NegA && !NegB && !NegC) 9177 return SDValue(); 9178 9179 unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC); 9180 return DAG.getNode(NewOpcode, SDLoc(N), N->getValueType(0), A, B, C, Mask, 9181 VL); 9182 } 9183 case ISD::STORE: { 9184 auto *Store = cast<StoreSDNode>(N); 9185 SDValue Val = Store->getValue(); 9186 // Combine store of vmv.x.s to vse with VL of 1. 9187 // FIXME: Support FP. 9188 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 9189 SDValue Src = Val.getOperand(0); 9190 MVT VecVT = Src.getSimpleValueType(); 9191 EVT MemVT = Store->getMemoryVT(); 9192 // The memory VT and the element type must match. 9193 if (MemVT == VecVT.getVectorElementType()) { 9194 SDLoc DL(N); 9195 MVT MaskVT = getMaskTypeFor(VecVT); 9196 return DAG.getStoreVP( 9197 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 9198 DAG.getConstant(1, DL, MaskVT), 9199 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 9200 Store->getMemOperand(), Store->getAddressingMode(), 9201 Store->isTruncatingStore(), /*IsCompress*/ false); 9202 } 9203 } 9204 9205 break; 9206 } 9207 case ISD::SPLAT_VECTOR: { 9208 EVT VT = N->getValueType(0); 9209 // Only perform this combine on legal MVT types. 9210 if (!isTypeLegal(VT)) 9211 break; 9212 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 9213 DAG, Subtarget)) 9214 return Gather; 9215 break; 9216 } 9217 case RISCVISD::VMV_V_X_VL: { 9218 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 9219 // scalar input. 9220 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 9221 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 9222 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 9223 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 9224 return SDValue(N, 0); 9225 9226 break; 9227 } 9228 case ISD::INTRINSIC_WO_CHAIN: { 9229 unsigned IntNo = N->getConstantOperandVal(0); 9230 switch (IntNo) { 9231 // By default we do not combine any intrinsic. 9232 default: 9233 return SDValue(); 9234 case Intrinsic::riscv_vcpop: 9235 case Intrinsic::riscv_vcpop_mask: 9236 case Intrinsic::riscv_vfirst: 9237 case Intrinsic::riscv_vfirst_mask: { 9238 SDValue VL = N->getOperand(2); 9239 if (IntNo == Intrinsic::riscv_vcpop_mask || 9240 IntNo == Intrinsic::riscv_vfirst_mask) 9241 VL = N->getOperand(3); 9242 if (!isNullConstant(VL)) 9243 return SDValue(); 9244 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 9245 SDLoc DL(N); 9246 EVT VT = N->getValueType(0); 9247 if (IntNo == Intrinsic::riscv_vfirst || 9248 IntNo == Intrinsic::riscv_vfirst_mask) 9249 return DAG.getConstant(-1, DL, VT); 9250 return DAG.getConstant(0, DL, VT); 9251 } 9252 } 9253 } 9254 case ISD::BITCAST: { 9255 assert(Subtarget.useRVVForFixedLengthVectors()); 9256 SDValue N0 = N->getOperand(0); 9257 EVT VT = N->getValueType(0); 9258 EVT SrcVT = N0.getValueType(); 9259 // If this is a bitcast between a MVT::v4i1/v2i1/v1i1 and an illegal integer 9260 // type, widen both sides to avoid a trip through memory. 9261 if ((SrcVT == MVT::v1i1 || SrcVT == MVT::v2i1 || SrcVT == MVT::v4i1) && 9262 VT.isScalarInteger()) { 9263 unsigned NumConcats = 8 / SrcVT.getVectorNumElements(); 9264 SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT)); 9265 Ops[0] = N0; 9266 SDLoc DL(N); 9267 N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i1, Ops); 9268 N0 = DAG.getBitcast(MVT::i8, N0); 9269 return DAG.getNode(ISD::TRUNCATE, DL, VT, N0); 9270 } 9271 9272 return SDValue(); 9273 } 9274 } 9275 9276 return SDValue(); 9277 } 9278 9279 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 9280 const SDNode *N, CombineLevel Level) const { 9281 // The following folds are only desirable if `(OP _, c1 << c2)` can be 9282 // materialised in fewer instructions than `(OP _, c1)`: 9283 // 9284 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 9285 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 9286 SDValue N0 = N->getOperand(0); 9287 EVT Ty = N0.getValueType(); 9288 if (Ty.isScalarInteger() && 9289 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 9290 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 9291 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9292 if (C1 && C2) { 9293 const APInt &C1Int = C1->getAPIntValue(); 9294 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 9295 9296 // We can materialise `c1 << c2` into an add immediate, so it's "free", 9297 // and the combine should happen, to potentially allow further combines 9298 // later. 9299 if (ShiftedC1Int.getMinSignedBits() <= 64 && 9300 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 9301 return true; 9302 9303 // We can materialise `c1` in an add immediate, so it's "free", and the 9304 // combine should be prevented. 9305 if (C1Int.getMinSignedBits() <= 64 && 9306 isLegalAddImmediate(C1Int.getSExtValue())) 9307 return false; 9308 9309 // Neither constant will fit into an immediate, so find materialisation 9310 // costs. 9311 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 9312 Subtarget.getFeatureBits(), 9313 /*CompressionCost*/true); 9314 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 9315 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 9316 /*CompressionCost*/true); 9317 9318 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 9319 // combine should be prevented. 9320 if (C1Cost < ShiftedC1Cost) 9321 return false; 9322 } 9323 } 9324 return true; 9325 } 9326 9327 bool RISCVTargetLowering::targetShrinkDemandedConstant( 9328 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 9329 TargetLoweringOpt &TLO) const { 9330 // Delay this optimization as late as possible. 9331 if (!TLO.LegalOps) 9332 return false; 9333 9334 EVT VT = Op.getValueType(); 9335 if (VT.isVector()) 9336 return false; 9337 9338 // Only handle AND for now. 9339 if (Op.getOpcode() != ISD::AND) 9340 return false; 9341 9342 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 9343 if (!C) 9344 return false; 9345 9346 const APInt &Mask = C->getAPIntValue(); 9347 9348 // Clear all non-demanded bits initially. 9349 APInt ShrunkMask = Mask & DemandedBits; 9350 9351 // Try to make a smaller immediate by setting undemanded bits. 9352 9353 APInt ExpandedMask = Mask | ~DemandedBits; 9354 9355 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 9356 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 9357 }; 9358 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 9359 if (NewMask == Mask) 9360 return true; 9361 SDLoc DL(Op); 9362 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 9363 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 9364 return TLO.CombineTo(Op, NewOp); 9365 }; 9366 9367 // If the shrunk mask fits in sign extended 12 bits, let the target 9368 // independent code apply it. 9369 if (ShrunkMask.isSignedIntN(12)) 9370 return false; 9371 9372 // Preserve (and X, 0xffff) when zext.h is supported. 9373 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 9374 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 9375 if (IsLegalMask(NewMask)) 9376 return UseMask(NewMask); 9377 } 9378 9379 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 9380 if (VT == MVT::i64) { 9381 APInt NewMask = APInt(64, 0xffffffff); 9382 if (IsLegalMask(NewMask)) 9383 return UseMask(NewMask); 9384 } 9385 9386 // For the remaining optimizations, we need to be able to make a negative 9387 // number through a combination of mask and undemanded bits. 9388 if (!ExpandedMask.isNegative()) 9389 return false; 9390 9391 // What is the fewest number of bits we need to represent the negative number. 9392 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 9393 9394 // Try to make a 12 bit negative immediate. If that fails try to make a 32 9395 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 9396 APInt NewMask = ShrunkMask; 9397 if (MinSignedBits <= 12) 9398 NewMask.setBitsFrom(11); 9399 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 9400 NewMask.setBitsFrom(31); 9401 else 9402 return false; 9403 9404 // Check that our new mask is a subset of the demanded mask. 9405 assert(IsLegalMask(NewMask)); 9406 return UseMask(NewMask); 9407 } 9408 9409 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) { 9410 static const uint64_t GREVMasks[] = { 9411 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 9412 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 9413 9414 for (unsigned Stage = 0; Stage != 6; ++Stage) { 9415 unsigned Shift = 1 << Stage; 9416 if (ShAmt & Shift) { 9417 uint64_t Mask = GREVMasks[Stage]; 9418 uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask); 9419 if (IsGORC) 9420 Res |= x; 9421 x = Res; 9422 } 9423 } 9424 9425 return x; 9426 } 9427 9428 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 9429 KnownBits &Known, 9430 const APInt &DemandedElts, 9431 const SelectionDAG &DAG, 9432 unsigned Depth) const { 9433 unsigned BitWidth = Known.getBitWidth(); 9434 unsigned Opc = Op.getOpcode(); 9435 assert((Opc >= ISD::BUILTIN_OP_END || 9436 Opc == ISD::INTRINSIC_WO_CHAIN || 9437 Opc == ISD::INTRINSIC_W_CHAIN || 9438 Opc == ISD::INTRINSIC_VOID) && 9439 "Should use MaskedValueIsZero if you don't know whether Op" 9440 " is a target node!"); 9441 9442 Known.resetAll(); 9443 switch (Opc) { 9444 default: break; 9445 case RISCVISD::SELECT_CC: { 9446 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 9447 // If we don't know any bits, early out. 9448 if (Known.isUnknown()) 9449 break; 9450 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 9451 9452 // Only known if known in both the LHS and RHS. 9453 Known = KnownBits::commonBits(Known, Known2); 9454 break; 9455 } 9456 case RISCVISD::REMUW: { 9457 KnownBits Known2; 9458 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9459 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9460 // We only care about the lower 32 bits. 9461 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 9462 // Restore the original width by sign extending. 9463 Known = Known.sext(BitWidth); 9464 break; 9465 } 9466 case RISCVISD::DIVUW: { 9467 KnownBits Known2; 9468 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9469 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9470 // We only care about the lower 32 bits. 9471 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 9472 // Restore the original width by sign extending. 9473 Known = Known.sext(BitWidth); 9474 break; 9475 } 9476 case RISCVISD::CTZW: { 9477 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9478 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 9479 unsigned LowBits = Log2_32(PossibleTZ) + 1; 9480 Known.Zero.setBitsFrom(LowBits); 9481 break; 9482 } 9483 case RISCVISD::CLZW: { 9484 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9485 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 9486 unsigned LowBits = Log2_32(PossibleLZ) + 1; 9487 Known.Zero.setBitsFrom(LowBits); 9488 break; 9489 } 9490 case RISCVISD::GREV: 9491 case RISCVISD::GORC: { 9492 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 9493 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9494 unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1); 9495 bool IsGORC = Op.getOpcode() == RISCVISD::GORC; 9496 // To compute zeros, we need to invert the value and invert it back after. 9497 Known.Zero = 9498 ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC); 9499 Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC); 9500 } 9501 break; 9502 } 9503 case RISCVISD::READ_VLENB: { 9504 // We can use the minimum and maximum VLEN values to bound VLENB. We 9505 // know VLEN must be a power of two. 9506 const unsigned MinVLenB = Subtarget.getRealMinVLen() / 8; 9507 const unsigned MaxVLenB = Subtarget.getRealMaxVLen() / 8; 9508 assert(MinVLenB > 0 && "READ_VLENB without vector extension enabled?"); 9509 Known.Zero.setLowBits(Log2_32(MinVLenB)); 9510 Known.Zero.setBitsFrom(Log2_32(MaxVLenB)+1); 9511 if (MaxVLenB == MinVLenB) 9512 Known.One.setBit(Log2_32(MinVLenB)); 9513 break; 9514 } 9515 case ISD::INTRINSIC_W_CHAIN: 9516 case ISD::INTRINSIC_WO_CHAIN: { 9517 unsigned IntNo = 9518 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 9519 switch (IntNo) { 9520 default: 9521 // We can't do anything for most intrinsics. 9522 break; 9523 case Intrinsic::riscv_vsetvli: 9524 case Intrinsic::riscv_vsetvlimax: 9525 case Intrinsic::riscv_vsetvli_opt: 9526 case Intrinsic::riscv_vsetvlimax_opt: 9527 // Assume that VL output is positive and would fit in an int32_t. 9528 // TODO: VLEN might be capped at 16 bits in a future V spec update. 9529 if (BitWidth >= 32) 9530 Known.Zero.setBitsFrom(31); 9531 break; 9532 } 9533 break; 9534 } 9535 } 9536 } 9537 9538 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 9539 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 9540 unsigned Depth) const { 9541 switch (Op.getOpcode()) { 9542 default: 9543 break; 9544 case RISCVISD::SELECT_CC: { 9545 unsigned Tmp = 9546 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 9547 if (Tmp == 1) return 1; // Early out. 9548 unsigned Tmp2 = 9549 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 9550 return std::min(Tmp, Tmp2); 9551 } 9552 case RISCVISD::SLLW: 9553 case RISCVISD::SRAW: 9554 case RISCVISD::SRLW: 9555 case RISCVISD::DIVW: 9556 case RISCVISD::DIVUW: 9557 case RISCVISD::REMUW: 9558 case RISCVISD::ROLW: 9559 case RISCVISD::RORW: 9560 case RISCVISD::GREVW: 9561 case RISCVISD::GORCW: 9562 case RISCVISD::FSLW: 9563 case RISCVISD::FSRW: 9564 case RISCVISD::SHFLW: 9565 case RISCVISD::UNSHFLW: 9566 case RISCVISD::BCOMPRESSW: 9567 case RISCVISD::BDECOMPRESSW: 9568 case RISCVISD::BFPW: 9569 case RISCVISD::FCVT_W_RV64: 9570 case RISCVISD::FCVT_WU_RV64: 9571 case RISCVISD::STRICT_FCVT_W_RV64: 9572 case RISCVISD::STRICT_FCVT_WU_RV64: 9573 // TODO: As the result is sign-extended, this is conservatively correct. A 9574 // more precise answer could be calculated for SRAW depending on known 9575 // bits in the shift amount. 9576 return 33; 9577 case RISCVISD::SHFL: 9578 case RISCVISD::UNSHFL: { 9579 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 9580 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 9581 // will stay within the upper 32 bits. If there were more than 32 sign bits 9582 // before there will be at least 33 sign bits after. 9583 if (Op.getValueType() == MVT::i64 && 9584 isa<ConstantSDNode>(Op.getOperand(1)) && 9585 (Op.getConstantOperandVal(1) & 0x10) == 0) { 9586 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 9587 if (Tmp > 32) 9588 return 33; 9589 } 9590 break; 9591 } 9592 case RISCVISD::VMV_X_S: { 9593 // The number of sign bits of the scalar result is computed by obtaining the 9594 // element type of the input vector operand, subtracting its width from the 9595 // XLEN, and then adding one (sign bit within the element type). If the 9596 // element type is wider than XLen, the least-significant XLEN bits are 9597 // taken. 9598 unsigned XLen = Subtarget.getXLen(); 9599 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 9600 if (EltBits <= XLen) 9601 return XLen - EltBits + 1; 9602 break; 9603 } 9604 } 9605 9606 return 1; 9607 } 9608 9609 const Constant * 9610 RISCVTargetLowering::getTargetConstantFromLoad(LoadSDNode *Ld) const { 9611 assert(Ld && "Unexpected null LoadSDNode"); 9612 if (!ISD::isNormalLoad(Ld)) 9613 return nullptr; 9614 9615 SDValue Ptr = Ld->getBasePtr(); 9616 9617 // Only constant pools with no offset are supported. 9618 auto GetSupportedConstantPool = [](SDValue Ptr) -> ConstantPoolSDNode * { 9619 auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr); 9620 if (!CNode || CNode->isMachineConstantPoolEntry() || 9621 CNode->getOffset() != 0) 9622 return nullptr; 9623 9624 return CNode; 9625 }; 9626 9627 // Simple case, LLA. 9628 if (Ptr.getOpcode() == RISCVISD::LLA) { 9629 auto *CNode = GetSupportedConstantPool(Ptr); 9630 if (!CNode || CNode->getTargetFlags() != 0) 9631 return nullptr; 9632 9633 return CNode->getConstVal(); 9634 } 9635 9636 // Look for a HI and ADD_LO pair. 9637 if (Ptr.getOpcode() != RISCVISD::ADD_LO || 9638 Ptr.getOperand(0).getOpcode() != RISCVISD::HI) 9639 return nullptr; 9640 9641 auto *CNodeLo = GetSupportedConstantPool(Ptr.getOperand(1)); 9642 auto *CNodeHi = GetSupportedConstantPool(Ptr.getOperand(0).getOperand(0)); 9643 9644 if (!CNodeLo || CNodeLo->getTargetFlags() != RISCVII::MO_LO || 9645 !CNodeHi || CNodeHi->getTargetFlags() != RISCVII::MO_HI) 9646 return nullptr; 9647 9648 if (CNodeLo->getConstVal() != CNodeHi->getConstVal()) 9649 return nullptr; 9650 9651 return CNodeLo->getConstVal(); 9652 } 9653 9654 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 9655 MachineBasicBlock *BB) { 9656 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 9657 9658 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 9659 // Should the count have wrapped while it was being read, we need to try 9660 // again. 9661 // ... 9662 // read: 9663 // rdcycleh x3 # load high word of cycle 9664 // rdcycle x2 # load low word of cycle 9665 // rdcycleh x4 # load high word of cycle 9666 // bne x3, x4, read # check if high word reads match, otherwise try again 9667 // ... 9668 9669 MachineFunction &MF = *BB->getParent(); 9670 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9671 MachineFunction::iterator It = ++BB->getIterator(); 9672 9673 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9674 MF.insert(It, LoopMBB); 9675 9676 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9677 MF.insert(It, DoneMBB); 9678 9679 // Transfer the remainder of BB and its successor edges to DoneMBB. 9680 DoneMBB->splice(DoneMBB->begin(), BB, 9681 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9682 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 9683 9684 BB->addSuccessor(LoopMBB); 9685 9686 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9687 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9688 Register LoReg = MI.getOperand(0).getReg(); 9689 Register HiReg = MI.getOperand(1).getReg(); 9690 DebugLoc DL = MI.getDebugLoc(); 9691 9692 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 9693 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 9694 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9695 .addReg(RISCV::X0); 9696 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 9697 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 9698 .addReg(RISCV::X0); 9699 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 9700 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9701 .addReg(RISCV::X0); 9702 9703 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 9704 .addReg(HiReg) 9705 .addReg(ReadAgainReg) 9706 .addMBB(LoopMBB); 9707 9708 LoopMBB->addSuccessor(LoopMBB); 9709 LoopMBB->addSuccessor(DoneMBB); 9710 9711 MI.eraseFromParent(); 9712 9713 return DoneMBB; 9714 } 9715 9716 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9717 MachineBasicBlock *BB) { 9718 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9719 9720 MachineFunction &MF = *BB->getParent(); 9721 DebugLoc DL = MI.getDebugLoc(); 9722 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9723 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9724 Register LoReg = MI.getOperand(0).getReg(); 9725 Register HiReg = MI.getOperand(1).getReg(); 9726 Register SrcReg = MI.getOperand(2).getReg(); 9727 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9728 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9729 9730 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9731 RI); 9732 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9733 MachineMemOperand *MMOLo = 9734 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9735 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9736 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9737 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9738 .addFrameIndex(FI) 9739 .addImm(0) 9740 .addMemOperand(MMOLo); 9741 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9742 .addFrameIndex(FI) 9743 .addImm(4) 9744 .addMemOperand(MMOHi); 9745 MI.eraseFromParent(); // The pseudo instruction is gone now. 9746 return BB; 9747 } 9748 9749 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9750 MachineBasicBlock *BB) { 9751 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9752 "Unexpected instruction"); 9753 9754 MachineFunction &MF = *BB->getParent(); 9755 DebugLoc DL = MI.getDebugLoc(); 9756 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9757 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9758 Register DstReg = MI.getOperand(0).getReg(); 9759 Register LoReg = MI.getOperand(1).getReg(); 9760 Register HiReg = MI.getOperand(2).getReg(); 9761 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9762 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9763 9764 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9765 MachineMemOperand *MMOLo = 9766 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9767 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9768 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9769 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9770 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9771 .addFrameIndex(FI) 9772 .addImm(0) 9773 .addMemOperand(MMOLo); 9774 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9775 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9776 .addFrameIndex(FI) 9777 .addImm(4) 9778 .addMemOperand(MMOHi); 9779 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9780 MI.eraseFromParent(); // The pseudo instruction is gone now. 9781 return BB; 9782 } 9783 9784 static bool isSelectPseudo(MachineInstr &MI) { 9785 switch (MI.getOpcode()) { 9786 default: 9787 return false; 9788 case RISCV::Select_GPR_Using_CC_GPR: 9789 case RISCV::Select_FPR16_Using_CC_GPR: 9790 case RISCV::Select_FPR32_Using_CC_GPR: 9791 case RISCV::Select_FPR64_Using_CC_GPR: 9792 return true; 9793 } 9794 } 9795 9796 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9797 unsigned RelOpcode, unsigned EqOpcode, 9798 const RISCVSubtarget &Subtarget) { 9799 DebugLoc DL = MI.getDebugLoc(); 9800 Register DstReg = MI.getOperand(0).getReg(); 9801 Register Src1Reg = MI.getOperand(1).getReg(); 9802 Register Src2Reg = MI.getOperand(2).getReg(); 9803 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9804 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9805 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9806 9807 // Save the current FFLAGS. 9808 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9809 9810 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9811 .addReg(Src1Reg) 9812 .addReg(Src2Reg); 9813 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9814 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9815 9816 // Restore the FFLAGS. 9817 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9818 .addReg(SavedFFlags, RegState::Kill); 9819 9820 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9821 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9822 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9823 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9824 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9825 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9826 9827 // Erase the pseudoinstruction. 9828 MI.eraseFromParent(); 9829 return BB; 9830 } 9831 9832 static MachineBasicBlock * 9833 EmitLoweredCascadedSelect(MachineInstr &First, MachineInstr &Second, 9834 MachineBasicBlock *ThisMBB, 9835 const RISCVSubtarget &Subtarget) { 9836 // Select_FPRX_ (rs1, rs2, imm, rs4, (Select_FPRX_ rs1, rs2, imm, rs4, rs5) 9837 // Without this, custom-inserter would have generated: 9838 // 9839 // A 9840 // | \ 9841 // | B 9842 // | / 9843 // C 9844 // | \ 9845 // | D 9846 // | / 9847 // E 9848 // 9849 // A: X = ...; Y = ... 9850 // B: empty 9851 // C: Z = PHI [X, A], [Y, B] 9852 // D: empty 9853 // E: PHI [X, C], [Z, D] 9854 // 9855 // If we lower both Select_FPRX_ in a single step, we can instead generate: 9856 // 9857 // A 9858 // | \ 9859 // | C 9860 // | /| 9861 // |/ | 9862 // | | 9863 // | D 9864 // | / 9865 // E 9866 // 9867 // A: X = ...; Y = ... 9868 // D: empty 9869 // E: PHI [X, A], [X, C], [Y, D] 9870 9871 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9872 const DebugLoc &DL = First.getDebugLoc(); 9873 const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock(); 9874 MachineFunction *F = ThisMBB->getParent(); 9875 MachineBasicBlock *FirstMBB = F->CreateMachineBasicBlock(LLVM_BB); 9876 MachineBasicBlock *SecondMBB = F->CreateMachineBasicBlock(LLVM_BB); 9877 MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9878 MachineFunction::iterator It = ++ThisMBB->getIterator(); 9879 F->insert(It, FirstMBB); 9880 F->insert(It, SecondMBB); 9881 F->insert(It, SinkMBB); 9882 9883 // Transfer the remainder of ThisMBB and its successor edges to SinkMBB. 9884 SinkMBB->splice(SinkMBB->begin(), ThisMBB, 9885 std::next(MachineBasicBlock::iterator(First)), 9886 ThisMBB->end()); 9887 SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB); 9888 9889 // Fallthrough block for ThisMBB. 9890 ThisMBB->addSuccessor(FirstMBB); 9891 // Fallthrough block for FirstMBB. 9892 FirstMBB->addSuccessor(SecondMBB); 9893 ThisMBB->addSuccessor(SinkMBB); 9894 FirstMBB->addSuccessor(SinkMBB); 9895 // This is fallthrough. 9896 SecondMBB->addSuccessor(SinkMBB); 9897 9898 auto FirstCC = static_cast<RISCVCC::CondCode>(First.getOperand(3).getImm()); 9899 Register FLHS = First.getOperand(1).getReg(); 9900 Register FRHS = First.getOperand(2).getReg(); 9901 // Insert appropriate branch. 9902 BuildMI(FirstMBB, DL, TII.getBrCond(FirstCC)) 9903 .addReg(FLHS) 9904 .addReg(FRHS) 9905 .addMBB(SinkMBB); 9906 9907 Register SLHS = Second.getOperand(1).getReg(); 9908 Register SRHS = Second.getOperand(2).getReg(); 9909 Register Op1Reg4 = First.getOperand(4).getReg(); 9910 Register Op1Reg5 = First.getOperand(5).getReg(); 9911 9912 auto SecondCC = static_cast<RISCVCC::CondCode>(Second.getOperand(3).getImm()); 9913 // Insert appropriate branch. 9914 BuildMI(ThisMBB, DL, TII.getBrCond(SecondCC)) 9915 .addReg(SLHS) 9916 .addReg(SRHS) 9917 .addMBB(SinkMBB); 9918 9919 Register DestReg = Second.getOperand(0).getReg(); 9920 Register Op2Reg4 = Second.getOperand(4).getReg(); 9921 BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII.get(RISCV::PHI), DestReg) 9922 .addReg(Op2Reg4) 9923 .addMBB(ThisMBB) 9924 .addReg(Op1Reg4) 9925 .addMBB(FirstMBB) 9926 .addReg(Op1Reg5) 9927 .addMBB(SecondMBB); 9928 9929 // Now remove the Select_FPRX_s. 9930 First.eraseFromParent(); 9931 Second.eraseFromParent(); 9932 return SinkMBB; 9933 } 9934 9935 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9936 MachineBasicBlock *BB, 9937 const RISCVSubtarget &Subtarget) { 9938 // To "insert" Select_* instructions, we actually have to insert the triangle 9939 // control-flow pattern. The incoming instructions know the destination vreg 9940 // to set, the condition code register to branch on, the true/false values to 9941 // select between, and the condcode to use to select the appropriate branch. 9942 // 9943 // We produce the following control flow: 9944 // HeadMBB 9945 // | \ 9946 // | IfFalseMBB 9947 // | / 9948 // TailMBB 9949 // 9950 // When we find a sequence of selects we attempt to optimize their emission 9951 // by sharing the control flow. Currently we only handle cases where we have 9952 // multiple selects with the exact same condition (same LHS, RHS and CC). 9953 // The selects may be interleaved with other instructions if the other 9954 // instructions meet some requirements we deem safe: 9955 // - They are debug instructions. Otherwise, 9956 // - They do not have side-effects, do not access memory and their inputs do 9957 // not depend on the results of the select pseudo-instructions. 9958 // The TrueV/FalseV operands of the selects cannot depend on the result of 9959 // previous selects in the sequence. 9960 // These conditions could be further relaxed. See the X86 target for a 9961 // related approach and more information. 9962 // 9963 // Select_FPRX_ (rs1, rs2, imm, rs4, (Select_FPRX_ rs1, rs2, imm, rs4, rs5)) 9964 // is checked here and handled by a separate function - 9965 // EmitLoweredCascadedSelect. 9966 Register LHS = MI.getOperand(1).getReg(); 9967 Register RHS = MI.getOperand(2).getReg(); 9968 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9969 9970 SmallVector<MachineInstr *, 4> SelectDebugValues; 9971 SmallSet<Register, 4> SelectDests; 9972 SelectDests.insert(MI.getOperand(0).getReg()); 9973 9974 MachineInstr *LastSelectPseudo = &MI; 9975 auto Next = next_nodbg(MI.getIterator(), BB->instr_end()); 9976 if (MI.getOpcode() != RISCV::Select_GPR_Using_CC_GPR && Next != BB->end() && 9977 Next->getOpcode() == MI.getOpcode() && 9978 Next->getOperand(5).getReg() == MI.getOperand(0).getReg() && 9979 Next->getOperand(5).isKill()) { 9980 return EmitLoweredCascadedSelect(MI, *Next, BB, Subtarget); 9981 } 9982 9983 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9984 SequenceMBBI != E; ++SequenceMBBI) { 9985 if (SequenceMBBI->isDebugInstr()) 9986 continue; 9987 if (isSelectPseudo(*SequenceMBBI)) { 9988 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9989 SequenceMBBI->getOperand(2).getReg() != RHS || 9990 SequenceMBBI->getOperand(3).getImm() != CC || 9991 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9992 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9993 break; 9994 LastSelectPseudo = &*SequenceMBBI; 9995 SequenceMBBI->collectDebugValues(SelectDebugValues); 9996 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9997 } else { 9998 if (SequenceMBBI->hasUnmodeledSideEffects() || 9999 SequenceMBBI->mayLoadOrStore()) 10000 break; 10001 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 10002 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 10003 })) 10004 break; 10005 } 10006 } 10007 10008 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 10009 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10010 DebugLoc DL = MI.getDebugLoc(); 10011 MachineFunction::iterator I = ++BB->getIterator(); 10012 10013 MachineBasicBlock *HeadMBB = BB; 10014 MachineFunction *F = BB->getParent(); 10015 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 10016 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 10017 10018 F->insert(I, IfFalseMBB); 10019 F->insert(I, TailMBB); 10020 10021 // Transfer debug instructions associated with the selects to TailMBB. 10022 for (MachineInstr *DebugInstr : SelectDebugValues) { 10023 TailMBB->push_back(DebugInstr->removeFromParent()); 10024 } 10025 10026 // Move all instructions after the sequence to TailMBB. 10027 TailMBB->splice(TailMBB->end(), HeadMBB, 10028 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 10029 // Update machine-CFG edges by transferring all successors of the current 10030 // block to the new block which will contain the Phi nodes for the selects. 10031 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 10032 // Set the successors for HeadMBB. 10033 HeadMBB->addSuccessor(IfFalseMBB); 10034 HeadMBB->addSuccessor(TailMBB); 10035 10036 // Insert appropriate branch. 10037 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 10038 .addReg(LHS) 10039 .addReg(RHS) 10040 .addMBB(TailMBB); 10041 10042 // IfFalseMBB just falls through to TailMBB. 10043 IfFalseMBB->addSuccessor(TailMBB); 10044 10045 // Create PHIs for all of the select pseudo-instructions. 10046 auto SelectMBBI = MI.getIterator(); 10047 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 10048 auto InsertionPoint = TailMBB->begin(); 10049 while (SelectMBBI != SelectEnd) { 10050 auto Next = std::next(SelectMBBI); 10051 if (isSelectPseudo(*SelectMBBI)) { 10052 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 10053 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 10054 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 10055 .addReg(SelectMBBI->getOperand(4).getReg()) 10056 .addMBB(HeadMBB) 10057 .addReg(SelectMBBI->getOperand(5).getReg()) 10058 .addMBB(IfFalseMBB); 10059 SelectMBBI->eraseFromParent(); 10060 } 10061 SelectMBBI = Next; 10062 } 10063 10064 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 10065 return TailMBB; 10066 } 10067 10068 MachineBasicBlock * 10069 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10070 MachineBasicBlock *BB) const { 10071 switch (MI.getOpcode()) { 10072 default: 10073 llvm_unreachable("Unexpected instr type to insert"); 10074 case RISCV::ReadCycleWide: 10075 assert(!Subtarget.is64Bit() && 10076 "ReadCycleWrite is only to be used on riscv32"); 10077 return emitReadCycleWidePseudo(MI, BB); 10078 case RISCV::Select_GPR_Using_CC_GPR: 10079 case RISCV::Select_FPR16_Using_CC_GPR: 10080 case RISCV::Select_FPR32_Using_CC_GPR: 10081 case RISCV::Select_FPR64_Using_CC_GPR: 10082 return emitSelectPseudo(MI, BB, Subtarget); 10083 case RISCV::BuildPairF64Pseudo: 10084 return emitBuildPairF64Pseudo(MI, BB); 10085 case RISCV::SplitF64Pseudo: 10086 return emitSplitF64Pseudo(MI, BB); 10087 case RISCV::PseudoQuietFLE_H: 10088 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 10089 case RISCV::PseudoQuietFLT_H: 10090 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 10091 case RISCV::PseudoQuietFLE_S: 10092 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 10093 case RISCV::PseudoQuietFLT_S: 10094 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 10095 case RISCV::PseudoQuietFLE_D: 10096 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 10097 case RISCV::PseudoQuietFLT_D: 10098 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 10099 } 10100 } 10101 10102 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10103 SDNode *Node) const { 10104 // Add FRM dependency to any instructions with dynamic rounding mode. 10105 unsigned Opc = MI.getOpcode(); 10106 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 10107 if (Idx < 0) 10108 return; 10109 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 10110 return; 10111 // If the instruction already reads FRM, don't add another read. 10112 if (MI.readsRegister(RISCV::FRM)) 10113 return; 10114 MI.addOperand( 10115 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 10116 } 10117 10118 // Calling Convention Implementation. 10119 // The expectations for frontend ABI lowering vary from target to target. 10120 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 10121 // details, but this is a longer term goal. For now, we simply try to keep the 10122 // role of the frontend as simple and well-defined as possible. The rules can 10123 // be summarised as: 10124 // * Never split up large scalar arguments. We handle them here. 10125 // * If a hardfloat calling convention is being used, and the struct may be 10126 // passed in a pair of registers (fp+fp, int+fp), and both registers are 10127 // available, then pass as two separate arguments. If either the GPRs or FPRs 10128 // are exhausted, then pass according to the rule below. 10129 // * If a struct could never be passed in registers or directly in a stack 10130 // slot (as it is larger than 2*XLEN and the floating point rules don't 10131 // apply), then pass it using a pointer with the byval attribute. 10132 // * If a struct is less than 2*XLEN, then coerce to either a two-element 10133 // word-sized array or a 2*XLEN scalar (depending on alignment). 10134 // * The frontend can determine whether a struct is returned by reference or 10135 // not based on its size and fields. If it will be returned by reference, the 10136 // frontend must modify the prototype so a pointer with the sret annotation is 10137 // passed as the first argument. This is not necessary for large scalar 10138 // returns. 10139 // * Struct return values and varargs should be coerced to structs containing 10140 // register-size fields in the same situations they would be for fixed 10141 // arguments. 10142 10143 static const MCPhysReg ArgGPRs[] = { 10144 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 10145 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 10146 }; 10147 static const MCPhysReg ArgFPR16s[] = { 10148 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 10149 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 10150 }; 10151 static const MCPhysReg ArgFPR32s[] = { 10152 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 10153 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 10154 }; 10155 static const MCPhysReg ArgFPR64s[] = { 10156 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 10157 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 10158 }; 10159 // This is an interim calling convention and it may be changed in the future. 10160 static const MCPhysReg ArgVRs[] = { 10161 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 10162 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 10163 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 10164 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 10165 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 10166 RISCV::V20M2, RISCV::V22M2}; 10167 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 10168 RISCV::V20M4}; 10169 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 10170 10171 // Pass a 2*XLEN argument that has been split into two XLEN values through 10172 // registers or the stack as necessary. 10173 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 10174 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 10175 MVT ValVT2, MVT LocVT2, 10176 ISD::ArgFlagsTy ArgFlags2) { 10177 unsigned XLenInBytes = XLen / 8; 10178 if (Register Reg = State.AllocateReg(ArgGPRs)) { 10179 // At least one half can be passed via register. 10180 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 10181 VA1.getLocVT(), CCValAssign::Full)); 10182 } else { 10183 // Both halves must be passed on the stack, with proper alignment. 10184 Align StackAlign = 10185 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 10186 State.addLoc( 10187 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 10188 State.AllocateStack(XLenInBytes, StackAlign), 10189 VA1.getLocVT(), CCValAssign::Full)); 10190 State.addLoc(CCValAssign::getMem( 10191 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 10192 LocVT2, CCValAssign::Full)); 10193 return false; 10194 } 10195 10196 if (Register Reg = State.AllocateReg(ArgGPRs)) { 10197 // The second half can also be passed via register. 10198 State.addLoc( 10199 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 10200 } else { 10201 // The second half is passed via the stack, without additional alignment. 10202 State.addLoc(CCValAssign::getMem( 10203 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 10204 LocVT2, CCValAssign::Full)); 10205 } 10206 10207 return false; 10208 } 10209 10210 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 10211 Optional<unsigned> FirstMaskArgument, 10212 CCState &State, const RISCVTargetLowering &TLI) { 10213 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 10214 if (RC == &RISCV::VRRegClass) { 10215 // Assign the first mask argument to V0. 10216 // This is an interim calling convention and it may be changed in the 10217 // future. 10218 if (FirstMaskArgument && ValNo == *FirstMaskArgument) 10219 return State.AllocateReg(RISCV::V0); 10220 return State.AllocateReg(ArgVRs); 10221 } 10222 if (RC == &RISCV::VRM2RegClass) 10223 return State.AllocateReg(ArgVRM2s); 10224 if (RC == &RISCV::VRM4RegClass) 10225 return State.AllocateReg(ArgVRM4s); 10226 if (RC == &RISCV::VRM8RegClass) 10227 return State.AllocateReg(ArgVRM8s); 10228 llvm_unreachable("Unhandled register class for ValueType"); 10229 } 10230 10231 // Implements the RISC-V calling convention. Returns true upon failure. 10232 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 10233 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 10234 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 10235 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 10236 Optional<unsigned> FirstMaskArgument) { 10237 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 10238 assert(XLen == 32 || XLen == 64); 10239 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 10240 10241 // Any return value split in to more than two values can't be returned 10242 // directly. Vectors are returned via the available vector registers. 10243 if (!LocVT.isVector() && IsRet && ValNo > 1) 10244 return true; 10245 10246 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 10247 // variadic argument, or if no F16/F32 argument registers are available. 10248 bool UseGPRForF16_F32 = true; 10249 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 10250 // variadic argument, or if no F64 argument registers are available. 10251 bool UseGPRForF64 = true; 10252 10253 switch (ABI) { 10254 default: 10255 llvm_unreachable("Unexpected ABI"); 10256 case RISCVABI::ABI_ILP32: 10257 case RISCVABI::ABI_LP64: 10258 break; 10259 case RISCVABI::ABI_ILP32F: 10260 case RISCVABI::ABI_LP64F: 10261 UseGPRForF16_F32 = !IsFixed; 10262 break; 10263 case RISCVABI::ABI_ILP32D: 10264 case RISCVABI::ABI_LP64D: 10265 UseGPRForF16_F32 = !IsFixed; 10266 UseGPRForF64 = !IsFixed; 10267 break; 10268 } 10269 10270 // FPR16, FPR32, and FPR64 alias each other. 10271 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 10272 UseGPRForF16_F32 = true; 10273 UseGPRForF64 = true; 10274 } 10275 10276 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 10277 // similar local variables rather than directly checking against the target 10278 // ABI. 10279 10280 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 10281 LocVT = XLenVT; 10282 LocInfo = CCValAssign::BCvt; 10283 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 10284 LocVT = MVT::i64; 10285 LocInfo = CCValAssign::BCvt; 10286 } 10287 10288 // If this is a variadic argument, the RISC-V calling convention requires 10289 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 10290 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 10291 // be used regardless of whether the original argument was split during 10292 // legalisation or not. The argument will not be passed by registers if the 10293 // original type is larger than 2*XLEN, so the register alignment rule does 10294 // not apply. 10295 unsigned TwoXLenInBytes = (2 * XLen) / 8; 10296 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 10297 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 10298 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 10299 // Skip 'odd' register if necessary. 10300 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 10301 State.AllocateReg(ArgGPRs); 10302 } 10303 10304 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 10305 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 10306 State.getPendingArgFlags(); 10307 10308 assert(PendingLocs.size() == PendingArgFlags.size() && 10309 "PendingLocs and PendingArgFlags out of sync"); 10310 10311 // Handle passing f64 on RV32D with a soft float ABI or when floating point 10312 // registers are exhausted. 10313 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 10314 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 10315 "Can't lower f64 if it is split"); 10316 // Depending on available argument GPRS, f64 may be passed in a pair of 10317 // GPRs, split between a GPR and the stack, or passed completely on the 10318 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 10319 // cases. 10320 Register Reg = State.AllocateReg(ArgGPRs); 10321 LocVT = MVT::i32; 10322 if (!Reg) { 10323 unsigned StackOffset = State.AllocateStack(8, Align(8)); 10324 State.addLoc( 10325 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10326 return false; 10327 } 10328 if (!State.AllocateReg(ArgGPRs)) 10329 State.AllocateStack(4, Align(4)); 10330 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10331 return false; 10332 } 10333 10334 // Fixed-length vectors are located in the corresponding scalable-vector 10335 // container types. 10336 if (ValVT.isFixedLengthVector()) 10337 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10338 10339 // Split arguments might be passed indirectly, so keep track of the pending 10340 // values. Split vectors are passed via a mix of registers and indirectly, so 10341 // treat them as we would any other argument. 10342 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 10343 LocVT = XLenVT; 10344 LocInfo = CCValAssign::Indirect; 10345 PendingLocs.push_back( 10346 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 10347 PendingArgFlags.push_back(ArgFlags); 10348 if (!ArgFlags.isSplitEnd()) { 10349 return false; 10350 } 10351 } 10352 10353 // If the split argument only had two elements, it should be passed directly 10354 // in registers or on the stack. 10355 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 10356 PendingLocs.size() <= 2) { 10357 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 10358 // Apply the normal calling convention rules to the first half of the 10359 // split argument. 10360 CCValAssign VA = PendingLocs[0]; 10361 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 10362 PendingLocs.clear(); 10363 PendingArgFlags.clear(); 10364 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 10365 ArgFlags); 10366 } 10367 10368 // Allocate to a register if possible, or else a stack slot. 10369 Register Reg; 10370 unsigned StoreSizeBytes = XLen / 8; 10371 Align StackAlign = Align(XLen / 8); 10372 10373 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 10374 Reg = State.AllocateReg(ArgFPR16s); 10375 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 10376 Reg = State.AllocateReg(ArgFPR32s); 10377 else if (ValVT == MVT::f64 && !UseGPRForF64) 10378 Reg = State.AllocateReg(ArgFPR64s); 10379 else if (ValVT.isVector()) { 10380 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 10381 if (!Reg) { 10382 // For return values, the vector must be passed fully via registers or 10383 // via the stack. 10384 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 10385 // but we're using all of them. 10386 if (IsRet) 10387 return true; 10388 // Try using a GPR to pass the address 10389 if ((Reg = State.AllocateReg(ArgGPRs))) { 10390 LocVT = XLenVT; 10391 LocInfo = CCValAssign::Indirect; 10392 } else if (ValVT.isScalableVector()) { 10393 LocVT = XLenVT; 10394 LocInfo = CCValAssign::Indirect; 10395 } else { 10396 // Pass fixed-length vectors on the stack. 10397 LocVT = ValVT; 10398 StoreSizeBytes = ValVT.getStoreSize(); 10399 // Align vectors to their element sizes, being careful for vXi1 10400 // vectors. 10401 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10402 } 10403 } 10404 } else { 10405 Reg = State.AllocateReg(ArgGPRs); 10406 } 10407 10408 unsigned StackOffset = 10409 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 10410 10411 // If we reach this point and PendingLocs is non-empty, we must be at the 10412 // end of a split argument that must be passed indirectly. 10413 if (!PendingLocs.empty()) { 10414 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 10415 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 10416 10417 for (auto &It : PendingLocs) { 10418 if (Reg) 10419 It.convertToReg(Reg); 10420 else 10421 It.convertToMem(StackOffset); 10422 State.addLoc(It); 10423 } 10424 PendingLocs.clear(); 10425 PendingArgFlags.clear(); 10426 return false; 10427 } 10428 10429 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 10430 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 10431 "Expected an XLenVT or vector types at this stage"); 10432 10433 if (Reg) { 10434 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10435 return false; 10436 } 10437 10438 // When a floating-point value is passed on the stack, no bit-conversion is 10439 // needed. 10440 if (ValVT.isFloatingPoint()) { 10441 LocVT = ValVT; 10442 LocInfo = CCValAssign::Full; 10443 } 10444 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10445 return false; 10446 } 10447 10448 template <typename ArgTy> 10449 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 10450 for (const auto &ArgIdx : enumerate(Args)) { 10451 MVT ArgVT = ArgIdx.value().VT; 10452 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 10453 return ArgIdx.index(); 10454 } 10455 return None; 10456 } 10457 10458 void RISCVTargetLowering::analyzeInputArgs( 10459 MachineFunction &MF, CCState &CCInfo, 10460 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 10461 RISCVCCAssignFn Fn) const { 10462 unsigned NumArgs = Ins.size(); 10463 FunctionType *FType = MF.getFunction().getFunctionType(); 10464 10465 Optional<unsigned> FirstMaskArgument; 10466 if (Subtarget.hasVInstructions()) 10467 FirstMaskArgument = preAssignMask(Ins); 10468 10469 for (unsigned i = 0; i != NumArgs; ++i) { 10470 MVT ArgVT = Ins[i].VT; 10471 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 10472 10473 Type *ArgTy = nullptr; 10474 if (IsRet) 10475 ArgTy = FType->getReturnType(); 10476 else if (Ins[i].isOrigArg()) 10477 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 10478 10479 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10480 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10481 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 10482 FirstMaskArgument)) { 10483 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 10484 << EVT(ArgVT).getEVTString() << '\n'); 10485 llvm_unreachable(nullptr); 10486 } 10487 } 10488 } 10489 10490 void RISCVTargetLowering::analyzeOutputArgs( 10491 MachineFunction &MF, CCState &CCInfo, 10492 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 10493 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 10494 unsigned NumArgs = Outs.size(); 10495 10496 Optional<unsigned> FirstMaskArgument; 10497 if (Subtarget.hasVInstructions()) 10498 FirstMaskArgument = preAssignMask(Outs); 10499 10500 for (unsigned i = 0; i != NumArgs; i++) { 10501 MVT ArgVT = Outs[i].VT; 10502 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10503 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 10504 10505 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10506 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10507 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 10508 FirstMaskArgument)) { 10509 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 10510 << EVT(ArgVT).getEVTString() << "\n"); 10511 llvm_unreachable(nullptr); 10512 } 10513 } 10514 } 10515 10516 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 10517 // values. 10518 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 10519 const CCValAssign &VA, const SDLoc &DL, 10520 const RISCVSubtarget &Subtarget) { 10521 switch (VA.getLocInfo()) { 10522 default: 10523 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10524 case CCValAssign::Full: 10525 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 10526 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 10527 break; 10528 case CCValAssign::BCvt: 10529 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10530 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 10531 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10532 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 10533 else 10534 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 10535 break; 10536 } 10537 return Val; 10538 } 10539 10540 // The caller is responsible for loading the full value if the argument is 10541 // passed with CCValAssign::Indirect. 10542 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 10543 const CCValAssign &VA, const SDLoc &DL, 10544 const RISCVTargetLowering &TLI) { 10545 MachineFunction &MF = DAG.getMachineFunction(); 10546 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10547 EVT LocVT = VA.getLocVT(); 10548 SDValue Val; 10549 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 10550 Register VReg = RegInfo.createVirtualRegister(RC); 10551 RegInfo.addLiveIn(VA.getLocReg(), VReg); 10552 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 10553 10554 if (VA.getLocInfo() == CCValAssign::Indirect) 10555 return Val; 10556 10557 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 10558 } 10559 10560 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 10561 const CCValAssign &VA, const SDLoc &DL, 10562 const RISCVSubtarget &Subtarget) { 10563 EVT LocVT = VA.getLocVT(); 10564 10565 switch (VA.getLocInfo()) { 10566 default: 10567 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10568 case CCValAssign::Full: 10569 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 10570 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 10571 break; 10572 case CCValAssign::BCvt: 10573 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10574 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 10575 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10576 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 10577 else 10578 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 10579 break; 10580 } 10581 return Val; 10582 } 10583 10584 // The caller is responsible for loading the full value if the argument is 10585 // passed with CCValAssign::Indirect. 10586 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 10587 const CCValAssign &VA, const SDLoc &DL) { 10588 MachineFunction &MF = DAG.getMachineFunction(); 10589 MachineFrameInfo &MFI = MF.getFrameInfo(); 10590 EVT LocVT = VA.getLocVT(); 10591 EVT ValVT = VA.getValVT(); 10592 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 10593 if (ValVT.isScalableVector()) { 10594 // When the value is a scalable vector, we save the pointer which points to 10595 // the scalable vector value in the stack. The ValVT will be the pointer 10596 // type, instead of the scalable vector type. 10597 ValVT = LocVT; 10598 } 10599 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 10600 /*IsImmutable=*/true); 10601 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 10602 SDValue Val; 10603 10604 ISD::LoadExtType ExtType; 10605 switch (VA.getLocInfo()) { 10606 default: 10607 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10608 case CCValAssign::Full: 10609 case CCValAssign::Indirect: 10610 case CCValAssign::BCvt: 10611 ExtType = ISD::NON_EXTLOAD; 10612 break; 10613 } 10614 Val = DAG.getExtLoad( 10615 ExtType, DL, LocVT, Chain, FIN, 10616 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 10617 return Val; 10618 } 10619 10620 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 10621 const CCValAssign &VA, const SDLoc &DL) { 10622 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 10623 "Unexpected VA"); 10624 MachineFunction &MF = DAG.getMachineFunction(); 10625 MachineFrameInfo &MFI = MF.getFrameInfo(); 10626 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10627 10628 if (VA.isMemLoc()) { 10629 // f64 is passed on the stack. 10630 int FI = 10631 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 10632 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10633 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 10634 MachinePointerInfo::getFixedStack(MF, FI)); 10635 } 10636 10637 assert(VA.isRegLoc() && "Expected register VA assignment"); 10638 10639 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10640 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 10641 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 10642 SDValue Hi; 10643 if (VA.getLocReg() == RISCV::X17) { 10644 // Second half of f64 is passed on the stack. 10645 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 10646 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10647 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 10648 MachinePointerInfo::getFixedStack(MF, FI)); 10649 } else { 10650 // Second half of f64 is passed in another GPR. 10651 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10652 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 10653 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 10654 } 10655 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 10656 } 10657 10658 // FastCC has less than 1% performance improvement for some particular 10659 // benchmark. But theoretically, it may has benenfit for some cases. 10660 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 10661 unsigned ValNo, MVT ValVT, MVT LocVT, 10662 CCValAssign::LocInfo LocInfo, 10663 ISD::ArgFlagsTy ArgFlags, CCState &State, 10664 bool IsFixed, bool IsRet, Type *OrigTy, 10665 const RISCVTargetLowering &TLI, 10666 Optional<unsigned> FirstMaskArgument) { 10667 10668 // X5 and X6 might be used for save-restore libcall. 10669 static const MCPhysReg GPRList[] = { 10670 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 10671 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 10672 RISCV::X29, RISCV::X30, RISCV::X31}; 10673 10674 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10675 if (unsigned Reg = State.AllocateReg(GPRList)) { 10676 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10677 return false; 10678 } 10679 } 10680 10681 if (LocVT == MVT::f16) { 10682 static const MCPhysReg FPR16List[] = { 10683 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 10684 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 10685 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 10686 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 10687 if (unsigned Reg = State.AllocateReg(FPR16List)) { 10688 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10689 return false; 10690 } 10691 } 10692 10693 if (LocVT == MVT::f32) { 10694 static const MCPhysReg FPR32List[] = { 10695 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 10696 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 10697 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 10698 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 10699 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10700 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10701 return false; 10702 } 10703 } 10704 10705 if (LocVT == MVT::f64) { 10706 static const MCPhysReg FPR64List[] = { 10707 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 10708 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 10709 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 10710 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 10711 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10712 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10713 return false; 10714 } 10715 } 10716 10717 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 10718 unsigned Offset4 = State.AllocateStack(4, Align(4)); 10719 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 10720 return false; 10721 } 10722 10723 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 10724 unsigned Offset5 = State.AllocateStack(8, Align(8)); 10725 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 10726 return false; 10727 } 10728 10729 if (LocVT.isVector()) { 10730 if (unsigned Reg = 10731 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 10732 // Fixed-length vectors are located in the corresponding scalable-vector 10733 // container types. 10734 if (ValVT.isFixedLengthVector()) 10735 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10736 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10737 } else { 10738 // Try and pass the address via a "fast" GPR. 10739 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 10740 LocInfo = CCValAssign::Indirect; 10741 LocVT = TLI.getSubtarget().getXLenVT(); 10742 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 10743 } else if (ValVT.isFixedLengthVector()) { 10744 auto StackAlign = 10745 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10746 unsigned StackOffset = 10747 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 10748 State.addLoc( 10749 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10750 } else { 10751 // Can't pass scalable vectors on the stack. 10752 return true; 10753 } 10754 } 10755 10756 return false; 10757 } 10758 10759 return true; // CC didn't match. 10760 } 10761 10762 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 10763 CCValAssign::LocInfo LocInfo, 10764 ISD::ArgFlagsTy ArgFlags, CCState &State) { 10765 10766 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10767 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 10768 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 10769 static const MCPhysReg GPRList[] = { 10770 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 10771 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 10772 if (unsigned Reg = State.AllocateReg(GPRList)) { 10773 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10774 return false; 10775 } 10776 } 10777 10778 if (LocVT == MVT::f32) { 10779 // Pass in STG registers: F1, ..., F6 10780 // fs0 ... fs5 10781 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 10782 RISCV::F18_F, RISCV::F19_F, 10783 RISCV::F20_F, RISCV::F21_F}; 10784 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10785 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10786 return false; 10787 } 10788 } 10789 10790 if (LocVT == MVT::f64) { 10791 // Pass in STG registers: D1, ..., D6 10792 // fs6 ... fs11 10793 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 10794 RISCV::F24_D, RISCV::F25_D, 10795 RISCV::F26_D, RISCV::F27_D}; 10796 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10797 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10798 return false; 10799 } 10800 } 10801 10802 report_fatal_error("No registers left in GHC calling convention"); 10803 return true; 10804 } 10805 10806 // Transform physical registers into virtual registers. 10807 SDValue RISCVTargetLowering::LowerFormalArguments( 10808 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 10809 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 10810 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 10811 10812 MachineFunction &MF = DAG.getMachineFunction(); 10813 10814 switch (CallConv) { 10815 default: 10816 report_fatal_error("Unsupported calling convention"); 10817 case CallingConv::C: 10818 case CallingConv::Fast: 10819 break; 10820 case CallingConv::GHC: 10821 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10822 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10823 report_fatal_error( 10824 "GHC calling convention requires the F and D instruction set extensions"); 10825 } 10826 10827 const Function &Func = MF.getFunction(); 10828 if (Func.hasFnAttribute("interrupt")) { 10829 if (!Func.arg_empty()) 10830 report_fatal_error( 10831 "Functions with the interrupt attribute cannot have arguments!"); 10832 10833 StringRef Kind = 10834 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10835 10836 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10837 report_fatal_error( 10838 "Function interrupt attribute argument not supported!"); 10839 } 10840 10841 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10842 MVT XLenVT = Subtarget.getXLenVT(); 10843 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10844 // Used with vargs to acumulate store chains. 10845 std::vector<SDValue> OutChains; 10846 10847 // Assign locations to all of the incoming arguments. 10848 SmallVector<CCValAssign, 16> ArgLocs; 10849 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10850 10851 if (CallConv == CallingConv::GHC) 10852 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10853 else 10854 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10855 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10856 : CC_RISCV); 10857 10858 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10859 CCValAssign &VA = ArgLocs[i]; 10860 SDValue ArgValue; 10861 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10862 // case. 10863 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10864 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10865 else if (VA.isRegLoc()) 10866 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10867 else 10868 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10869 10870 if (VA.getLocInfo() == CCValAssign::Indirect) { 10871 // If the original argument was split and passed by reference (e.g. i128 10872 // on RV32), we need to load all parts of it here (using the same 10873 // address). Vectors may be partly split to registers and partly to the 10874 // stack, in which case the base address is partly offset and subsequent 10875 // stores are relative to that. 10876 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10877 MachinePointerInfo())); 10878 unsigned ArgIndex = Ins[i].OrigArgIndex; 10879 unsigned ArgPartOffset = Ins[i].PartOffset; 10880 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10881 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10882 CCValAssign &PartVA = ArgLocs[i + 1]; 10883 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10884 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10885 if (PartVA.getValVT().isScalableVector()) 10886 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10887 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10888 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10889 MachinePointerInfo())); 10890 ++i; 10891 } 10892 continue; 10893 } 10894 InVals.push_back(ArgValue); 10895 } 10896 10897 if (IsVarArg) { 10898 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10899 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10900 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10901 MachineFrameInfo &MFI = MF.getFrameInfo(); 10902 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10903 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10904 10905 // Offset of the first variable argument from stack pointer, and size of 10906 // the vararg save area. For now, the varargs save area is either zero or 10907 // large enough to hold a0-a7. 10908 int VaArgOffset, VarArgsSaveSize; 10909 10910 // If all registers are allocated, then all varargs must be passed on the 10911 // stack and we don't need to save any argregs. 10912 if (ArgRegs.size() == Idx) { 10913 VaArgOffset = CCInfo.getNextStackOffset(); 10914 VarArgsSaveSize = 0; 10915 } else { 10916 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10917 VaArgOffset = -VarArgsSaveSize; 10918 } 10919 10920 // Record the frame index of the first variable argument 10921 // which is a value necessary to VASTART. 10922 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10923 RVFI->setVarArgsFrameIndex(FI); 10924 10925 // If saving an odd number of registers then create an extra stack slot to 10926 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10927 // offsets to even-numbered registered remain 2*XLEN-aligned. 10928 if (Idx % 2) { 10929 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10930 VarArgsSaveSize += XLenInBytes; 10931 } 10932 10933 // Copy the integer registers that may have been used for passing varargs 10934 // to the vararg save area. 10935 for (unsigned I = Idx; I < ArgRegs.size(); 10936 ++I, VaArgOffset += XLenInBytes) { 10937 const Register Reg = RegInfo.createVirtualRegister(RC); 10938 RegInfo.addLiveIn(ArgRegs[I], Reg); 10939 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10940 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10941 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10942 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10943 MachinePointerInfo::getFixedStack(MF, FI)); 10944 cast<StoreSDNode>(Store.getNode()) 10945 ->getMemOperand() 10946 ->setValue((Value *)nullptr); 10947 OutChains.push_back(Store); 10948 } 10949 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10950 } 10951 10952 // All stores are grouped in one node to allow the matching between 10953 // the size of Ins and InVals. This only happens for vararg functions. 10954 if (!OutChains.empty()) { 10955 OutChains.push_back(Chain); 10956 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10957 } 10958 10959 return Chain; 10960 } 10961 10962 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10963 /// for tail call optimization. 10964 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10965 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10966 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10967 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10968 10969 auto &Callee = CLI.Callee; 10970 auto CalleeCC = CLI.CallConv; 10971 auto &Outs = CLI.Outs; 10972 auto &Caller = MF.getFunction(); 10973 auto CallerCC = Caller.getCallingConv(); 10974 10975 // Exception-handling functions need a special set of instructions to 10976 // indicate a return to the hardware. Tail-calling another function would 10977 // probably break this. 10978 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10979 // should be expanded as new function attributes are introduced. 10980 if (Caller.hasFnAttribute("interrupt")) 10981 return false; 10982 10983 // Do not tail call opt if the stack is used to pass parameters. 10984 if (CCInfo.getNextStackOffset() != 0) 10985 return false; 10986 10987 // Do not tail call opt if any parameters need to be passed indirectly. 10988 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10989 // passed indirectly. So the address of the value will be passed in a 10990 // register, or if not available, then the address is put on the stack. In 10991 // order to pass indirectly, space on the stack often needs to be allocated 10992 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10993 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10994 // are passed CCValAssign::Indirect. 10995 for (auto &VA : ArgLocs) 10996 if (VA.getLocInfo() == CCValAssign::Indirect) 10997 return false; 10998 10999 // Do not tail call opt if either caller or callee uses struct return 11000 // semantics. 11001 auto IsCallerStructRet = Caller.hasStructRetAttr(); 11002 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 11003 if (IsCallerStructRet || IsCalleeStructRet) 11004 return false; 11005 11006 // Externally-defined functions with weak linkage should not be 11007 // tail-called. The behaviour of branch instructions in this situation (as 11008 // used for tail calls) is implementation-defined, so we cannot rely on the 11009 // linker replacing the tail call with a return. 11010 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 11011 const GlobalValue *GV = G->getGlobal(); 11012 if (GV->hasExternalWeakLinkage()) 11013 return false; 11014 } 11015 11016 // The callee has to preserve all registers the caller needs to preserve. 11017 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11018 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 11019 if (CalleeCC != CallerCC) { 11020 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 11021 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 11022 return false; 11023 } 11024 11025 // Byval parameters hand the function a pointer directly into the stack area 11026 // we want to reuse during a tail call. Working around this *is* possible 11027 // but less efficient and uglier in LowerCall. 11028 for (auto &Arg : Outs) 11029 if (Arg.Flags.isByVal()) 11030 return false; 11031 11032 return true; 11033 } 11034 11035 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 11036 return DAG.getDataLayout().getPrefTypeAlign( 11037 VT.getTypeForEVT(*DAG.getContext())); 11038 } 11039 11040 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 11041 // and output parameter nodes. 11042 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 11043 SmallVectorImpl<SDValue> &InVals) const { 11044 SelectionDAG &DAG = CLI.DAG; 11045 SDLoc &DL = CLI.DL; 11046 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 11047 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 11048 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 11049 SDValue Chain = CLI.Chain; 11050 SDValue Callee = CLI.Callee; 11051 bool &IsTailCall = CLI.IsTailCall; 11052 CallingConv::ID CallConv = CLI.CallConv; 11053 bool IsVarArg = CLI.IsVarArg; 11054 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 11055 MVT XLenVT = Subtarget.getXLenVT(); 11056 11057 MachineFunction &MF = DAG.getMachineFunction(); 11058 11059 // Analyze the operands of the call, assigning locations to each operand. 11060 SmallVector<CCValAssign, 16> ArgLocs; 11061 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 11062 11063 if (CallConv == CallingConv::GHC) 11064 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 11065 else 11066 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 11067 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 11068 : CC_RISCV); 11069 11070 // Check if it's really possible to do a tail call. 11071 if (IsTailCall) 11072 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 11073 11074 if (IsTailCall) 11075 ++NumTailCalls; 11076 else if (CLI.CB && CLI.CB->isMustTailCall()) 11077 report_fatal_error("failed to perform tail call elimination on a call " 11078 "site marked musttail"); 11079 11080 // Get a count of how many bytes are to be pushed on the stack. 11081 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 11082 11083 // Create local copies for byval args 11084 SmallVector<SDValue, 8> ByValArgs; 11085 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 11086 ISD::ArgFlagsTy Flags = Outs[i].Flags; 11087 if (!Flags.isByVal()) 11088 continue; 11089 11090 SDValue Arg = OutVals[i]; 11091 unsigned Size = Flags.getByValSize(); 11092 Align Alignment = Flags.getNonZeroByValAlign(); 11093 11094 int FI = 11095 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 11096 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 11097 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 11098 11099 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 11100 /*IsVolatile=*/false, 11101 /*AlwaysInline=*/false, IsTailCall, 11102 MachinePointerInfo(), MachinePointerInfo()); 11103 ByValArgs.push_back(FIPtr); 11104 } 11105 11106 if (!IsTailCall) 11107 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 11108 11109 // Copy argument values to their designated locations. 11110 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 11111 SmallVector<SDValue, 8> MemOpChains; 11112 SDValue StackPtr; 11113 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 11114 CCValAssign &VA = ArgLocs[i]; 11115 SDValue ArgValue = OutVals[i]; 11116 ISD::ArgFlagsTy Flags = Outs[i].Flags; 11117 11118 // Handle passing f64 on RV32D with a soft float ABI as a special case. 11119 bool IsF64OnRV32DSoftABI = 11120 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 11121 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 11122 SDValue SplitF64 = DAG.getNode( 11123 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 11124 SDValue Lo = SplitF64.getValue(0); 11125 SDValue Hi = SplitF64.getValue(1); 11126 11127 Register RegLo = VA.getLocReg(); 11128 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 11129 11130 if (RegLo == RISCV::X17) { 11131 // Second half of f64 is passed on the stack. 11132 // Work out the address of the stack slot. 11133 if (!StackPtr.getNode()) 11134 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 11135 // Emit the store. 11136 MemOpChains.push_back( 11137 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 11138 } else { 11139 // Second half of f64 is passed in another GPR. 11140 assert(RegLo < RISCV::X31 && "Invalid register pair"); 11141 Register RegHigh = RegLo + 1; 11142 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 11143 } 11144 continue; 11145 } 11146 11147 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 11148 // as any other MemLoc. 11149 11150 // Promote the value if needed. 11151 // For now, only handle fully promoted and indirect arguments. 11152 if (VA.getLocInfo() == CCValAssign::Indirect) { 11153 // Store the argument in a stack slot and pass its address. 11154 Align StackAlign = 11155 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 11156 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 11157 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 11158 // If the original argument was split (e.g. i128), we need 11159 // to store the required parts of it here (and pass just one address). 11160 // Vectors may be partly split to registers and partly to the stack, in 11161 // which case the base address is partly offset and subsequent stores are 11162 // relative to that. 11163 unsigned ArgIndex = Outs[i].OrigArgIndex; 11164 unsigned ArgPartOffset = Outs[i].PartOffset; 11165 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 11166 // Calculate the total size to store. We don't have access to what we're 11167 // actually storing other than performing the loop and collecting the 11168 // info. 11169 SmallVector<std::pair<SDValue, SDValue>> Parts; 11170 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 11171 SDValue PartValue = OutVals[i + 1]; 11172 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 11173 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 11174 EVT PartVT = PartValue.getValueType(); 11175 if (PartVT.isScalableVector()) 11176 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 11177 StoredSize += PartVT.getStoreSize(); 11178 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 11179 Parts.push_back(std::make_pair(PartValue, Offset)); 11180 ++i; 11181 } 11182 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 11183 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 11184 MemOpChains.push_back( 11185 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 11186 MachinePointerInfo::getFixedStack(MF, FI))); 11187 for (const auto &Part : Parts) { 11188 SDValue PartValue = Part.first; 11189 SDValue PartOffset = Part.second; 11190 SDValue Address = 11191 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 11192 MemOpChains.push_back( 11193 DAG.getStore(Chain, DL, PartValue, Address, 11194 MachinePointerInfo::getFixedStack(MF, FI))); 11195 } 11196 ArgValue = SpillSlot; 11197 } else { 11198 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 11199 } 11200 11201 // Use local copy if it is a byval arg. 11202 if (Flags.isByVal()) 11203 ArgValue = ByValArgs[j++]; 11204 11205 if (VA.isRegLoc()) { 11206 // Queue up the argument copies and emit them at the end. 11207 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 11208 } else { 11209 assert(VA.isMemLoc() && "Argument not register or memory"); 11210 assert(!IsTailCall && "Tail call not allowed if stack is used " 11211 "for passing parameters"); 11212 11213 // Work out the address of the stack slot. 11214 if (!StackPtr.getNode()) 11215 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 11216 SDValue Address = 11217 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 11218 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 11219 11220 // Emit the store. 11221 MemOpChains.push_back( 11222 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 11223 } 11224 } 11225 11226 // Join the stores, which are independent of one another. 11227 if (!MemOpChains.empty()) 11228 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 11229 11230 SDValue Glue; 11231 11232 // Build a sequence of copy-to-reg nodes, chained and glued together. 11233 for (auto &Reg : RegsToPass) { 11234 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 11235 Glue = Chain.getValue(1); 11236 } 11237 11238 // Validate that none of the argument registers have been marked as 11239 // reserved, if so report an error. Do the same for the return address if this 11240 // is not a tailcall. 11241 validateCCReservedRegs(RegsToPass, MF); 11242 if (!IsTailCall && 11243 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 11244 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11245 MF.getFunction(), 11246 "Return address register required, but has been reserved."}); 11247 11248 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 11249 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 11250 // split it and then direct call can be matched by PseudoCALL. 11251 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 11252 const GlobalValue *GV = S->getGlobal(); 11253 11254 unsigned OpFlags = RISCVII::MO_CALL; 11255 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 11256 OpFlags = RISCVII::MO_PLT; 11257 11258 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 11259 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 11260 unsigned OpFlags = RISCVII::MO_CALL; 11261 11262 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 11263 nullptr)) 11264 OpFlags = RISCVII::MO_PLT; 11265 11266 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 11267 } 11268 11269 // The first call operand is the chain and the second is the target address. 11270 SmallVector<SDValue, 8> Ops; 11271 Ops.push_back(Chain); 11272 Ops.push_back(Callee); 11273 11274 // Add argument registers to the end of the list so that they are 11275 // known live into the call. 11276 for (auto &Reg : RegsToPass) 11277 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 11278 11279 if (!IsTailCall) { 11280 // Add a register mask operand representing the call-preserved registers. 11281 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11282 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 11283 assert(Mask && "Missing call preserved mask for calling convention"); 11284 Ops.push_back(DAG.getRegisterMask(Mask)); 11285 } 11286 11287 // Glue the call to the argument copies, if any. 11288 if (Glue.getNode()) 11289 Ops.push_back(Glue); 11290 11291 // Emit the call. 11292 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 11293 11294 if (IsTailCall) { 11295 MF.getFrameInfo().setHasTailCall(); 11296 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 11297 } 11298 11299 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 11300 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 11301 Glue = Chain.getValue(1); 11302 11303 // Mark the end of the call, which is glued to the call itself. 11304 Chain = DAG.getCALLSEQ_END(Chain, 11305 DAG.getConstant(NumBytes, DL, PtrVT, true), 11306 DAG.getConstant(0, DL, PtrVT, true), 11307 Glue, DL); 11308 Glue = Chain.getValue(1); 11309 11310 // Assign locations to each value returned by this call. 11311 SmallVector<CCValAssign, 16> RVLocs; 11312 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 11313 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 11314 11315 // Copy all of the result registers out of their specified physreg. 11316 for (auto &VA : RVLocs) { 11317 // Copy the value out 11318 SDValue RetValue = 11319 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 11320 // Glue the RetValue to the end of the call sequence 11321 Chain = RetValue.getValue(1); 11322 Glue = RetValue.getValue(2); 11323 11324 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 11325 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 11326 SDValue RetValue2 = 11327 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 11328 Chain = RetValue2.getValue(1); 11329 Glue = RetValue2.getValue(2); 11330 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 11331 RetValue2); 11332 } 11333 11334 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 11335 11336 InVals.push_back(RetValue); 11337 } 11338 11339 return Chain; 11340 } 11341 11342 bool RISCVTargetLowering::CanLowerReturn( 11343 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 11344 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 11345 SmallVector<CCValAssign, 16> RVLocs; 11346 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 11347 11348 Optional<unsigned> FirstMaskArgument; 11349 if (Subtarget.hasVInstructions()) 11350 FirstMaskArgument = preAssignMask(Outs); 11351 11352 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 11353 MVT VT = Outs[i].VT; 11354 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 11355 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 11356 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 11357 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 11358 *this, FirstMaskArgument)) 11359 return false; 11360 } 11361 return true; 11362 } 11363 11364 SDValue 11365 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 11366 bool IsVarArg, 11367 const SmallVectorImpl<ISD::OutputArg> &Outs, 11368 const SmallVectorImpl<SDValue> &OutVals, 11369 const SDLoc &DL, SelectionDAG &DAG) const { 11370 const MachineFunction &MF = DAG.getMachineFunction(); 11371 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 11372 11373 // Stores the assignment of the return value to a location. 11374 SmallVector<CCValAssign, 16> RVLocs; 11375 11376 // Info about the registers and stack slot. 11377 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 11378 *DAG.getContext()); 11379 11380 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 11381 nullptr, CC_RISCV); 11382 11383 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 11384 report_fatal_error("GHC functions return void only"); 11385 11386 SDValue Glue; 11387 SmallVector<SDValue, 4> RetOps(1, Chain); 11388 11389 // Copy the result values into the output registers. 11390 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 11391 SDValue Val = OutVals[i]; 11392 CCValAssign &VA = RVLocs[i]; 11393 assert(VA.isRegLoc() && "Can only return in registers!"); 11394 11395 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 11396 // Handle returning f64 on RV32D with a soft float ABI. 11397 assert(VA.isRegLoc() && "Expected return via registers"); 11398 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 11399 DAG.getVTList(MVT::i32, MVT::i32), Val); 11400 SDValue Lo = SplitF64.getValue(0); 11401 SDValue Hi = SplitF64.getValue(1); 11402 Register RegLo = VA.getLocReg(); 11403 assert(RegLo < RISCV::X31 && "Invalid register pair"); 11404 Register RegHi = RegLo + 1; 11405 11406 if (STI.isRegisterReservedByUser(RegLo) || 11407 STI.isRegisterReservedByUser(RegHi)) 11408 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11409 MF.getFunction(), 11410 "Return value register required, but has been reserved."}); 11411 11412 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 11413 Glue = Chain.getValue(1); 11414 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 11415 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 11416 Glue = Chain.getValue(1); 11417 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 11418 } else { 11419 // Handle a 'normal' return. 11420 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 11421 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 11422 11423 if (STI.isRegisterReservedByUser(VA.getLocReg())) 11424 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11425 MF.getFunction(), 11426 "Return value register required, but has been reserved."}); 11427 11428 // Guarantee that all emitted copies are stuck together. 11429 Glue = Chain.getValue(1); 11430 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 11431 } 11432 } 11433 11434 RetOps[0] = Chain; // Update chain. 11435 11436 // Add the glue node if we have it. 11437 if (Glue.getNode()) { 11438 RetOps.push_back(Glue); 11439 } 11440 11441 unsigned RetOpc = RISCVISD::RET_FLAG; 11442 // Interrupt service routines use different return instructions. 11443 const Function &Func = DAG.getMachineFunction().getFunction(); 11444 if (Func.hasFnAttribute("interrupt")) { 11445 if (!Func.getReturnType()->isVoidTy()) 11446 report_fatal_error( 11447 "Functions with the interrupt attribute must have void return type!"); 11448 11449 MachineFunction &MF = DAG.getMachineFunction(); 11450 StringRef Kind = 11451 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 11452 11453 if (Kind == "user") 11454 RetOpc = RISCVISD::URET_FLAG; 11455 else if (Kind == "supervisor") 11456 RetOpc = RISCVISD::SRET_FLAG; 11457 else 11458 RetOpc = RISCVISD::MRET_FLAG; 11459 } 11460 11461 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 11462 } 11463 11464 void RISCVTargetLowering::validateCCReservedRegs( 11465 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 11466 MachineFunction &MF) const { 11467 const Function &F = MF.getFunction(); 11468 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 11469 11470 if (llvm::any_of(Regs, [&STI](auto Reg) { 11471 return STI.isRegisterReservedByUser(Reg.first); 11472 })) 11473 F.getContext().diagnose(DiagnosticInfoUnsupported{ 11474 F, "Argument register required, but has been reserved."}); 11475 } 11476 11477 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 11478 return CI->isTailCall(); 11479 } 11480 11481 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 11482 #define NODE_NAME_CASE(NODE) \ 11483 case RISCVISD::NODE: \ 11484 return "RISCVISD::" #NODE; 11485 // clang-format off 11486 switch ((RISCVISD::NodeType)Opcode) { 11487 case RISCVISD::FIRST_NUMBER: 11488 break; 11489 NODE_NAME_CASE(RET_FLAG) 11490 NODE_NAME_CASE(URET_FLAG) 11491 NODE_NAME_CASE(SRET_FLAG) 11492 NODE_NAME_CASE(MRET_FLAG) 11493 NODE_NAME_CASE(CALL) 11494 NODE_NAME_CASE(SELECT_CC) 11495 NODE_NAME_CASE(BR_CC) 11496 NODE_NAME_CASE(BuildPairF64) 11497 NODE_NAME_CASE(SplitF64) 11498 NODE_NAME_CASE(TAIL) 11499 NODE_NAME_CASE(ADD_LO) 11500 NODE_NAME_CASE(HI) 11501 NODE_NAME_CASE(LLA) 11502 NODE_NAME_CASE(ADD_TPREL) 11503 NODE_NAME_CASE(LA) 11504 NODE_NAME_CASE(LA_TLS_IE) 11505 NODE_NAME_CASE(LA_TLS_GD) 11506 NODE_NAME_CASE(MULHSU) 11507 NODE_NAME_CASE(SLLW) 11508 NODE_NAME_CASE(SRAW) 11509 NODE_NAME_CASE(SRLW) 11510 NODE_NAME_CASE(DIVW) 11511 NODE_NAME_CASE(DIVUW) 11512 NODE_NAME_CASE(REMUW) 11513 NODE_NAME_CASE(ROLW) 11514 NODE_NAME_CASE(RORW) 11515 NODE_NAME_CASE(CLZW) 11516 NODE_NAME_CASE(CTZW) 11517 NODE_NAME_CASE(FSLW) 11518 NODE_NAME_CASE(FSRW) 11519 NODE_NAME_CASE(FSL) 11520 NODE_NAME_CASE(FSR) 11521 NODE_NAME_CASE(FMV_H_X) 11522 NODE_NAME_CASE(FMV_X_ANYEXTH) 11523 NODE_NAME_CASE(FMV_X_SIGNEXTH) 11524 NODE_NAME_CASE(FMV_W_X_RV64) 11525 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 11526 NODE_NAME_CASE(FCVT_X) 11527 NODE_NAME_CASE(FCVT_XU) 11528 NODE_NAME_CASE(FCVT_W_RV64) 11529 NODE_NAME_CASE(FCVT_WU_RV64) 11530 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 11531 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 11532 NODE_NAME_CASE(READ_CYCLE_WIDE) 11533 NODE_NAME_CASE(GREV) 11534 NODE_NAME_CASE(GREVW) 11535 NODE_NAME_CASE(GORC) 11536 NODE_NAME_CASE(GORCW) 11537 NODE_NAME_CASE(SHFL) 11538 NODE_NAME_CASE(SHFLW) 11539 NODE_NAME_CASE(UNSHFL) 11540 NODE_NAME_CASE(UNSHFLW) 11541 NODE_NAME_CASE(BFP) 11542 NODE_NAME_CASE(BFPW) 11543 NODE_NAME_CASE(BCOMPRESS) 11544 NODE_NAME_CASE(BCOMPRESSW) 11545 NODE_NAME_CASE(BDECOMPRESS) 11546 NODE_NAME_CASE(BDECOMPRESSW) 11547 NODE_NAME_CASE(VMV_V_X_VL) 11548 NODE_NAME_CASE(VFMV_V_F_VL) 11549 NODE_NAME_CASE(VMV_X_S) 11550 NODE_NAME_CASE(VMV_S_X_VL) 11551 NODE_NAME_CASE(VFMV_S_F_VL) 11552 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 11553 NODE_NAME_CASE(READ_VLENB) 11554 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 11555 NODE_NAME_CASE(VSLIDEUP_VL) 11556 NODE_NAME_CASE(VSLIDE1UP_VL) 11557 NODE_NAME_CASE(VSLIDEDOWN_VL) 11558 NODE_NAME_CASE(VSLIDE1DOWN_VL) 11559 NODE_NAME_CASE(VID_VL) 11560 NODE_NAME_CASE(VFNCVT_ROD_VL) 11561 NODE_NAME_CASE(VECREDUCE_ADD_VL) 11562 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 11563 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 11564 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 11565 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 11566 NODE_NAME_CASE(VECREDUCE_AND_VL) 11567 NODE_NAME_CASE(VECREDUCE_OR_VL) 11568 NODE_NAME_CASE(VECREDUCE_XOR_VL) 11569 NODE_NAME_CASE(VECREDUCE_FADD_VL) 11570 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 11571 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 11572 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 11573 NODE_NAME_CASE(ADD_VL) 11574 NODE_NAME_CASE(AND_VL) 11575 NODE_NAME_CASE(MUL_VL) 11576 NODE_NAME_CASE(OR_VL) 11577 NODE_NAME_CASE(SDIV_VL) 11578 NODE_NAME_CASE(SHL_VL) 11579 NODE_NAME_CASE(SREM_VL) 11580 NODE_NAME_CASE(SRA_VL) 11581 NODE_NAME_CASE(SRL_VL) 11582 NODE_NAME_CASE(SUB_VL) 11583 NODE_NAME_CASE(UDIV_VL) 11584 NODE_NAME_CASE(UREM_VL) 11585 NODE_NAME_CASE(XOR_VL) 11586 NODE_NAME_CASE(SADDSAT_VL) 11587 NODE_NAME_CASE(UADDSAT_VL) 11588 NODE_NAME_CASE(SSUBSAT_VL) 11589 NODE_NAME_CASE(USUBSAT_VL) 11590 NODE_NAME_CASE(FADD_VL) 11591 NODE_NAME_CASE(FSUB_VL) 11592 NODE_NAME_CASE(FMUL_VL) 11593 NODE_NAME_CASE(FDIV_VL) 11594 NODE_NAME_CASE(FNEG_VL) 11595 NODE_NAME_CASE(FABS_VL) 11596 NODE_NAME_CASE(FSQRT_VL) 11597 NODE_NAME_CASE(VFMADD_VL) 11598 NODE_NAME_CASE(VFNMADD_VL) 11599 NODE_NAME_CASE(VFMSUB_VL) 11600 NODE_NAME_CASE(VFNMSUB_VL) 11601 NODE_NAME_CASE(FCOPYSIGN_VL) 11602 NODE_NAME_CASE(SMIN_VL) 11603 NODE_NAME_CASE(SMAX_VL) 11604 NODE_NAME_CASE(UMIN_VL) 11605 NODE_NAME_CASE(UMAX_VL) 11606 NODE_NAME_CASE(FMINNUM_VL) 11607 NODE_NAME_CASE(FMAXNUM_VL) 11608 NODE_NAME_CASE(MULHS_VL) 11609 NODE_NAME_CASE(MULHU_VL) 11610 NODE_NAME_CASE(FP_TO_SINT_VL) 11611 NODE_NAME_CASE(FP_TO_UINT_VL) 11612 NODE_NAME_CASE(SINT_TO_FP_VL) 11613 NODE_NAME_CASE(UINT_TO_FP_VL) 11614 NODE_NAME_CASE(FP_EXTEND_VL) 11615 NODE_NAME_CASE(FP_ROUND_VL) 11616 NODE_NAME_CASE(VWMUL_VL) 11617 NODE_NAME_CASE(VWMULU_VL) 11618 NODE_NAME_CASE(VWMULSU_VL) 11619 NODE_NAME_CASE(VWADD_VL) 11620 NODE_NAME_CASE(VWADDU_VL) 11621 NODE_NAME_CASE(VWSUB_VL) 11622 NODE_NAME_CASE(VWSUBU_VL) 11623 NODE_NAME_CASE(VWADD_W_VL) 11624 NODE_NAME_CASE(VWADDU_W_VL) 11625 NODE_NAME_CASE(VWSUB_W_VL) 11626 NODE_NAME_CASE(VWSUBU_W_VL) 11627 NODE_NAME_CASE(SETCC_VL) 11628 NODE_NAME_CASE(VSELECT_VL) 11629 NODE_NAME_CASE(VP_MERGE_VL) 11630 NODE_NAME_CASE(VMAND_VL) 11631 NODE_NAME_CASE(VMOR_VL) 11632 NODE_NAME_CASE(VMXOR_VL) 11633 NODE_NAME_CASE(VMCLR_VL) 11634 NODE_NAME_CASE(VMSET_VL) 11635 NODE_NAME_CASE(VRGATHER_VX_VL) 11636 NODE_NAME_CASE(VRGATHER_VV_VL) 11637 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 11638 NODE_NAME_CASE(VSEXT_VL) 11639 NODE_NAME_CASE(VZEXT_VL) 11640 NODE_NAME_CASE(VCPOP_VL) 11641 NODE_NAME_CASE(READ_CSR) 11642 NODE_NAME_CASE(WRITE_CSR) 11643 NODE_NAME_CASE(SWAP_CSR) 11644 } 11645 // clang-format on 11646 return nullptr; 11647 #undef NODE_NAME_CASE 11648 } 11649 11650 /// getConstraintType - Given a constraint letter, return the type of 11651 /// constraint it is for this target. 11652 RISCVTargetLowering::ConstraintType 11653 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 11654 if (Constraint.size() == 1) { 11655 switch (Constraint[0]) { 11656 default: 11657 break; 11658 case 'f': 11659 return C_RegisterClass; 11660 case 'I': 11661 case 'J': 11662 case 'K': 11663 return C_Immediate; 11664 case 'A': 11665 return C_Memory; 11666 case 'S': // A symbolic address 11667 return C_Other; 11668 } 11669 } else { 11670 if (Constraint == "vr" || Constraint == "vm") 11671 return C_RegisterClass; 11672 } 11673 return TargetLowering::getConstraintType(Constraint); 11674 } 11675 11676 std::pair<unsigned, const TargetRegisterClass *> 11677 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11678 StringRef Constraint, 11679 MVT VT) const { 11680 // First, see if this is a constraint that directly corresponds to a 11681 // RISCV register class. 11682 if (Constraint.size() == 1) { 11683 switch (Constraint[0]) { 11684 case 'r': 11685 // TODO: Support fixed vectors up to XLen for P extension? 11686 if (VT.isVector()) 11687 break; 11688 return std::make_pair(0U, &RISCV::GPRRegClass); 11689 case 'f': 11690 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 11691 return std::make_pair(0U, &RISCV::FPR16RegClass); 11692 if (Subtarget.hasStdExtF() && VT == MVT::f32) 11693 return std::make_pair(0U, &RISCV::FPR32RegClass); 11694 if (Subtarget.hasStdExtD() && VT == MVT::f64) 11695 return std::make_pair(0U, &RISCV::FPR64RegClass); 11696 break; 11697 default: 11698 break; 11699 } 11700 } else if (Constraint == "vr") { 11701 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 11702 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11703 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 11704 return std::make_pair(0U, RC); 11705 } 11706 } else if (Constraint == "vm") { 11707 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 11708 return std::make_pair(0U, &RISCV::VMV0RegClass); 11709 } 11710 11711 // Clang will correctly decode the usage of register name aliases into their 11712 // official names. However, other frontends like `rustc` do not. This allows 11713 // users of these frontends to use the ABI names for registers in LLVM-style 11714 // register constraints. 11715 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 11716 .Case("{zero}", RISCV::X0) 11717 .Case("{ra}", RISCV::X1) 11718 .Case("{sp}", RISCV::X2) 11719 .Case("{gp}", RISCV::X3) 11720 .Case("{tp}", RISCV::X4) 11721 .Case("{t0}", RISCV::X5) 11722 .Case("{t1}", RISCV::X6) 11723 .Case("{t2}", RISCV::X7) 11724 .Cases("{s0}", "{fp}", RISCV::X8) 11725 .Case("{s1}", RISCV::X9) 11726 .Case("{a0}", RISCV::X10) 11727 .Case("{a1}", RISCV::X11) 11728 .Case("{a2}", RISCV::X12) 11729 .Case("{a3}", RISCV::X13) 11730 .Case("{a4}", RISCV::X14) 11731 .Case("{a5}", RISCV::X15) 11732 .Case("{a6}", RISCV::X16) 11733 .Case("{a7}", RISCV::X17) 11734 .Case("{s2}", RISCV::X18) 11735 .Case("{s3}", RISCV::X19) 11736 .Case("{s4}", RISCV::X20) 11737 .Case("{s5}", RISCV::X21) 11738 .Case("{s6}", RISCV::X22) 11739 .Case("{s7}", RISCV::X23) 11740 .Case("{s8}", RISCV::X24) 11741 .Case("{s9}", RISCV::X25) 11742 .Case("{s10}", RISCV::X26) 11743 .Case("{s11}", RISCV::X27) 11744 .Case("{t3}", RISCV::X28) 11745 .Case("{t4}", RISCV::X29) 11746 .Case("{t5}", RISCV::X30) 11747 .Case("{t6}", RISCV::X31) 11748 .Default(RISCV::NoRegister); 11749 if (XRegFromAlias != RISCV::NoRegister) 11750 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 11751 11752 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 11753 // TableGen record rather than the AsmName to choose registers for InlineAsm 11754 // constraints, plus we want to match those names to the widest floating point 11755 // register type available, manually select floating point registers here. 11756 // 11757 // The second case is the ABI name of the register, so that frontends can also 11758 // use the ABI names in register constraint lists. 11759 if (Subtarget.hasStdExtF()) { 11760 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 11761 .Cases("{f0}", "{ft0}", RISCV::F0_F) 11762 .Cases("{f1}", "{ft1}", RISCV::F1_F) 11763 .Cases("{f2}", "{ft2}", RISCV::F2_F) 11764 .Cases("{f3}", "{ft3}", RISCV::F3_F) 11765 .Cases("{f4}", "{ft4}", RISCV::F4_F) 11766 .Cases("{f5}", "{ft5}", RISCV::F5_F) 11767 .Cases("{f6}", "{ft6}", RISCV::F6_F) 11768 .Cases("{f7}", "{ft7}", RISCV::F7_F) 11769 .Cases("{f8}", "{fs0}", RISCV::F8_F) 11770 .Cases("{f9}", "{fs1}", RISCV::F9_F) 11771 .Cases("{f10}", "{fa0}", RISCV::F10_F) 11772 .Cases("{f11}", "{fa1}", RISCV::F11_F) 11773 .Cases("{f12}", "{fa2}", RISCV::F12_F) 11774 .Cases("{f13}", "{fa3}", RISCV::F13_F) 11775 .Cases("{f14}", "{fa4}", RISCV::F14_F) 11776 .Cases("{f15}", "{fa5}", RISCV::F15_F) 11777 .Cases("{f16}", "{fa6}", RISCV::F16_F) 11778 .Cases("{f17}", "{fa7}", RISCV::F17_F) 11779 .Cases("{f18}", "{fs2}", RISCV::F18_F) 11780 .Cases("{f19}", "{fs3}", RISCV::F19_F) 11781 .Cases("{f20}", "{fs4}", RISCV::F20_F) 11782 .Cases("{f21}", "{fs5}", RISCV::F21_F) 11783 .Cases("{f22}", "{fs6}", RISCV::F22_F) 11784 .Cases("{f23}", "{fs7}", RISCV::F23_F) 11785 .Cases("{f24}", "{fs8}", RISCV::F24_F) 11786 .Cases("{f25}", "{fs9}", RISCV::F25_F) 11787 .Cases("{f26}", "{fs10}", RISCV::F26_F) 11788 .Cases("{f27}", "{fs11}", RISCV::F27_F) 11789 .Cases("{f28}", "{ft8}", RISCV::F28_F) 11790 .Cases("{f29}", "{ft9}", RISCV::F29_F) 11791 .Cases("{f30}", "{ft10}", RISCV::F30_F) 11792 .Cases("{f31}", "{ft11}", RISCV::F31_F) 11793 .Default(RISCV::NoRegister); 11794 if (FReg != RISCV::NoRegister) { 11795 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 11796 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 11797 unsigned RegNo = FReg - RISCV::F0_F; 11798 unsigned DReg = RISCV::F0_D + RegNo; 11799 return std::make_pair(DReg, &RISCV::FPR64RegClass); 11800 } 11801 if (VT == MVT::f32 || VT == MVT::Other) 11802 return std::make_pair(FReg, &RISCV::FPR32RegClass); 11803 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 11804 unsigned RegNo = FReg - RISCV::F0_F; 11805 unsigned HReg = RISCV::F0_H + RegNo; 11806 return std::make_pair(HReg, &RISCV::FPR16RegClass); 11807 } 11808 } 11809 } 11810 11811 if (Subtarget.hasVInstructions()) { 11812 Register VReg = StringSwitch<Register>(Constraint.lower()) 11813 .Case("{v0}", RISCV::V0) 11814 .Case("{v1}", RISCV::V1) 11815 .Case("{v2}", RISCV::V2) 11816 .Case("{v3}", RISCV::V3) 11817 .Case("{v4}", RISCV::V4) 11818 .Case("{v5}", RISCV::V5) 11819 .Case("{v6}", RISCV::V6) 11820 .Case("{v7}", RISCV::V7) 11821 .Case("{v8}", RISCV::V8) 11822 .Case("{v9}", RISCV::V9) 11823 .Case("{v10}", RISCV::V10) 11824 .Case("{v11}", RISCV::V11) 11825 .Case("{v12}", RISCV::V12) 11826 .Case("{v13}", RISCV::V13) 11827 .Case("{v14}", RISCV::V14) 11828 .Case("{v15}", RISCV::V15) 11829 .Case("{v16}", RISCV::V16) 11830 .Case("{v17}", RISCV::V17) 11831 .Case("{v18}", RISCV::V18) 11832 .Case("{v19}", RISCV::V19) 11833 .Case("{v20}", RISCV::V20) 11834 .Case("{v21}", RISCV::V21) 11835 .Case("{v22}", RISCV::V22) 11836 .Case("{v23}", RISCV::V23) 11837 .Case("{v24}", RISCV::V24) 11838 .Case("{v25}", RISCV::V25) 11839 .Case("{v26}", RISCV::V26) 11840 .Case("{v27}", RISCV::V27) 11841 .Case("{v28}", RISCV::V28) 11842 .Case("{v29}", RISCV::V29) 11843 .Case("{v30}", RISCV::V30) 11844 .Case("{v31}", RISCV::V31) 11845 .Default(RISCV::NoRegister); 11846 if (VReg != RISCV::NoRegister) { 11847 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11848 return std::make_pair(VReg, &RISCV::VMRegClass); 11849 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11850 return std::make_pair(VReg, &RISCV::VRRegClass); 11851 for (const auto *RC : 11852 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11853 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11854 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11855 return std::make_pair(VReg, RC); 11856 } 11857 } 11858 } 11859 } 11860 11861 std::pair<Register, const TargetRegisterClass *> Res = 11862 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11863 11864 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11865 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11866 // Subtarget into account. 11867 if (Res.second == &RISCV::GPRF16RegClass || 11868 Res.second == &RISCV::GPRF32RegClass || 11869 Res.second == &RISCV::GPRF64RegClass) 11870 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11871 11872 return Res; 11873 } 11874 11875 unsigned 11876 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11877 // Currently only support length 1 constraints. 11878 if (ConstraintCode.size() == 1) { 11879 switch (ConstraintCode[0]) { 11880 case 'A': 11881 return InlineAsm::Constraint_A; 11882 default: 11883 break; 11884 } 11885 } 11886 11887 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11888 } 11889 11890 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11891 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11892 SelectionDAG &DAG) const { 11893 // Currently only support length 1 constraints. 11894 if (Constraint.length() == 1) { 11895 switch (Constraint[0]) { 11896 case 'I': 11897 // Validate & create a 12-bit signed immediate operand. 11898 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11899 uint64_t CVal = C->getSExtValue(); 11900 if (isInt<12>(CVal)) 11901 Ops.push_back( 11902 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11903 } 11904 return; 11905 case 'J': 11906 // Validate & create an integer zero operand. 11907 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11908 if (C->getZExtValue() == 0) 11909 Ops.push_back( 11910 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11911 return; 11912 case 'K': 11913 // Validate & create a 5-bit unsigned immediate operand. 11914 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11915 uint64_t CVal = C->getZExtValue(); 11916 if (isUInt<5>(CVal)) 11917 Ops.push_back( 11918 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11919 } 11920 return; 11921 case 'S': 11922 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11923 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11924 GA->getValueType(0))); 11925 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11926 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11927 BA->getValueType(0))); 11928 } 11929 return; 11930 default: 11931 break; 11932 } 11933 } 11934 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11935 } 11936 11937 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11938 Instruction *Inst, 11939 AtomicOrdering Ord) const { 11940 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 11941 return Builder.CreateFence(Ord); 11942 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 11943 return Builder.CreateFence(AtomicOrdering::Release); 11944 return nullptr; 11945 } 11946 11947 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11948 Instruction *Inst, 11949 AtomicOrdering Ord) const { 11950 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11951 return Builder.CreateFence(AtomicOrdering::Acquire); 11952 return nullptr; 11953 } 11954 11955 TargetLowering::AtomicExpansionKind 11956 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11957 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11958 // point operations can't be used in an lr/sc sequence without breaking the 11959 // forward-progress guarantee. 11960 if (AI->isFloatingPointOperation()) 11961 return AtomicExpansionKind::CmpXChg; 11962 11963 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11964 if (Size == 8 || Size == 16) 11965 return AtomicExpansionKind::MaskedIntrinsic; 11966 return AtomicExpansionKind::None; 11967 } 11968 11969 static Intrinsic::ID 11970 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11971 if (XLen == 32) { 11972 switch (BinOp) { 11973 default: 11974 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11975 case AtomicRMWInst::Xchg: 11976 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11977 case AtomicRMWInst::Add: 11978 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11979 case AtomicRMWInst::Sub: 11980 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11981 case AtomicRMWInst::Nand: 11982 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11983 case AtomicRMWInst::Max: 11984 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11985 case AtomicRMWInst::Min: 11986 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11987 case AtomicRMWInst::UMax: 11988 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11989 case AtomicRMWInst::UMin: 11990 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11991 } 11992 } 11993 11994 if (XLen == 64) { 11995 switch (BinOp) { 11996 default: 11997 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11998 case AtomicRMWInst::Xchg: 11999 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 12000 case AtomicRMWInst::Add: 12001 return Intrinsic::riscv_masked_atomicrmw_add_i64; 12002 case AtomicRMWInst::Sub: 12003 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 12004 case AtomicRMWInst::Nand: 12005 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 12006 case AtomicRMWInst::Max: 12007 return Intrinsic::riscv_masked_atomicrmw_max_i64; 12008 case AtomicRMWInst::Min: 12009 return Intrinsic::riscv_masked_atomicrmw_min_i64; 12010 case AtomicRMWInst::UMax: 12011 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 12012 case AtomicRMWInst::UMin: 12013 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 12014 } 12015 } 12016 12017 llvm_unreachable("Unexpected XLen\n"); 12018 } 12019 12020 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 12021 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 12022 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 12023 unsigned XLen = Subtarget.getXLen(); 12024 Value *Ordering = 12025 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 12026 Type *Tys[] = {AlignedAddr->getType()}; 12027 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 12028 AI->getModule(), 12029 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 12030 12031 if (XLen == 64) { 12032 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 12033 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 12034 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 12035 } 12036 12037 Value *Result; 12038 12039 // Must pass the shift amount needed to sign extend the loaded value prior 12040 // to performing a signed comparison for min/max. ShiftAmt is the number of 12041 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 12042 // is the number of bits to left+right shift the value in order to 12043 // sign-extend. 12044 if (AI->getOperation() == AtomicRMWInst::Min || 12045 AI->getOperation() == AtomicRMWInst::Max) { 12046 const DataLayout &DL = AI->getModule()->getDataLayout(); 12047 unsigned ValWidth = 12048 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 12049 Value *SextShamt = 12050 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 12051 Result = Builder.CreateCall(LrwOpScwLoop, 12052 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 12053 } else { 12054 Result = 12055 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 12056 } 12057 12058 if (XLen == 64) 12059 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 12060 return Result; 12061 } 12062 12063 TargetLowering::AtomicExpansionKind 12064 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 12065 AtomicCmpXchgInst *CI) const { 12066 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 12067 if (Size == 8 || Size == 16) 12068 return AtomicExpansionKind::MaskedIntrinsic; 12069 return AtomicExpansionKind::None; 12070 } 12071 12072 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 12073 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 12074 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 12075 unsigned XLen = Subtarget.getXLen(); 12076 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 12077 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 12078 if (XLen == 64) { 12079 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 12080 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 12081 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 12082 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 12083 } 12084 Type *Tys[] = {AlignedAddr->getType()}; 12085 Function *MaskedCmpXchg = 12086 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 12087 Value *Result = Builder.CreateCall( 12088 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 12089 if (XLen == 64) 12090 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 12091 return Result; 12092 } 12093 12094 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT, 12095 EVT DataVT) const { 12096 return false; 12097 } 12098 12099 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 12100 EVT VT) const { 12101 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 12102 return false; 12103 12104 switch (FPVT.getSimpleVT().SimpleTy) { 12105 case MVT::f16: 12106 return Subtarget.hasStdExtZfh(); 12107 case MVT::f32: 12108 return Subtarget.hasStdExtF(); 12109 case MVT::f64: 12110 return Subtarget.hasStdExtD(); 12111 default: 12112 return false; 12113 } 12114 } 12115 12116 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 12117 // If we are using the small code model, we can reduce size of jump table 12118 // entry to 4 bytes. 12119 if (Subtarget.is64Bit() && !isPositionIndependent() && 12120 getTargetMachine().getCodeModel() == CodeModel::Small) { 12121 return MachineJumpTableInfo::EK_Custom32; 12122 } 12123 return TargetLowering::getJumpTableEncoding(); 12124 } 12125 12126 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 12127 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 12128 unsigned uid, MCContext &Ctx) const { 12129 assert(Subtarget.is64Bit() && !isPositionIndependent() && 12130 getTargetMachine().getCodeModel() == CodeModel::Small); 12131 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 12132 } 12133 12134 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 12135 EVT VT) const { 12136 VT = VT.getScalarType(); 12137 12138 if (!VT.isSimple()) 12139 return false; 12140 12141 switch (VT.getSimpleVT().SimpleTy) { 12142 case MVT::f16: 12143 return Subtarget.hasStdExtZfh(); 12144 case MVT::f32: 12145 return Subtarget.hasStdExtF(); 12146 case MVT::f64: 12147 return Subtarget.hasStdExtD(); 12148 default: 12149 break; 12150 } 12151 12152 return false; 12153 } 12154 12155 Register RISCVTargetLowering::getExceptionPointerRegister( 12156 const Constant *PersonalityFn) const { 12157 return RISCV::X10; 12158 } 12159 12160 Register RISCVTargetLowering::getExceptionSelectorRegister( 12161 const Constant *PersonalityFn) const { 12162 return RISCV::X11; 12163 } 12164 12165 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 12166 // Return false to suppress the unnecessary extensions if the LibCall 12167 // arguments or return value is f32 type for LP64 ABI. 12168 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 12169 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 12170 return false; 12171 12172 return true; 12173 } 12174 12175 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 12176 if (Subtarget.is64Bit() && Type == MVT::i32) 12177 return true; 12178 12179 return IsSigned; 12180 } 12181 12182 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 12183 SDValue C) const { 12184 // Check integral scalar types. 12185 if (VT.isScalarInteger()) { 12186 // Omit the optimization if the sub target has the M extension and the data 12187 // size exceeds XLen. 12188 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 12189 return false; 12190 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 12191 // Break the MUL to a SLLI and an ADD/SUB. 12192 const APInt &Imm = ConstNode->getAPIntValue(); 12193 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 12194 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 12195 return true; 12196 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 12197 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 12198 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 12199 (Imm - 8).isPowerOf2())) 12200 return true; 12201 // Omit the following optimization if the sub target has the M extension 12202 // and the data size >= XLen. 12203 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 12204 return false; 12205 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 12206 // a pair of LUI/ADDI. 12207 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 12208 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 12209 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 12210 (1 - ImmS).isPowerOf2()) 12211 return true; 12212 } 12213 } 12214 } 12215 12216 return false; 12217 } 12218 12219 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 12220 SDValue ConstNode) const { 12221 // Let the DAGCombiner decide for vectors. 12222 EVT VT = AddNode.getValueType(); 12223 if (VT.isVector()) 12224 return true; 12225 12226 // Let the DAGCombiner decide for larger types. 12227 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 12228 return true; 12229 12230 // It is worse if c1 is simm12 while c1*c2 is not. 12231 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 12232 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 12233 const APInt &C1 = C1Node->getAPIntValue(); 12234 const APInt &C2 = C2Node->getAPIntValue(); 12235 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 12236 return false; 12237 12238 // Default to true and let the DAGCombiner decide. 12239 return true; 12240 } 12241 12242 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 12243 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 12244 bool *Fast) const { 12245 if (!VT.isVector()) { 12246 if (Fast) 12247 *Fast = false; 12248 return Subtarget.enableUnalignedScalarMem(); 12249 } 12250 12251 // All vector implementations must support element alignment 12252 EVT ElemVT = VT.getVectorElementType(); 12253 if (Alignment >= ElemVT.getStoreSize()) { 12254 if (Fast) 12255 *Fast = true; 12256 return true; 12257 } 12258 12259 return false; 12260 } 12261 12262 bool RISCVTargetLowering::splitValueIntoRegisterParts( 12263 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 12264 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 12265 bool IsABIRegCopy = CC.has_value(); 12266 EVT ValueVT = Val.getValueType(); 12267 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 12268 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 12269 // and cast to f32. 12270 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 12271 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 12272 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 12273 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 12274 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 12275 Parts[0] = Val; 12276 return true; 12277 } 12278 12279 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 12280 LLVMContext &Context = *DAG.getContext(); 12281 EVT ValueEltVT = ValueVT.getVectorElementType(); 12282 EVT PartEltVT = PartVT.getVectorElementType(); 12283 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 12284 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 12285 if (PartVTBitSize % ValueVTBitSize == 0) { 12286 assert(PartVTBitSize >= ValueVTBitSize); 12287 // If the element types are different, bitcast to the same element type of 12288 // PartVT first. 12289 // Give an example here, we want copy a <vscale x 1 x i8> value to 12290 // <vscale x 4 x i16>. 12291 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 12292 // subvector, then we can bitcast to <vscale x 4 x i16>. 12293 if (ValueEltVT != PartEltVT) { 12294 if (PartVTBitSize > ValueVTBitSize) { 12295 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 12296 assert(Count != 0 && "The number of element should not be zero."); 12297 EVT SameEltTypeVT = 12298 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 12299 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 12300 DAG.getUNDEF(SameEltTypeVT), Val, 12301 DAG.getVectorIdxConstant(0, DL)); 12302 } 12303 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 12304 } else { 12305 Val = 12306 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 12307 Val, DAG.getVectorIdxConstant(0, DL)); 12308 } 12309 Parts[0] = Val; 12310 return true; 12311 } 12312 } 12313 return false; 12314 } 12315 12316 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 12317 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 12318 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 12319 bool IsABIRegCopy = CC.has_value(); 12320 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 12321 SDValue Val = Parts[0]; 12322 12323 // Cast the f32 to i32, truncate to i16, and cast back to f16. 12324 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 12325 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 12326 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 12327 return Val; 12328 } 12329 12330 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 12331 LLVMContext &Context = *DAG.getContext(); 12332 SDValue Val = Parts[0]; 12333 EVT ValueEltVT = ValueVT.getVectorElementType(); 12334 EVT PartEltVT = PartVT.getVectorElementType(); 12335 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 12336 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 12337 if (PartVTBitSize % ValueVTBitSize == 0) { 12338 assert(PartVTBitSize >= ValueVTBitSize); 12339 EVT SameEltTypeVT = ValueVT; 12340 // If the element types are different, convert it to the same element type 12341 // of PartVT. 12342 // Give an example here, we want copy a <vscale x 1 x i8> value from 12343 // <vscale x 4 x i16>. 12344 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 12345 // then we can extract <vscale x 1 x i8>. 12346 if (ValueEltVT != PartEltVT) { 12347 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 12348 assert(Count != 0 && "The number of element should not be zero."); 12349 SameEltTypeVT = 12350 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 12351 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 12352 } 12353 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 12354 DAG.getVectorIdxConstant(0, DL)); 12355 return Val; 12356 } 12357 } 12358 return SDValue(); 12359 } 12360 12361 SDValue 12362 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 12363 SelectionDAG &DAG, 12364 SmallVectorImpl<SDNode *> &Created) const { 12365 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 12366 if (isIntDivCheap(N->getValueType(0), Attr)) 12367 return SDValue(N, 0); // Lower SDIV as SDIV 12368 12369 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 12370 "Unexpected divisor!"); 12371 12372 // Conditional move is needed, so do the transformation iff Zbt is enabled. 12373 if (!Subtarget.hasStdExtZbt()) 12374 return SDValue(); 12375 12376 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 12377 // Besides, more critical path instructions will be generated when dividing 12378 // by 2. So we keep using the original DAGs for these cases. 12379 unsigned Lg2 = Divisor.countTrailingZeros(); 12380 if (Lg2 == 1 || Lg2 >= 12) 12381 return SDValue(); 12382 12383 // fold (sdiv X, pow2) 12384 EVT VT = N->getValueType(0); 12385 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 12386 return SDValue(); 12387 12388 SDLoc DL(N); 12389 SDValue N0 = N->getOperand(0); 12390 SDValue Zero = DAG.getConstant(0, DL, VT); 12391 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 12392 12393 // Add (N0 < 0) ? Pow2 - 1 : 0; 12394 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 12395 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 12396 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 12397 12398 Created.push_back(Cmp.getNode()); 12399 Created.push_back(Add.getNode()); 12400 Created.push_back(Sel.getNode()); 12401 12402 // Divide by pow2. 12403 SDValue SRA = 12404 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 12405 12406 // If we're dividing by a positive value, we're done. Otherwise, we must 12407 // negate the result. 12408 if (Divisor.isNonNegative()) 12409 return SRA; 12410 12411 Created.push_back(SRA.getNode()); 12412 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 12413 } 12414 12415 #define GET_REGISTER_MATCHER 12416 #include "RISCVGenAsmMatcher.inc" 12417 12418 Register 12419 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 12420 const MachineFunction &MF) const { 12421 Register Reg = MatchRegisterAltName(RegName); 12422 if (Reg == RISCV::NoRegister) 12423 Reg = MatchRegisterName(RegName); 12424 if (Reg == RISCV::NoRegister) 12425 report_fatal_error( 12426 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 12427 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 12428 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 12429 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 12430 StringRef(RegName) + "\".")); 12431 return Reg; 12432 } 12433 12434 namespace llvm { 12435 namespace RISCVVIntrinsicsTable { 12436 12437 #define GET_RISCVVIntrinsicsTable_IMPL 12438 #include "RISCVGenSearchableTables.inc" 12439 12440 } // namespace RISCVVIntrinsicsTable 12441 12442 } // namespace llvm 12443