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 531 for (MVT VT : IntVecVTs) { 532 if (!isTypeLegal(VT)) 533 continue; 534 535 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 536 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 537 538 // Vectors implement MULHS/MULHU. 539 setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand); 540 541 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 542 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) 543 setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand); 544 545 setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT, 546 Legal); 547 548 setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand); 549 550 setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP, ISD::BSWAP}, VT, 551 Expand); 552 553 setOperationAction(ISD::BSWAP, VT, Expand); 554 555 // Custom-lower extensions and truncations from/to mask types. 556 setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, 557 VT, Custom); 558 559 // RVV has native int->float & float->int conversions where the 560 // element type sizes are within one power-of-two of each other. Any 561 // wider distances between type sizes have to be lowered as sequences 562 // which progressively narrow the gap in stages. 563 setOperationAction( 564 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 565 VT, Custom); 566 567 setOperationAction( 568 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal); 569 570 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 571 // nodes which truncate by one power of two at a time. 572 setOperationAction(ISD::TRUNCATE, VT, Custom); 573 574 // Custom-lower insert/extract operations to simplify patterns. 575 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 576 Custom); 577 578 // Custom-lower reduction operations to set up the corresponding custom 579 // nodes' operands. 580 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, 581 ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR, 582 ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 583 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}, 584 VT, Custom); 585 586 setOperationAction(IntegerVPOps, VT, Custom); 587 588 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 589 590 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 591 VT, Custom); 592 593 setOperationAction( 594 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 595 Custom); 596 597 setOperationAction( 598 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 599 VT, Custom); 600 601 setOperationAction(ISD::SELECT, VT, Custom); 602 setOperationAction(ISD::SELECT_CC, VT, Expand); 603 604 setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom); 605 606 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 607 setTruncStoreAction(VT, OtherVT, Expand); 608 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 609 VT, Expand); 610 } 611 612 // Splice 613 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 614 615 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 616 // type that can represent the value exactly. 617 if (VT.getVectorElementType() != MVT::i64) { 618 MVT FloatEltVT = 619 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 620 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 621 if (isTypeLegal(FloatVT)) { 622 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 623 Custom); 624 } 625 } 626 } 627 628 // Expand various CCs to best match the RVV ISA, which natively supports UNE 629 // but no other unordered comparisons, and supports all ordered comparisons 630 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 631 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 632 // and we pattern-match those back to the "original", swapping operands once 633 // more. This way we catch both operations and both "vf" and "fv" forms with 634 // fewer patterns. 635 static const ISD::CondCode VFPCCToExpand[] = { 636 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 637 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 638 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 639 }; 640 641 // Sets common operation actions on RVV floating-point vector types. 642 const auto SetCommonVFPActions = [&](MVT VT) { 643 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 644 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 645 // sizes are within one power-of-two of each other. Therefore conversions 646 // between vXf16 and vXf64 must be lowered as sequences which convert via 647 // vXf32. 648 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 649 // Custom-lower insert/extract operations to simplify patterns. 650 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 651 Custom); 652 // Expand various condition codes (explained above). 653 setCondCodeAction(VFPCCToExpand, VT, Expand); 654 655 setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal); 656 657 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 658 VT, Custom); 659 660 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 661 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 662 VT, Custom); 663 664 // Expand FP operations that need libcalls. 665 setOperationAction(ISD::FREM, VT, Expand); 666 setOperationAction(ISD::FPOW, VT, Expand); 667 setOperationAction(ISD::FCOS, VT, Expand); 668 setOperationAction(ISD::FSIN, VT, Expand); 669 setOperationAction(ISD::FSINCOS, VT, Expand); 670 setOperationAction(ISD::FEXP, VT, Expand); 671 setOperationAction(ISD::FEXP2, VT, Expand); 672 setOperationAction(ISD::FLOG, VT, Expand); 673 setOperationAction(ISD::FLOG2, VT, Expand); 674 setOperationAction(ISD::FLOG10, VT, Expand); 675 setOperationAction(ISD::FRINT, VT, Expand); 676 setOperationAction(ISD::FNEARBYINT, VT, Expand); 677 678 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 679 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 680 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 681 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 682 683 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 684 685 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 686 687 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 688 VT, Custom); 689 690 setOperationAction( 691 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 692 Custom); 693 694 setOperationAction(ISD::SELECT, VT, Custom); 695 setOperationAction(ISD::SELECT_CC, VT, Expand); 696 697 setOperationAction( 698 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 699 VT, Custom); 700 701 setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom); 702 703 setOperationAction(FloatingPointVPOps, VT, Custom); 704 }; 705 706 // Sets common extload/truncstore actions on RVV floating-point vector 707 // types. 708 const auto SetCommonVFPExtLoadTruncStoreActions = 709 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 710 for (auto SmallVT : SmallerVTs) { 711 setTruncStoreAction(VT, SmallVT, Expand); 712 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 713 } 714 }; 715 716 if (Subtarget.hasVInstructionsF16()) { 717 for (MVT VT : F16VecVTs) { 718 if (!isTypeLegal(VT)) 719 continue; 720 SetCommonVFPActions(VT); 721 } 722 } 723 724 if (Subtarget.hasVInstructionsF32()) { 725 for (MVT VT : F32VecVTs) { 726 if (!isTypeLegal(VT)) 727 continue; 728 SetCommonVFPActions(VT); 729 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 730 } 731 } 732 733 if (Subtarget.hasVInstructionsF64()) { 734 for (MVT VT : F64VecVTs) { 735 if (!isTypeLegal(VT)) 736 continue; 737 SetCommonVFPActions(VT); 738 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 739 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 740 } 741 } 742 743 if (Subtarget.useRVVForFixedLengthVectors()) { 744 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 745 if (!useRVVForFixedLengthVectorVT(VT)) 746 continue; 747 748 // By default everything must be expanded. 749 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 750 setOperationAction(Op, VT, Expand); 751 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 752 setTruncStoreAction(VT, OtherVT, Expand); 753 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, 754 OtherVT, VT, Expand); 755 } 756 757 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 758 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 759 Custom); 760 761 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT, 762 Custom); 763 764 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 765 VT, Custom); 766 767 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 768 769 setOperationAction(ISD::SETCC, VT, Custom); 770 771 setOperationAction(ISD::SELECT, VT, Custom); 772 773 setOperationAction(ISD::TRUNCATE, VT, Custom); 774 775 setOperationAction(ISD::BITCAST, VT, Custom); 776 777 setOperationAction( 778 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 779 Custom); 780 781 setOperationAction( 782 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 783 Custom); 784 785 setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, 786 ISD::FP_TO_UINT}, 787 VT, Custom); 788 789 // Operations below are different for between masks and other vectors. 790 if (VT.getVectorElementType() == MVT::i1) { 791 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND, 792 ISD::OR, ISD::XOR}, 793 VT, Custom); 794 795 setOperationAction( 796 {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_TRUNCATE}, 797 VT, Custom); 798 continue; 799 } 800 801 // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to 802 // it before type legalization for i64 vectors on RV32. It will then be 803 // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle. 804 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 805 // improvements first. 806 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 807 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 808 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 809 } 810 811 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 812 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 813 814 setOperationAction( 815 {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom); 816 817 setOperationAction( 818 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 819 Custom); 820 821 setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR, 822 ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV, 823 ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL}, 824 VT, Custom); 825 826 setOperationAction( 827 {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom); 828 829 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 830 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) 831 setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom); 832 833 setOperationAction( 834 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, 835 Custom); 836 837 setOperationAction(ISD::VSELECT, VT, Custom); 838 setOperationAction(ISD::SELECT_CC, VT, Expand); 839 840 setOperationAction( 841 {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom); 842 843 // Custom-lower reduction operations to set up the corresponding custom 844 // nodes' operands. 845 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX, 846 ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX, 847 ISD::VECREDUCE_UMIN}, 848 VT, Custom); 849 850 setOperationAction(IntegerVPOps, VT, Custom); 851 852 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 853 // type that can represent the value exactly. 854 if (VT.getVectorElementType() != MVT::i64) { 855 MVT FloatEltVT = 856 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 857 EVT FloatVT = 858 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 859 if (isTypeLegal(FloatVT)) 860 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 861 Custom); 862 } 863 } 864 865 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 866 if (!useRVVForFixedLengthVectorVT(VT)) 867 continue; 868 869 // By default everything must be expanded. 870 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 871 setOperationAction(Op, VT, Expand); 872 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 873 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 874 setTruncStoreAction(VT, OtherVT, Expand); 875 } 876 877 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 878 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 879 Custom); 880 881 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS, 882 ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT, 883 ISD::EXTRACT_VECTOR_ELT}, 884 VT, Custom); 885 886 setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE, 887 ISD::MGATHER, ISD::MSCATTER}, 888 VT, Custom); 889 890 setOperationAction( 891 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 892 Custom); 893 894 setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV, 895 ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT, 896 ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM}, 897 VT, Custom); 898 899 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 900 901 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 902 VT, Custom); 903 904 for (auto CC : VFPCCToExpand) 905 setCondCodeAction(CC, VT, Expand); 906 907 setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom); 908 setOperationAction(ISD::SELECT_CC, VT, Expand); 909 910 setOperationAction(ISD::BITCAST, VT, Custom); 911 912 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 913 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 914 VT, Custom); 915 916 setOperationAction(FloatingPointVPOps, VT, Custom); 917 } 918 919 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 920 setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64}, 921 Custom); 922 if (Subtarget.hasStdExtZfh()) 923 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 924 if (Subtarget.hasStdExtF()) 925 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 926 if (Subtarget.hasStdExtD()) 927 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 928 } 929 } 930 931 // Function alignments. 932 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 933 setMinFunctionAlignment(FunctionAlignment); 934 setPrefFunctionAlignment(FunctionAlignment); 935 936 setMinimumJumpTableEntries(5); 937 938 // Jumps are expensive, compared to logic 939 setJumpIsExpensive(); 940 941 setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND, 942 ISD::OR, ISD::XOR}); 943 if (Subtarget.is64Bit()) 944 setTargetDAGCombine(ISD::SRA); 945 946 if (Subtarget.hasStdExtF()) 947 setTargetDAGCombine({ISD::FADD, ISD::FMAXNUM, ISD::FMINNUM}); 948 949 if (Subtarget.hasStdExtZbp()) 950 setTargetDAGCombine({ISD::ROTL, ISD::ROTR}); 951 952 if (Subtarget.hasStdExtZbb()) 953 setTargetDAGCombine({ISD::UMAX, ISD::UMIN, ISD::SMAX, ISD::SMIN}); 954 955 if (Subtarget.hasStdExtZbkb()) 956 setTargetDAGCombine(ISD::BITREVERSE); 957 if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb()) 958 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 959 if (Subtarget.hasStdExtF()) 960 setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT, 961 ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}); 962 if (Subtarget.hasVInstructions()) 963 setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER, 964 ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL, 965 ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR}); 966 if (Subtarget.useRVVForFixedLengthVectors()) 967 setTargetDAGCombine(ISD::BITCAST); 968 969 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 970 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 971 } 972 973 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 974 LLVMContext &Context, 975 EVT VT) const { 976 if (!VT.isVector()) 977 return getPointerTy(DL); 978 if (Subtarget.hasVInstructions() && 979 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 980 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 981 return VT.changeVectorElementTypeToInteger(); 982 } 983 984 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 985 return Subtarget.getXLenVT(); 986 } 987 988 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 989 const CallInst &I, 990 MachineFunction &MF, 991 unsigned Intrinsic) const { 992 auto &DL = I.getModule()->getDataLayout(); 993 switch (Intrinsic) { 994 default: 995 return false; 996 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 997 case Intrinsic::riscv_masked_atomicrmw_add_i32: 998 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 999 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1000 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1001 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1002 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1003 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1004 case Intrinsic::riscv_masked_cmpxchg_i32: 1005 Info.opc = ISD::INTRINSIC_W_CHAIN; 1006 Info.memVT = MVT::i32; 1007 Info.ptrVal = I.getArgOperand(0); 1008 Info.offset = 0; 1009 Info.align = Align(4); 1010 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1011 MachineMemOperand::MOVolatile; 1012 return true; 1013 case Intrinsic::riscv_masked_strided_load: 1014 Info.opc = ISD::INTRINSIC_W_CHAIN; 1015 Info.ptrVal = I.getArgOperand(1); 1016 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1017 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1018 Info.size = MemoryLocation::UnknownSize; 1019 Info.flags |= MachineMemOperand::MOLoad; 1020 return true; 1021 case Intrinsic::riscv_masked_strided_store: 1022 Info.opc = ISD::INTRINSIC_VOID; 1023 Info.ptrVal = I.getArgOperand(1); 1024 Info.memVT = 1025 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1026 Info.align = Align( 1027 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1028 8); 1029 Info.size = MemoryLocation::UnknownSize; 1030 Info.flags |= MachineMemOperand::MOStore; 1031 return true; 1032 case Intrinsic::riscv_seg2_load: 1033 case Intrinsic::riscv_seg3_load: 1034 case Intrinsic::riscv_seg4_load: 1035 case Intrinsic::riscv_seg5_load: 1036 case Intrinsic::riscv_seg6_load: 1037 case Intrinsic::riscv_seg7_load: 1038 case Intrinsic::riscv_seg8_load: 1039 Info.opc = ISD::INTRINSIC_W_CHAIN; 1040 Info.ptrVal = I.getArgOperand(0); 1041 Info.memVT = 1042 getValueType(DL, I.getType()->getStructElementType(0)->getScalarType()); 1043 Info.align = 1044 Align(DL.getTypeSizeInBits( 1045 I.getType()->getStructElementType(0)->getScalarType()) / 1046 8); 1047 Info.size = MemoryLocation::UnknownSize; 1048 Info.flags |= MachineMemOperand::MOLoad; 1049 return true; 1050 } 1051 } 1052 1053 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1054 const AddrMode &AM, Type *Ty, 1055 unsigned AS, 1056 Instruction *I) const { 1057 // No global is ever allowed as a base. 1058 if (AM.BaseGV) 1059 return false; 1060 1061 // RVV instructions only support register addressing. 1062 if (Subtarget.hasVInstructions() && isa<VectorType>(Ty)) 1063 return AM.HasBaseReg && AM.Scale == 0 && !AM.BaseOffs; 1064 1065 // Require a 12-bit signed offset. 1066 if (!isInt<12>(AM.BaseOffs)) 1067 return false; 1068 1069 switch (AM.Scale) { 1070 case 0: // "r+i" or just "i", depending on HasBaseReg. 1071 break; 1072 case 1: 1073 if (!AM.HasBaseReg) // allow "r+i". 1074 break; 1075 return false; // disallow "r+r" or "r+r+i". 1076 default: 1077 return false; 1078 } 1079 1080 return true; 1081 } 1082 1083 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1084 return isInt<12>(Imm); 1085 } 1086 1087 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1088 return isInt<12>(Imm); 1089 } 1090 1091 // On RV32, 64-bit integers are split into their high and low parts and held 1092 // in two different registers, so the trunc is free since the low register can 1093 // just be used. 1094 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1095 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1096 return false; 1097 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1098 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1099 return (SrcBits == 64 && DestBits == 32); 1100 } 1101 1102 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1103 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1104 !SrcVT.isInteger() || !DstVT.isInteger()) 1105 return false; 1106 unsigned SrcBits = SrcVT.getSizeInBits(); 1107 unsigned DestBits = DstVT.getSizeInBits(); 1108 return (SrcBits == 64 && DestBits == 32); 1109 } 1110 1111 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1112 // Zexts are free if they can be combined with a load. 1113 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1114 // poorly with type legalization of compares preferring sext. 1115 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1116 EVT MemVT = LD->getMemoryVT(); 1117 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1118 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1119 LD->getExtensionType() == ISD::ZEXTLOAD)) 1120 return true; 1121 } 1122 1123 return TargetLowering::isZExtFree(Val, VT2); 1124 } 1125 1126 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1127 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1128 } 1129 1130 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const { 1131 return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32); 1132 } 1133 1134 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1135 return Subtarget.hasStdExtZbb(); 1136 } 1137 1138 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1139 return Subtarget.hasStdExtZbb(); 1140 } 1141 1142 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1143 EVT VT = Y.getValueType(); 1144 1145 // FIXME: Support vectors once we have tests. 1146 if (VT.isVector()) 1147 return false; 1148 1149 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1150 Subtarget.hasStdExtZbkb()) && 1151 !isa<ConstantSDNode>(Y); 1152 } 1153 1154 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const { 1155 // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position. 1156 auto *C = dyn_cast<ConstantSDNode>(Y); 1157 return C && C->getAPIntValue().ule(10); 1158 } 1159 1160 bool RISCVTargetLowering:: 1161 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 1162 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y, 1163 unsigned OldShiftOpcode, unsigned NewShiftOpcode, 1164 SelectionDAG &DAG) const { 1165 // One interesting pattern that we'd want to form is 'bit extract': 1166 // ((1 >> Y) & 1) ==/!= 0 1167 // But we also need to be careful not to try to reverse that fold. 1168 1169 // Is this '((1 >> Y) & 1)'? 1170 if (XC && OldShiftOpcode == ISD::SRL && XC->isOne()) 1171 return false; // Keep the 'bit extract' pattern. 1172 1173 // Will this be '((1 >> Y) & 1)' after the transform? 1174 if (NewShiftOpcode == ISD::SRL && CC->isOne()) 1175 return true; // Do form the 'bit extract' pattern. 1176 1177 // If 'X' is a constant, and we transform, then we will immediately 1178 // try to undo the fold, thus causing endless combine loop. 1179 // So only do the transform if X is not a constant. This matches the default 1180 // implementation of this function. 1181 return !XC; 1182 } 1183 1184 /// Check if sinking \p I's operands to I's basic block is profitable, because 1185 /// the operands can be folded into a target instruction, e.g. 1186 /// splats of scalars can fold into vector instructions. 1187 bool RISCVTargetLowering::shouldSinkOperands( 1188 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1189 using namespace llvm::PatternMatch; 1190 1191 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1192 return false; 1193 1194 auto IsSinker = [&](Instruction *I, int Operand) { 1195 switch (I->getOpcode()) { 1196 case Instruction::Add: 1197 case Instruction::Sub: 1198 case Instruction::Mul: 1199 case Instruction::And: 1200 case Instruction::Or: 1201 case Instruction::Xor: 1202 case Instruction::FAdd: 1203 case Instruction::FSub: 1204 case Instruction::FMul: 1205 case Instruction::FDiv: 1206 case Instruction::ICmp: 1207 case Instruction::FCmp: 1208 return true; 1209 case Instruction::Shl: 1210 case Instruction::LShr: 1211 case Instruction::AShr: 1212 case Instruction::UDiv: 1213 case Instruction::SDiv: 1214 case Instruction::URem: 1215 case Instruction::SRem: 1216 return Operand == 1; 1217 case Instruction::Call: 1218 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1219 switch (II->getIntrinsicID()) { 1220 case Intrinsic::fma: 1221 case Intrinsic::vp_fma: 1222 return Operand == 0 || Operand == 1; 1223 // FIXME: Our patterns can only match vx/vf instructions when the splat 1224 // it on the RHS, because TableGen doesn't recognize our VP operations 1225 // as commutative. 1226 case Intrinsic::vp_add: 1227 case Intrinsic::vp_mul: 1228 case Intrinsic::vp_and: 1229 case Intrinsic::vp_or: 1230 case Intrinsic::vp_xor: 1231 case Intrinsic::vp_fadd: 1232 case Intrinsic::vp_fmul: 1233 case Intrinsic::vp_shl: 1234 case Intrinsic::vp_lshr: 1235 case Intrinsic::vp_ashr: 1236 case Intrinsic::vp_udiv: 1237 case Intrinsic::vp_sdiv: 1238 case Intrinsic::vp_urem: 1239 case Intrinsic::vp_srem: 1240 return Operand == 1; 1241 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1242 // explicit patterns for both LHS and RHS (as 'vr' versions). 1243 case Intrinsic::vp_sub: 1244 case Intrinsic::vp_fsub: 1245 case Intrinsic::vp_fdiv: 1246 return Operand == 0 || Operand == 1; 1247 default: 1248 return false; 1249 } 1250 } 1251 return false; 1252 default: 1253 return false; 1254 } 1255 }; 1256 1257 for (auto OpIdx : enumerate(I->operands())) { 1258 if (!IsSinker(I, OpIdx.index())) 1259 continue; 1260 1261 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1262 // Make sure we are not already sinking this operand 1263 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1264 continue; 1265 1266 // We are looking for a splat that can be sunk. 1267 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1268 m_Undef(), m_ZeroMask()))) 1269 continue; 1270 1271 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1272 // and vector registers 1273 for (Use &U : Op->uses()) { 1274 Instruction *Insn = cast<Instruction>(U.getUser()); 1275 if (!IsSinker(Insn, U.getOperandNo())) 1276 return false; 1277 } 1278 1279 Ops.push_back(&Op->getOperandUse(0)); 1280 Ops.push_back(&OpIdx.value()); 1281 } 1282 return true; 1283 } 1284 1285 bool RISCVTargetLowering::isOffsetFoldingLegal( 1286 const GlobalAddressSDNode *GA) const { 1287 // In order to maximise the opportunity for common subexpression elimination, 1288 // keep a separate ADD node for the global address offset instead of folding 1289 // it in the global address node. Later peephole optimisations may choose to 1290 // fold it back in when profitable. 1291 return false; 1292 } 1293 1294 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1295 bool ForCodeSize) const { 1296 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1297 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1298 return false; 1299 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1300 return false; 1301 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1302 return false; 1303 return Imm.isZero(); 1304 } 1305 1306 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1307 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1308 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1309 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1310 } 1311 1312 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1313 CallingConv::ID CC, 1314 EVT VT) const { 1315 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1316 // We might still end up using a GPR but that will be decided based on ABI. 1317 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1318 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1319 return MVT::f32; 1320 1321 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1322 } 1323 1324 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1325 CallingConv::ID CC, 1326 EVT VT) const { 1327 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1328 // We might still end up using a GPR but that will be decided based on ABI. 1329 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1330 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1331 return 1; 1332 1333 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1334 } 1335 1336 // Changes the condition code and swaps operands if necessary, so the SetCC 1337 // operation matches one of the comparisons supported directly by branches 1338 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1339 // with 1/-1. 1340 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1341 ISD::CondCode &CC, SelectionDAG &DAG) { 1342 // Convert X > -1 to X >= 0. 1343 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1344 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1345 CC = ISD::SETGE; 1346 return; 1347 } 1348 // Convert X < 1 to 0 >= X. 1349 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1350 RHS = LHS; 1351 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1352 CC = ISD::SETGE; 1353 return; 1354 } 1355 1356 switch (CC) { 1357 default: 1358 break; 1359 case ISD::SETGT: 1360 case ISD::SETLE: 1361 case ISD::SETUGT: 1362 case ISD::SETULE: 1363 CC = ISD::getSetCCSwappedOperands(CC); 1364 std::swap(LHS, RHS); 1365 break; 1366 } 1367 } 1368 1369 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1370 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1371 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1372 if (VT.getVectorElementType() == MVT::i1) 1373 KnownSize *= 8; 1374 1375 switch (KnownSize) { 1376 default: 1377 llvm_unreachable("Invalid LMUL."); 1378 case 8: 1379 return RISCVII::VLMUL::LMUL_F8; 1380 case 16: 1381 return RISCVII::VLMUL::LMUL_F4; 1382 case 32: 1383 return RISCVII::VLMUL::LMUL_F2; 1384 case 64: 1385 return RISCVII::VLMUL::LMUL_1; 1386 case 128: 1387 return RISCVII::VLMUL::LMUL_2; 1388 case 256: 1389 return RISCVII::VLMUL::LMUL_4; 1390 case 512: 1391 return RISCVII::VLMUL::LMUL_8; 1392 } 1393 } 1394 1395 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1396 switch (LMul) { 1397 default: 1398 llvm_unreachable("Invalid LMUL."); 1399 case RISCVII::VLMUL::LMUL_F8: 1400 case RISCVII::VLMUL::LMUL_F4: 1401 case RISCVII::VLMUL::LMUL_F2: 1402 case RISCVII::VLMUL::LMUL_1: 1403 return RISCV::VRRegClassID; 1404 case RISCVII::VLMUL::LMUL_2: 1405 return RISCV::VRM2RegClassID; 1406 case RISCVII::VLMUL::LMUL_4: 1407 return RISCV::VRM4RegClassID; 1408 case RISCVII::VLMUL::LMUL_8: 1409 return RISCV::VRM8RegClassID; 1410 } 1411 } 1412 1413 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1414 RISCVII::VLMUL LMUL = getLMUL(VT); 1415 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1416 LMUL == RISCVII::VLMUL::LMUL_F4 || 1417 LMUL == RISCVII::VLMUL::LMUL_F2 || 1418 LMUL == RISCVII::VLMUL::LMUL_1) { 1419 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1420 "Unexpected subreg numbering"); 1421 return RISCV::sub_vrm1_0 + Index; 1422 } 1423 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1424 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1425 "Unexpected subreg numbering"); 1426 return RISCV::sub_vrm2_0 + Index; 1427 } 1428 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1429 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1430 "Unexpected subreg numbering"); 1431 return RISCV::sub_vrm4_0 + Index; 1432 } 1433 llvm_unreachable("Invalid vector type."); 1434 } 1435 1436 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1437 if (VT.getVectorElementType() == MVT::i1) 1438 return RISCV::VRRegClassID; 1439 return getRegClassIDForLMUL(getLMUL(VT)); 1440 } 1441 1442 // Attempt to decompose a subvector insert/extract between VecVT and 1443 // SubVecVT via subregister indices. Returns the subregister index that 1444 // can perform the subvector insert/extract with the given element index, as 1445 // well as the index corresponding to any leftover subvectors that must be 1446 // further inserted/extracted within the register class for SubVecVT. 1447 std::pair<unsigned, unsigned> 1448 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1449 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1450 const RISCVRegisterInfo *TRI) { 1451 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1452 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1453 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1454 "Register classes not ordered"); 1455 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1456 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1457 // Try to compose a subregister index that takes us from the incoming 1458 // LMUL>1 register class down to the outgoing one. At each step we half 1459 // the LMUL: 1460 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1461 // Note that this is not guaranteed to find a subregister index, such as 1462 // when we are extracting from one VR type to another. 1463 unsigned SubRegIdx = RISCV::NoSubRegister; 1464 for (const unsigned RCID : 1465 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1466 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1467 VecVT = VecVT.getHalfNumVectorElementsVT(); 1468 bool IsHi = 1469 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1470 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1471 getSubregIndexByMVT(VecVT, IsHi)); 1472 if (IsHi) 1473 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1474 } 1475 return {SubRegIdx, InsertExtractIdx}; 1476 } 1477 1478 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1479 // stores for those types. 1480 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1481 return !Subtarget.useRVVForFixedLengthVectors() || 1482 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1483 } 1484 1485 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1486 if (ScalarTy->isPointerTy()) 1487 return true; 1488 1489 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1490 ScalarTy->isIntegerTy(32)) 1491 return true; 1492 1493 if (ScalarTy->isIntegerTy(64)) 1494 return Subtarget.hasVInstructionsI64(); 1495 1496 if (ScalarTy->isHalfTy()) 1497 return Subtarget.hasVInstructionsF16(); 1498 if (ScalarTy->isFloatTy()) 1499 return Subtarget.hasVInstructionsF32(); 1500 if (ScalarTy->isDoubleTy()) 1501 return Subtarget.hasVInstructionsF64(); 1502 1503 return false; 1504 } 1505 1506 static SDValue getVLOperand(SDValue Op) { 1507 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1508 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1509 "Unexpected opcode"); 1510 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1511 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1512 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1513 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1514 if (!II) 1515 return SDValue(); 1516 return Op.getOperand(II->VLOperand + 1 + HasChain); 1517 } 1518 1519 static bool useRVVForFixedLengthVectorVT(MVT VT, 1520 const RISCVSubtarget &Subtarget) { 1521 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1522 if (!Subtarget.useRVVForFixedLengthVectors()) 1523 return false; 1524 1525 // We only support a set of vector types with a consistent maximum fixed size 1526 // across all supported vector element types to avoid legalization issues. 1527 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1528 // fixed-length vector type we support is 1024 bytes. 1529 if (VT.getFixedSizeInBits() > 1024 * 8) 1530 return false; 1531 1532 unsigned MinVLen = Subtarget.getRealMinVLen(); 1533 1534 MVT EltVT = VT.getVectorElementType(); 1535 1536 // Don't use RVV for vectors we cannot scalarize if required. 1537 switch (EltVT.SimpleTy) { 1538 // i1 is supported but has different rules. 1539 default: 1540 return false; 1541 case MVT::i1: 1542 // Masks can only use a single register. 1543 if (VT.getVectorNumElements() > MinVLen) 1544 return false; 1545 MinVLen /= 8; 1546 break; 1547 case MVT::i8: 1548 case MVT::i16: 1549 case MVT::i32: 1550 break; 1551 case MVT::i64: 1552 if (!Subtarget.hasVInstructionsI64()) 1553 return false; 1554 break; 1555 case MVT::f16: 1556 if (!Subtarget.hasVInstructionsF16()) 1557 return false; 1558 break; 1559 case MVT::f32: 1560 if (!Subtarget.hasVInstructionsF32()) 1561 return false; 1562 break; 1563 case MVT::f64: 1564 if (!Subtarget.hasVInstructionsF64()) 1565 return false; 1566 break; 1567 } 1568 1569 // Reject elements larger than ELEN. 1570 if (EltVT.getSizeInBits() > Subtarget.getELEN()) 1571 return false; 1572 1573 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1574 // Don't use RVV for types that don't fit. 1575 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1576 return false; 1577 1578 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1579 // the base fixed length RVV support in place. 1580 if (!VT.isPow2VectorType()) 1581 return false; 1582 1583 return true; 1584 } 1585 1586 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1587 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1588 } 1589 1590 // Return the largest legal scalable vector type that matches VT's element type. 1591 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1592 const RISCVSubtarget &Subtarget) { 1593 // This may be called before legal types are setup. 1594 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1595 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1596 "Expected legal fixed length vector!"); 1597 1598 unsigned MinVLen = Subtarget.getRealMinVLen(); 1599 unsigned MaxELen = Subtarget.getELEN(); 1600 1601 MVT EltVT = VT.getVectorElementType(); 1602 switch (EltVT.SimpleTy) { 1603 default: 1604 llvm_unreachable("unexpected element type for RVV container"); 1605 case MVT::i1: 1606 case MVT::i8: 1607 case MVT::i16: 1608 case MVT::i32: 1609 case MVT::i64: 1610 case MVT::f16: 1611 case MVT::f32: 1612 case MVT::f64: { 1613 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1614 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1615 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1616 unsigned NumElts = 1617 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1618 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1619 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1620 return MVT::getScalableVectorVT(EltVT, NumElts); 1621 } 1622 } 1623 } 1624 1625 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1626 const RISCVSubtarget &Subtarget) { 1627 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1628 Subtarget); 1629 } 1630 1631 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1632 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1633 } 1634 1635 // Grow V to consume an entire RVV register. 1636 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1637 const RISCVSubtarget &Subtarget) { 1638 assert(VT.isScalableVector() && 1639 "Expected to convert into a scalable vector!"); 1640 assert(V.getValueType().isFixedLengthVector() && 1641 "Expected a fixed length vector operand!"); 1642 SDLoc DL(V); 1643 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1644 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1645 } 1646 1647 // Shrink V so it's just big enough to maintain a VT's worth of data. 1648 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1649 const RISCVSubtarget &Subtarget) { 1650 assert(VT.isFixedLengthVector() && 1651 "Expected to convert into a fixed length vector!"); 1652 assert(V.getValueType().isScalableVector() && 1653 "Expected a scalable vector operand!"); 1654 SDLoc DL(V); 1655 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1656 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1657 } 1658 1659 /// Return the type of the mask type suitable for masking the provided 1660 /// vector type. This is simply an i1 element type vector of the same 1661 /// (possibly scalable) length. 1662 static MVT getMaskTypeFor(EVT VecVT) { 1663 assert(VecVT.isVector()); 1664 ElementCount EC = VecVT.getVectorElementCount(); 1665 return MVT::getVectorVT(MVT::i1, EC); 1666 } 1667 1668 /// Creates an all ones mask suitable for masking a vector of type VecTy with 1669 /// vector length VL. . 1670 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL, 1671 SelectionDAG &DAG) { 1672 MVT MaskVT = getMaskTypeFor(VecVT); 1673 return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1674 } 1675 1676 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1677 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1678 // the vector type that it is contained in. 1679 static std::pair<SDValue, SDValue> 1680 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1681 const RISCVSubtarget &Subtarget) { 1682 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1683 MVT XLenVT = Subtarget.getXLenVT(); 1684 SDValue VL = VecVT.isFixedLengthVector() 1685 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1686 : DAG.getRegister(RISCV::X0, XLenVT); 1687 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 1688 return {Mask, VL}; 1689 } 1690 1691 // As above but assuming the given type is a scalable vector type. 1692 static std::pair<SDValue, SDValue> 1693 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1694 const RISCVSubtarget &Subtarget) { 1695 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1696 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1697 } 1698 1699 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1700 // of either is (currently) supported. This can get us into an infinite loop 1701 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1702 // as a ..., etc. 1703 // Until either (or both) of these can reliably lower any node, reporting that 1704 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1705 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1706 // which is not desirable. 1707 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1708 EVT VT, unsigned DefinedValues) const { 1709 return false; 1710 } 1711 1712 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1713 const RISCVSubtarget &Subtarget) { 1714 // RISCV FP-to-int conversions saturate to the destination register size, but 1715 // don't produce 0 for nan. We can use a conversion instruction and fix the 1716 // nan case with a compare and a select. 1717 SDValue Src = Op.getOperand(0); 1718 1719 EVT DstVT = Op.getValueType(); 1720 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1721 1722 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1723 unsigned Opc; 1724 if (SatVT == DstVT) 1725 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1726 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1727 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1728 else 1729 return SDValue(); 1730 // FIXME: Support other SatVTs by clamping before or after the conversion. 1731 1732 SDLoc DL(Op); 1733 SDValue FpToInt = DAG.getNode( 1734 Opc, DL, DstVT, Src, 1735 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1736 1737 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1738 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1739 } 1740 1741 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1742 // and back. Taking care to avoid converting values that are nan or already 1743 // correct. 1744 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1745 // have FRM dependencies modeled yet. 1746 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1747 MVT VT = Op.getSimpleValueType(); 1748 assert(VT.isVector() && "Unexpected type"); 1749 1750 SDLoc DL(Op); 1751 1752 // Freeze the source since we are increasing the number of uses. 1753 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1754 1755 // Truncate to integer and convert back to FP. 1756 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1757 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1758 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1759 1760 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1761 1762 if (Op.getOpcode() == ISD::FCEIL) { 1763 // If the truncated value is the greater than or equal to the original 1764 // value, we've computed the ceil. Otherwise, we went the wrong way and 1765 // need to increase by 1. 1766 // FIXME: This should use a masked operation. Handle here or in isel? 1767 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1768 DAG.getConstantFP(1.0, DL, VT)); 1769 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1770 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1771 } else if (Op.getOpcode() == ISD::FFLOOR) { 1772 // If the truncated value is the less than or equal to the original value, 1773 // we've computed the floor. Otherwise, we went the wrong way and need to 1774 // decrease by 1. 1775 // FIXME: This should use a masked operation. Handle here or in isel? 1776 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1777 DAG.getConstantFP(1.0, DL, VT)); 1778 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1779 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1780 } 1781 1782 // Restore the original sign so that -0.0 is preserved. 1783 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1784 1785 // Determine the largest integer that can be represented exactly. This and 1786 // values larger than it don't have any fractional bits so don't need to 1787 // be converted. 1788 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1789 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1790 APFloat MaxVal = APFloat(FltSem); 1791 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1792 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1793 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1794 1795 // If abs(Src) was larger than MaxVal or nan, keep it. 1796 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1797 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1798 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1799 } 1800 1801 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1802 // This mode isn't supported in vector hardware on RISCV. But as long as we 1803 // aren't compiling with trapping math, we can emulate this with 1804 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1805 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1806 // dependencies modeled yet. 1807 // FIXME: Use masked operations to avoid final merge. 1808 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1809 MVT VT = Op.getSimpleValueType(); 1810 assert(VT.isVector() && "Unexpected type"); 1811 1812 SDLoc DL(Op); 1813 1814 // Freeze the source since we are increasing the number of uses. 1815 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1816 1817 // We do the conversion on the absolute value and fix the sign at the end. 1818 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1819 1820 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1821 bool Ignored; 1822 APFloat Point5Pred = APFloat(0.5f); 1823 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1824 Point5Pred.next(/*nextDown*/ true); 1825 1826 // Add the adjustment. 1827 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1828 DAG.getConstantFP(Point5Pred, DL, VT)); 1829 1830 // Truncate to integer and convert back to fp. 1831 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1832 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1833 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1834 1835 // Restore the original sign. 1836 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1837 1838 // Determine the largest integer that can be represented exactly. This and 1839 // values larger than it don't have any fractional bits so don't need to 1840 // be converted. 1841 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1842 APFloat MaxVal = APFloat(FltSem); 1843 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1844 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1845 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1846 1847 // If abs(Src) was larger than MaxVal or nan, keep it. 1848 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1849 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1850 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1851 } 1852 1853 struct VIDSequence { 1854 int64_t StepNumerator; 1855 unsigned StepDenominator; 1856 int64_t Addend; 1857 }; 1858 1859 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1860 // to the (non-zero) step S and start value X. This can be then lowered as the 1861 // RVV sequence (VID * S) + X, for example. 1862 // The step S is represented as an integer numerator divided by a positive 1863 // denominator. Note that the implementation currently only identifies 1864 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1865 // cannot detect 2/3, for example. 1866 // Note that this method will also match potentially unappealing index 1867 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1868 // determine whether this is worth generating code for. 1869 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1870 unsigned NumElts = Op.getNumOperands(); 1871 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1872 if (!Op.getValueType().isInteger()) 1873 return None; 1874 1875 Optional<unsigned> SeqStepDenom; 1876 Optional<int64_t> SeqStepNum, SeqAddend; 1877 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1878 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1879 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1880 // Assume undef elements match the sequence; we just have to be careful 1881 // when interpolating across them. 1882 if (Op.getOperand(Idx).isUndef()) 1883 continue; 1884 // The BUILD_VECTOR must be all constants. 1885 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1886 return None; 1887 1888 uint64_t Val = Op.getConstantOperandVal(Idx) & 1889 maskTrailingOnes<uint64_t>(EltSizeInBits); 1890 1891 if (PrevElt) { 1892 // Calculate the step since the last non-undef element, and ensure 1893 // it's consistent across the entire sequence. 1894 unsigned IdxDiff = Idx - PrevElt->second; 1895 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1896 1897 // A zero-value value difference means that we're somewhere in the middle 1898 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1899 // step change before evaluating the sequence. 1900 if (ValDiff == 0) 1901 continue; 1902 1903 int64_t Remainder = ValDiff % IdxDiff; 1904 // Normalize the step if it's greater than 1. 1905 if (Remainder != ValDiff) { 1906 // The difference must cleanly divide the element span. 1907 if (Remainder != 0) 1908 return None; 1909 ValDiff /= IdxDiff; 1910 IdxDiff = 1; 1911 } 1912 1913 if (!SeqStepNum) 1914 SeqStepNum = ValDiff; 1915 else if (ValDiff != SeqStepNum) 1916 return None; 1917 1918 if (!SeqStepDenom) 1919 SeqStepDenom = IdxDiff; 1920 else if (IdxDiff != *SeqStepDenom) 1921 return None; 1922 } 1923 1924 // Record this non-undef element for later. 1925 if (!PrevElt || PrevElt->first != Val) 1926 PrevElt = std::make_pair(Val, Idx); 1927 } 1928 1929 // We need to have logged a step for this to count as a legal index sequence. 1930 if (!SeqStepNum || !SeqStepDenom) 1931 return None; 1932 1933 // Loop back through the sequence and validate elements we might have skipped 1934 // while waiting for a valid step. While doing this, log any sequence addend. 1935 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1936 if (Op.getOperand(Idx).isUndef()) 1937 continue; 1938 uint64_t Val = Op.getConstantOperandVal(Idx) & 1939 maskTrailingOnes<uint64_t>(EltSizeInBits); 1940 uint64_t ExpectedVal = 1941 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1942 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1943 if (!SeqAddend) 1944 SeqAddend = Addend; 1945 else if (Addend != SeqAddend) 1946 return None; 1947 } 1948 1949 assert(SeqAddend && "Must have an addend if we have a step"); 1950 1951 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1952 } 1953 1954 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1955 // and lower it as a VRGATHER_VX_VL from the source vector. 1956 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 1957 SelectionDAG &DAG, 1958 const RISCVSubtarget &Subtarget) { 1959 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1960 return SDValue(); 1961 SDValue Vec = SplatVal.getOperand(0); 1962 // Only perform this optimization on vectors of the same size for simplicity. 1963 // Don't perform this optimization for i1 vectors. 1964 // FIXME: Support i1 vectors, maybe by promoting to i8? 1965 if (Vec.getValueType() != VT || VT.getVectorElementType() == MVT::i1) 1966 return SDValue(); 1967 SDValue Idx = SplatVal.getOperand(1); 1968 // The index must be a legal type. 1969 if (Idx.getValueType() != Subtarget.getXLenVT()) 1970 return SDValue(); 1971 1972 MVT ContainerVT = VT; 1973 if (VT.isFixedLengthVector()) { 1974 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1975 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 1976 } 1977 1978 SDValue Mask, VL; 1979 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1980 1981 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 1982 Idx, Mask, DAG.getUNDEF(ContainerVT), VL); 1983 1984 if (!VT.isFixedLengthVector()) 1985 return Gather; 1986 1987 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 1988 } 1989 1990 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1991 const RISCVSubtarget &Subtarget) { 1992 MVT VT = Op.getSimpleValueType(); 1993 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1994 1995 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1996 1997 SDLoc DL(Op); 1998 SDValue Mask, VL; 1999 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2000 2001 MVT XLenVT = Subtarget.getXLenVT(); 2002 unsigned NumElts = Op.getNumOperands(); 2003 2004 if (VT.getVectorElementType() == MVT::i1) { 2005 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 2006 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 2007 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 2008 } 2009 2010 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 2011 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 2012 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 2013 } 2014 2015 // Lower constant mask BUILD_VECTORs via an integer vector type, in 2016 // scalar integer chunks whose bit-width depends on the number of mask 2017 // bits and XLEN. 2018 // First, determine the most appropriate scalar integer type to use. This 2019 // is at most XLenVT, but may be shrunk to a smaller vector element type 2020 // according to the size of the final vector - use i8 chunks rather than 2021 // XLenVT if we're producing a v8i1. This results in more consistent 2022 // codegen across RV32 and RV64. 2023 unsigned NumViaIntegerBits = 2024 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 2025 NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN()); 2026 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 2027 // If we have to use more than one INSERT_VECTOR_ELT then this 2028 // optimization is likely to increase code size; avoid peforming it in 2029 // such a case. We can use a load from a constant pool in this case. 2030 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 2031 return SDValue(); 2032 // Now we can create our integer vector type. Note that it may be larger 2033 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2034 MVT IntegerViaVecVT = 2035 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2036 divideCeil(NumElts, NumViaIntegerBits)); 2037 2038 uint64_t Bits = 0; 2039 unsigned BitPos = 0, IntegerEltIdx = 0; 2040 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2041 2042 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2043 // Once we accumulate enough bits to fill our scalar type, insert into 2044 // our vector and clear our accumulated data. 2045 if (I != 0 && I % NumViaIntegerBits == 0) { 2046 if (NumViaIntegerBits <= 32) 2047 Bits = SignExtend64<32>(Bits); 2048 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2049 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2050 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2051 Bits = 0; 2052 BitPos = 0; 2053 IntegerEltIdx++; 2054 } 2055 SDValue V = Op.getOperand(I); 2056 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2057 Bits |= ((uint64_t)BitValue << BitPos); 2058 } 2059 2060 // Insert the (remaining) scalar value into position in our integer 2061 // vector type. 2062 if (NumViaIntegerBits <= 32) 2063 Bits = SignExtend64<32>(Bits); 2064 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2065 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2066 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2067 2068 if (NumElts < NumViaIntegerBits) { 2069 // If we're producing a smaller vector than our minimum legal integer 2070 // type, bitcast to the equivalent (known-legal) mask type, and extract 2071 // our final mask. 2072 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2073 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2074 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2075 DAG.getConstant(0, DL, XLenVT)); 2076 } else { 2077 // Else we must have produced an integer type with the same size as the 2078 // mask type; bitcast for the final result. 2079 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2080 Vec = DAG.getBitcast(VT, Vec); 2081 } 2082 2083 return Vec; 2084 } 2085 2086 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2087 // vector type, we have a legal equivalently-sized i8 type, so we can use 2088 // that. 2089 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2090 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2091 2092 SDValue WideVec; 2093 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2094 // For a splat, perform a scalar truncate before creating the wider 2095 // vector. 2096 assert(Splat.getValueType() == XLenVT && 2097 "Unexpected type for i1 splat value"); 2098 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2099 DAG.getConstant(1, DL, XLenVT)); 2100 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2101 } else { 2102 SmallVector<SDValue, 8> Ops(Op->op_values()); 2103 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2104 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2105 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2106 } 2107 2108 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2109 } 2110 2111 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2112 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2113 return Gather; 2114 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2115 : RISCVISD::VMV_V_X_VL; 2116 Splat = 2117 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2118 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2119 } 2120 2121 // Try and match index sequences, which we can lower to the vid instruction 2122 // with optional modifications. An all-undef vector is matched by 2123 // getSplatValue, above. 2124 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2125 int64_t StepNumerator = SimpleVID->StepNumerator; 2126 unsigned StepDenominator = SimpleVID->StepDenominator; 2127 int64_t Addend = SimpleVID->Addend; 2128 2129 assert(StepNumerator != 0 && "Invalid step"); 2130 bool Negate = false; 2131 int64_t SplatStepVal = StepNumerator; 2132 unsigned StepOpcode = ISD::MUL; 2133 if (StepNumerator != 1) { 2134 if (isPowerOf2_64(std::abs(StepNumerator))) { 2135 Negate = StepNumerator < 0; 2136 StepOpcode = ISD::SHL; 2137 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2138 } 2139 } 2140 2141 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2142 // threshold since it's the immediate value many RVV instructions accept. 2143 // There is no vmul.vi instruction so ensure multiply constant can fit in 2144 // a single addi instruction. 2145 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2146 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2147 isPowerOf2_32(StepDenominator) && 2148 (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) { 2149 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2150 // Convert right out of the scalable type so we can use standard ISD 2151 // nodes for the rest of the computation. If we used scalable types with 2152 // these, we'd lose the fixed-length vector info and generate worse 2153 // vsetvli code. 2154 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2155 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2156 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2157 SDValue SplatStep = DAG.getSplatBuildVector( 2158 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2159 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2160 } 2161 if (StepDenominator != 1) { 2162 SDValue SplatStep = DAG.getSplatBuildVector( 2163 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2164 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2165 } 2166 if (Addend != 0 || Negate) { 2167 SDValue SplatAddend = DAG.getSplatBuildVector( 2168 VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2169 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2170 } 2171 return VID; 2172 } 2173 } 2174 2175 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2176 // when re-interpreted as a vector with a larger element type. For example, 2177 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2178 // could be instead splat as 2179 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2180 // TODO: This optimization could also work on non-constant splats, but it 2181 // would require bit-manipulation instructions to construct the splat value. 2182 SmallVector<SDValue> Sequence; 2183 unsigned EltBitSize = VT.getScalarSizeInBits(); 2184 const auto *BV = cast<BuildVectorSDNode>(Op); 2185 if (VT.isInteger() && EltBitSize < 64 && 2186 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2187 BV->getRepeatedSequence(Sequence) && 2188 (Sequence.size() * EltBitSize) <= 64) { 2189 unsigned SeqLen = Sequence.size(); 2190 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2191 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2192 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2193 ViaIntVT == MVT::i64) && 2194 "Unexpected sequence type"); 2195 2196 unsigned EltIdx = 0; 2197 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2198 uint64_t SplatValue = 0; 2199 // Construct the amalgamated value which can be splatted as this larger 2200 // vector type. 2201 for (const auto &SeqV : Sequence) { 2202 if (!SeqV.isUndef()) 2203 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2204 << (EltIdx * EltBitSize)); 2205 EltIdx++; 2206 } 2207 2208 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2209 // achieve better constant materializion. 2210 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2211 SplatValue = SignExtend64<32>(SplatValue); 2212 2213 // Since we can't introduce illegal i64 types at this stage, we can only 2214 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2215 // way we can use RVV instructions to splat. 2216 assert((ViaIntVT.bitsLE(XLenVT) || 2217 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2218 "Unexpected bitcast sequence"); 2219 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2220 SDValue ViaVL = 2221 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2222 MVT ViaContainerVT = 2223 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2224 SDValue Splat = 2225 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2226 DAG.getUNDEF(ViaContainerVT), 2227 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2228 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2229 return DAG.getBitcast(VT, Splat); 2230 } 2231 } 2232 2233 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2234 // which constitute a large proportion of the elements. In such cases we can 2235 // splat a vector with the dominant element and make up the shortfall with 2236 // INSERT_VECTOR_ELTs. 2237 // Note that this includes vectors of 2 elements by association. The 2238 // upper-most element is the "dominant" one, allowing us to use a splat to 2239 // "insert" the upper element, and an insert of the lower element at position 2240 // 0, which improves codegen. 2241 SDValue DominantValue; 2242 unsigned MostCommonCount = 0; 2243 DenseMap<SDValue, unsigned> ValueCounts; 2244 unsigned NumUndefElts = 2245 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2246 2247 // Track the number of scalar loads we know we'd be inserting, estimated as 2248 // any non-zero floating-point constant. Other kinds of element are either 2249 // already in registers or are materialized on demand. The threshold at which 2250 // a vector load is more desirable than several scalar materializion and 2251 // vector-insertion instructions is not known. 2252 unsigned NumScalarLoads = 0; 2253 2254 for (SDValue V : Op->op_values()) { 2255 if (V.isUndef()) 2256 continue; 2257 2258 ValueCounts.insert(std::make_pair(V, 0)); 2259 unsigned &Count = ValueCounts[V]; 2260 2261 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2262 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2263 2264 // Is this value dominant? In case of a tie, prefer the highest element as 2265 // it's cheaper to insert near the beginning of a vector than it is at the 2266 // end. 2267 if (++Count >= MostCommonCount) { 2268 DominantValue = V; 2269 MostCommonCount = Count; 2270 } 2271 } 2272 2273 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2274 unsigned NumDefElts = NumElts - NumUndefElts; 2275 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2276 2277 // Don't perform this optimization when optimizing for size, since 2278 // materializing elements and inserting them tends to cause code bloat. 2279 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2280 ((MostCommonCount > DominantValueCountThreshold) || 2281 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2282 // Start by splatting the most common element. 2283 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2284 2285 DenseSet<SDValue> Processed{DominantValue}; 2286 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2287 for (const auto &OpIdx : enumerate(Op->ops())) { 2288 const SDValue &V = OpIdx.value(); 2289 if (V.isUndef() || !Processed.insert(V).second) 2290 continue; 2291 if (ValueCounts[V] == 1) { 2292 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2293 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2294 } else { 2295 // Blend in all instances of this value using a VSELECT, using a 2296 // mask where each bit signals whether that element is the one 2297 // we're after. 2298 SmallVector<SDValue> Ops; 2299 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2300 return DAG.getConstant(V == V1, DL, XLenVT); 2301 }); 2302 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2303 DAG.getBuildVector(SelMaskTy, DL, Ops), 2304 DAG.getSplatBuildVector(VT, DL, V), Vec); 2305 } 2306 } 2307 2308 return Vec; 2309 } 2310 2311 return SDValue(); 2312 } 2313 2314 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2315 SDValue Lo, SDValue Hi, SDValue VL, 2316 SelectionDAG &DAG) { 2317 if (!Passthru) 2318 Passthru = DAG.getUNDEF(VT); 2319 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2320 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2321 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2322 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2323 // node in order to try and match RVV vector/scalar instructions. 2324 if ((LoC >> 31) == HiC) 2325 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2326 2327 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2328 // vmv.v.x whose EEW = 32 to lower it. 2329 auto *Const = dyn_cast<ConstantSDNode>(VL); 2330 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2331 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2332 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2333 // access the subtarget here now. 2334 auto InterVec = DAG.getNode( 2335 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2336 DAG.getRegister(RISCV::X0, MVT::i32)); 2337 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2338 } 2339 } 2340 2341 // Fall back to a stack store and stride x0 vector load. 2342 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2343 Hi, VL); 2344 } 2345 2346 // Called by type legalization to handle splat of i64 on RV32. 2347 // FIXME: We can optimize this when the type has sign or zero bits in one 2348 // of the halves. 2349 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2350 SDValue Scalar, SDValue VL, 2351 SelectionDAG &DAG) { 2352 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2353 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2354 DAG.getConstant(0, DL, MVT::i32)); 2355 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2356 DAG.getConstant(1, DL, MVT::i32)); 2357 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2358 } 2359 2360 // This function lowers a splat of a scalar operand Splat with the vector 2361 // length VL. It ensures the final sequence is type legal, which is useful when 2362 // lowering a splat after type legalization. 2363 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2364 MVT VT, SDLoc DL, SelectionDAG &DAG, 2365 const RISCVSubtarget &Subtarget) { 2366 bool HasPassthru = Passthru && !Passthru.isUndef(); 2367 if (!HasPassthru && !Passthru) 2368 Passthru = DAG.getUNDEF(VT); 2369 if (VT.isFloatingPoint()) { 2370 // If VL is 1, we could use vfmv.s.f. 2371 if (isOneConstant(VL)) 2372 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2373 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2374 } 2375 2376 MVT XLenVT = Subtarget.getXLenVT(); 2377 2378 // Simplest case is that the operand needs to be promoted to XLenVT. 2379 if (Scalar.getValueType().bitsLE(XLenVT)) { 2380 // If the operand is a constant, sign extend to increase our chances 2381 // of being able to use a .vi instruction. ANY_EXTEND would become a 2382 // a zero extend and the simm5 check in isel would fail. 2383 // FIXME: Should we ignore the upper bits in isel instead? 2384 unsigned ExtOpc = 2385 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2386 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2387 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2388 // If VL is 1 and the scalar value won't benefit from immediate, we could 2389 // use vmv.s.x. 2390 if (isOneConstant(VL) && 2391 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2392 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2393 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2394 } 2395 2396 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2397 "Unexpected scalar for splat lowering!"); 2398 2399 if (isOneConstant(VL) && isNullConstant(Scalar)) 2400 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2401 DAG.getConstant(0, DL, XLenVT), VL); 2402 2403 // Otherwise use the more complicated splatting algorithm. 2404 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2405 } 2406 2407 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2408 const RISCVSubtarget &Subtarget) { 2409 // We need to be able to widen elements to the next larger integer type. 2410 if (VT.getScalarSizeInBits() >= Subtarget.getELEN()) 2411 return false; 2412 2413 int Size = Mask.size(); 2414 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2415 2416 int Srcs[] = {-1, -1}; 2417 for (int i = 0; i != Size; ++i) { 2418 // Ignore undef elements. 2419 if (Mask[i] < 0) 2420 continue; 2421 2422 // Is this an even or odd element. 2423 int Pol = i % 2; 2424 2425 // Ensure we consistently use the same source for this element polarity. 2426 int Src = Mask[i] / Size; 2427 if (Srcs[Pol] < 0) 2428 Srcs[Pol] = Src; 2429 if (Srcs[Pol] != Src) 2430 return false; 2431 2432 // Make sure the element within the source is appropriate for this element 2433 // in the destination. 2434 int Elt = Mask[i] % Size; 2435 if (Elt != i / 2) 2436 return false; 2437 } 2438 2439 // We need to find a source for each polarity and they can't be the same. 2440 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2441 return false; 2442 2443 // Swap the sources if the second source was in the even polarity. 2444 SwapSources = Srcs[0] > Srcs[1]; 2445 2446 return true; 2447 } 2448 2449 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2450 /// and then extract the original number of elements from the rotated result. 2451 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2452 /// returned rotation amount is for a rotate right, where elements move from 2453 /// higher elements to lower elements. \p LoSrc indicates the first source 2454 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2455 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2456 /// 0 or 1 if a rotation is found. 2457 /// 2458 /// NOTE: We talk about rotate to the right which matches how bit shift and 2459 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2460 /// and the table below write vectors with the lowest elements on the left. 2461 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2462 int Size = Mask.size(); 2463 2464 // We need to detect various ways of spelling a rotation: 2465 // [11, 12, 13, 14, 15, 0, 1, 2] 2466 // [-1, 12, 13, 14, -1, -1, 1, -1] 2467 // [-1, -1, -1, -1, -1, -1, 1, 2] 2468 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2469 // [-1, 4, 5, 6, -1, -1, 9, -1] 2470 // [-1, 4, 5, 6, -1, -1, -1, -1] 2471 int Rotation = 0; 2472 LoSrc = -1; 2473 HiSrc = -1; 2474 for (int i = 0; i != Size; ++i) { 2475 int M = Mask[i]; 2476 if (M < 0) 2477 continue; 2478 2479 // Determine where a rotate vector would have started. 2480 int StartIdx = i - (M % Size); 2481 // The identity rotation isn't interesting, stop. 2482 if (StartIdx == 0) 2483 return -1; 2484 2485 // If we found the tail of a vector the rotation must be the missing 2486 // front. If we found the head of a vector, it must be how much of the 2487 // head. 2488 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2489 2490 if (Rotation == 0) 2491 Rotation = CandidateRotation; 2492 else if (Rotation != CandidateRotation) 2493 // The rotations don't match, so we can't match this mask. 2494 return -1; 2495 2496 // Compute which value this mask is pointing at. 2497 int MaskSrc = M < Size ? 0 : 1; 2498 2499 // Compute which of the two target values this index should be assigned to. 2500 // This reflects whether the high elements are remaining or the low elemnts 2501 // are remaining. 2502 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2503 2504 // Either set up this value if we've not encountered it before, or check 2505 // that it remains consistent. 2506 if (TargetSrc < 0) 2507 TargetSrc = MaskSrc; 2508 else if (TargetSrc != MaskSrc) 2509 // This may be a rotation, but it pulls from the inputs in some 2510 // unsupported interleaving. 2511 return -1; 2512 } 2513 2514 // Check that we successfully analyzed the mask, and normalize the results. 2515 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2516 assert((LoSrc >= 0 || HiSrc >= 0) && 2517 "Failed to find a rotated input vector!"); 2518 2519 return Rotation; 2520 } 2521 2522 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2523 const RISCVSubtarget &Subtarget) { 2524 SDValue V1 = Op.getOperand(0); 2525 SDValue V2 = Op.getOperand(1); 2526 SDLoc DL(Op); 2527 MVT XLenVT = Subtarget.getXLenVT(); 2528 MVT VT = Op.getSimpleValueType(); 2529 unsigned NumElts = VT.getVectorNumElements(); 2530 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2531 2532 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2533 2534 SDValue TrueMask, VL; 2535 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2536 2537 if (SVN->isSplat()) { 2538 const int Lane = SVN->getSplatIndex(); 2539 if (Lane >= 0) { 2540 MVT SVT = VT.getVectorElementType(); 2541 2542 // Turn splatted vector load into a strided load with an X0 stride. 2543 SDValue V = V1; 2544 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2545 // with undef. 2546 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2547 int Offset = Lane; 2548 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2549 int OpElements = 2550 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2551 V = V.getOperand(Offset / OpElements); 2552 Offset %= OpElements; 2553 } 2554 2555 // We need to ensure the load isn't atomic or volatile. 2556 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2557 auto *Ld = cast<LoadSDNode>(V); 2558 Offset *= SVT.getStoreSize(); 2559 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2560 TypeSize::Fixed(Offset), DL); 2561 2562 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2563 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2564 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2565 SDValue IntID = 2566 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2567 SDValue Ops[] = {Ld->getChain(), 2568 IntID, 2569 DAG.getUNDEF(ContainerVT), 2570 NewAddr, 2571 DAG.getRegister(RISCV::X0, XLenVT), 2572 VL}; 2573 SDValue NewLoad = DAG.getMemIntrinsicNode( 2574 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2575 DAG.getMachineFunction().getMachineMemOperand( 2576 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2577 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2578 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2579 } 2580 2581 // Otherwise use a scalar load and splat. This will give the best 2582 // opportunity to fold a splat into the operation. ISel can turn it into 2583 // the x0 strided load if we aren't able to fold away the select. 2584 if (SVT.isFloatingPoint()) 2585 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2586 Ld->getPointerInfo().getWithOffset(Offset), 2587 Ld->getOriginalAlign(), 2588 Ld->getMemOperand()->getFlags()); 2589 else 2590 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2591 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2592 Ld->getOriginalAlign(), 2593 Ld->getMemOperand()->getFlags()); 2594 DAG.makeEquivalentMemoryOrdering(Ld, V); 2595 2596 unsigned Opc = 2597 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2598 SDValue Splat = 2599 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2600 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2601 } 2602 2603 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2604 assert(Lane < (int)NumElts && "Unexpected lane!"); 2605 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, 2606 V1, DAG.getConstant(Lane, DL, XLenVT), 2607 TrueMask, DAG.getUNDEF(ContainerVT), VL); 2608 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2609 } 2610 } 2611 2612 ArrayRef<int> Mask = SVN->getMask(); 2613 2614 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2615 // be undef which can be handled with a single SLIDEDOWN/UP. 2616 int LoSrc, HiSrc; 2617 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2618 if (Rotation > 0) { 2619 SDValue LoV, HiV; 2620 if (LoSrc >= 0) { 2621 LoV = LoSrc == 0 ? V1 : V2; 2622 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2623 } 2624 if (HiSrc >= 0) { 2625 HiV = HiSrc == 0 ? V1 : V2; 2626 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2627 } 2628 2629 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2630 // to slide LoV up by (NumElts - Rotation). 2631 unsigned InvRotate = NumElts - Rotation; 2632 2633 SDValue Res = DAG.getUNDEF(ContainerVT); 2634 if (HiV) { 2635 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2636 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2637 // causes multiple vsetvlis in some test cases such as lowering 2638 // reduce.mul 2639 SDValue DownVL = VL; 2640 if (LoV) 2641 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2642 Res = 2643 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2644 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2645 } 2646 if (LoV) 2647 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2648 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2649 2650 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2651 } 2652 2653 // Detect an interleave shuffle and lower to 2654 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2655 bool SwapSources; 2656 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2657 // Swap sources if needed. 2658 if (SwapSources) 2659 std::swap(V1, V2); 2660 2661 // Extract the lower half of the vectors. 2662 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2663 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2664 DAG.getConstant(0, DL, XLenVT)); 2665 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2666 DAG.getConstant(0, DL, XLenVT)); 2667 2668 // Double the element width and halve the number of elements in an int type. 2669 unsigned EltBits = VT.getScalarSizeInBits(); 2670 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2671 MVT WideIntVT = 2672 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2673 // Convert this to a scalable vector. We need to base this on the 2674 // destination size to ensure there's always a type with a smaller LMUL. 2675 MVT WideIntContainerVT = 2676 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2677 2678 // Convert sources to scalable vectors with the same element count as the 2679 // larger type. 2680 MVT HalfContainerVT = MVT::getVectorVT( 2681 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2682 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2683 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2684 2685 // Cast sources to integer. 2686 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2687 MVT IntHalfVT = 2688 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2689 V1 = DAG.getBitcast(IntHalfVT, V1); 2690 V2 = DAG.getBitcast(IntHalfVT, V2); 2691 2692 // Freeze V2 since we use it twice and we need to be sure that the add and 2693 // multiply see the same value. 2694 V2 = DAG.getFreeze(V2); 2695 2696 // Recreate TrueMask using the widened type's element count. 2697 TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG); 2698 2699 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2700 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2701 V2, TrueMask, VL); 2702 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2703 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2704 DAG.getUNDEF(IntHalfVT), 2705 DAG.getAllOnesConstant(DL, XLenVT)); 2706 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2707 V2, Multiplier, TrueMask, VL); 2708 // Add the new copies to our previous addition giving us 2^eltbits copies of 2709 // V2. This is equivalent to shifting V2 left by eltbits. This should 2710 // combine with the vwmulu.vv above to form vwmaccu.vv. 2711 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2712 TrueMask, VL); 2713 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2714 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2715 // vector VT. 2716 ContainerVT = 2717 MVT::getVectorVT(VT.getVectorElementType(), 2718 WideIntContainerVT.getVectorElementCount() * 2); 2719 Add = DAG.getBitcast(ContainerVT, Add); 2720 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2721 } 2722 2723 // Detect shuffles which can be re-expressed as vector selects; these are 2724 // shuffles in which each element in the destination is taken from an element 2725 // at the corresponding index in either source vectors. 2726 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2727 int MaskIndex = MaskIdx.value(); 2728 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2729 }); 2730 2731 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2732 2733 SmallVector<SDValue> MaskVals; 2734 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2735 // merged with a second vrgather. 2736 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2737 2738 // By default we preserve the original operand order, and use a mask to 2739 // select LHS as true and RHS as false. However, since RVV vector selects may 2740 // feature splats but only on the LHS, we may choose to invert our mask and 2741 // instead select between RHS and LHS. 2742 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2743 bool InvertMask = IsSelect == SwapOps; 2744 2745 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2746 // half. 2747 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2748 2749 // Now construct the mask that will be used by the vselect or blended 2750 // vrgather operation. For vrgathers, construct the appropriate indices into 2751 // each vector. 2752 for (int MaskIndex : Mask) { 2753 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2754 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2755 if (!IsSelect) { 2756 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2757 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2758 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2759 : DAG.getUNDEF(XLenVT)); 2760 GatherIndicesRHS.push_back( 2761 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2762 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2763 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2764 ++LHSIndexCounts[MaskIndex]; 2765 if (!IsLHSOrUndefIndex) 2766 ++RHSIndexCounts[MaskIndex - NumElts]; 2767 } 2768 } 2769 2770 if (SwapOps) { 2771 std::swap(V1, V2); 2772 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2773 } 2774 2775 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2776 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2777 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2778 2779 if (IsSelect) 2780 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2781 2782 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2783 // On such a large vector we're unable to use i8 as the index type. 2784 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2785 // may involve vector splitting if we're already at LMUL=8, or our 2786 // user-supplied maximum fixed-length LMUL. 2787 return SDValue(); 2788 } 2789 2790 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2791 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2792 MVT IndexVT = VT.changeTypeToInteger(); 2793 // Since we can't introduce illegal index types at this stage, use i16 and 2794 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2795 // than XLenVT. 2796 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2797 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2798 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2799 } 2800 2801 MVT IndexContainerVT = 2802 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2803 2804 SDValue Gather; 2805 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2806 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2807 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2808 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2809 Subtarget); 2810 } else { 2811 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2812 // If only one index is used, we can use a "splat" vrgather. 2813 // TODO: We can splat the most-common index and fix-up any stragglers, if 2814 // that's beneficial. 2815 if (LHSIndexCounts.size() == 1) { 2816 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2817 Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2818 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, 2819 DAG.getUNDEF(ContainerVT), VL); 2820 } else { 2821 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2822 LHSIndices = 2823 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2824 2825 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2826 TrueMask, DAG.getUNDEF(ContainerVT), VL); 2827 } 2828 } 2829 2830 // If a second vector operand is used by this shuffle, blend it in with an 2831 // additional vrgather. 2832 if (!V2.isUndef()) { 2833 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2834 2835 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2836 SelectMask = 2837 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2838 2839 // If only one index is used, we can use a "splat" vrgather. 2840 // TODO: We can splat the most-common index and fix-up any stragglers, if 2841 // that's beneficial. 2842 if (RHSIndexCounts.size() == 1) { 2843 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2844 Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2845 DAG.getConstant(SplatIndex, DL, XLenVT), SelectMask, 2846 Gather, VL); 2847 } else { 2848 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2849 RHSIndices = 2850 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2851 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, 2852 SelectMask, Gather, VL); 2853 } 2854 } 2855 2856 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2857 } 2858 2859 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2860 // Support splats for any type. These should type legalize well. 2861 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2862 return true; 2863 2864 // Only support legal VTs for other shuffles for now. 2865 if (!isTypeLegal(VT)) 2866 return false; 2867 2868 MVT SVT = VT.getSimpleVT(); 2869 2870 bool SwapSources; 2871 int LoSrc, HiSrc; 2872 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2873 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2874 } 2875 2876 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2877 // the exponent. 2878 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2879 MVT VT = Op.getSimpleValueType(); 2880 unsigned EltSize = VT.getScalarSizeInBits(); 2881 SDValue Src = Op.getOperand(0); 2882 SDLoc DL(Op); 2883 2884 // We need a FP type that can represent the value. 2885 // TODO: Use f16 for i8 when possible? 2886 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2887 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2888 2889 // Legal types should have been checked in the RISCVTargetLowering 2890 // constructor. 2891 // TODO: Splitting may make sense in some cases. 2892 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2893 "Expected legal float type!"); 2894 2895 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2896 // The trailing zero count is equal to log2 of this single bit value. 2897 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2898 SDValue Neg = 2899 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2900 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2901 } 2902 2903 // We have a legal FP type, convert to it. 2904 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2905 // Bitcast to integer and shift the exponent to the LSB. 2906 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2907 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2908 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2909 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2910 DAG.getConstant(ShiftAmt, DL, IntVT)); 2911 // Truncate back to original type to allow vnsrl. 2912 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2913 // The exponent contains log2 of the value in biased form. 2914 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2915 2916 // For trailing zeros, we just need to subtract the bias. 2917 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2918 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2919 DAG.getConstant(ExponentBias, DL, VT)); 2920 2921 // For leading zeros, we need to remove the bias and convert from log2 to 2922 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2923 unsigned Adjust = ExponentBias + (EltSize - 1); 2924 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2925 } 2926 2927 // While RVV has alignment restrictions, we should always be able to load as a 2928 // legal equivalently-sized byte-typed vector instead. This method is 2929 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2930 // the load is already correctly-aligned, it returns SDValue(). 2931 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2932 SelectionDAG &DAG) const { 2933 auto *Load = cast<LoadSDNode>(Op); 2934 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2935 2936 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2937 Load->getMemoryVT(), 2938 *Load->getMemOperand())) 2939 return SDValue(); 2940 2941 SDLoc DL(Op); 2942 MVT VT = Op.getSimpleValueType(); 2943 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2944 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2945 "Unexpected unaligned RVV load type"); 2946 MVT NewVT = 2947 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2948 assert(NewVT.isValid() && 2949 "Expecting equally-sized RVV vector types to be legal"); 2950 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2951 Load->getPointerInfo(), Load->getOriginalAlign(), 2952 Load->getMemOperand()->getFlags()); 2953 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2954 } 2955 2956 // While RVV has alignment restrictions, we should always be able to store as a 2957 // legal equivalently-sized byte-typed vector instead. This method is 2958 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2959 // returns SDValue() if the store is already correctly aligned. 2960 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2961 SelectionDAG &DAG) const { 2962 auto *Store = cast<StoreSDNode>(Op); 2963 assert(Store && Store->getValue().getValueType().isVector() && 2964 "Expected vector store"); 2965 2966 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2967 Store->getMemoryVT(), 2968 *Store->getMemOperand())) 2969 return SDValue(); 2970 2971 SDLoc DL(Op); 2972 SDValue StoredVal = Store->getValue(); 2973 MVT VT = StoredVal.getSimpleValueType(); 2974 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2975 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2976 "Unexpected unaligned RVV store type"); 2977 MVT NewVT = 2978 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2979 assert(NewVT.isValid() && 2980 "Expecting equally-sized RVV vector types to be legal"); 2981 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2982 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2983 Store->getPointerInfo(), Store->getOriginalAlign(), 2984 Store->getMemOperand()->getFlags()); 2985 } 2986 2987 static SDValue lowerConstant(SDValue Op, SelectionDAG &DAG, 2988 const RISCVSubtarget &Subtarget) { 2989 assert(Op.getValueType() == MVT::i64 && "Unexpected VT"); 2990 2991 int64_t Imm = cast<ConstantSDNode>(Op)->getSExtValue(); 2992 2993 // All simm32 constants should be handled by isel. 2994 // NOTE: The getMaxBuildIntsCost call below should return a value >= 2 making 2995 // this check redundant, but small immediates are common so this check 2996 // should have better compile time. 2997 if (isInt<32>(Imm)) 2998 return Op; 2999 3000 // We only need to cost the immediate, if constant pool lowering is enabled. 3001 if (!Subtarget.useConstantPoolForLargeInts()) 3002 return Op; 3003 3004 RISCVMatInt::InstSeq Seq = 3005 RISCVMatInt::generateInstSeq(Imm, Subtarget.getFeatureBits()); 3006 if (Seq.size() <= Subtarget.getMaxBuildIntsCost()) 3007 return Op; 3008 3009 // Expand to a constant pool using the default expansion code. 3010 return SDValue(); 3011 } 3012 3013 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 3014 SelectionDAG &DAG) const { 3015 switch (Op.getOpcode()) { 3016 default: 3017 report_fatal_error("unimplemented operand"); 3018 case ISD::GlobalAddress: 3019 return lowerGlobalAddress(Op, DAG); 3020 case ISD::BlockAddress: 3021 return lowerBlockAddress(Op, DAG); 3022 case ISD::ConstantPool: 3023 return lowerConstantPool(Op, DAG); 3024 case ISD::JumpTable: 3025 return lowerJumpTable(Op, DAG); 3026 case ISD::GlobalTLSAddress: 3027 return lowerGlobalTLSAddress(Op, DAG); 3028 case ISD::Constant: 3029 return lowerConstant(Op, DAG, Subtarget); 3030 case ISD::SELECT: 3031 return lowerSELECT(Op, DAG); 3032 case ISD::BRCOND: 3033 return lowerBRCOND(Op, DAG); 3034 case ISD::VASTART: 3035 return lowerVASTART(Op, DAG); 3036 case ISD::FRAMEADDR: 3037 return lowerFRAMEADDR(Op, DAG); 3038 case ISD::RETURNADDR: 3039 return lowerRETURNADDR(Op, DAG); 3040 case ISD::SHL_PARTS: 3041 return lowerShiftLeftParts(Op, DAG); 3042 case ISD::SRA_PARTS: 3043 return lowerShiftRightParts(Op, DAG, true); 3044 case ISD::SRL_PARTS: 3045 return lowerShiftRightParts(Op, DAG, false); 3046 case ISD::BITCAST: { 3047 SDLoc DL(Op); 3048 EVT VT = Op.getValueType(); 3049 SDValue Op0 = Op.getOperand(0); 3050 EVT Op0VT = Op0.getValueType(); 3051 MVT XLenVT = Subtarget.getXLenVT(); 3052 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 3053 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 3054 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 3055 return FPConv; 3056 } 3057 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 3058 Subtarget.hasStdExtF()) { 3059 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3060 SDValue FPConv = 3061 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3062 return FPConv; 3063 } 3064 3065 // Consider other scalar<->scalar casts as legal if the types are legal. 3066 // Otherwise expand them. 3067 if (!VT.isVector() && !Op0VT.isVector()) { 3068 if (isTypeLegal(VT) && isTypeLegal(Op0VT)) 3069 return Op; 3070 return SDValue(); 3071 } 3072 3073 assert(!VT.isScalableVector() && !Op0VT.isScalableVector() && 3074 "Unexpected types"); 3075 3076 if (VT.isFixedLengthVector()) { 3077 // We can handle fixed length vector bitcasts with a simple replacement 3078 // in isel. 3079 if (Op0VT.isFixedLengthVector()) 3080 return Op; 3081 // When bitcasting from scalar to fixed-length vector, insert the scalar 3082 // into a one-element vector of the result type, and perform a vector 3083 // bitcast. 3084 if (!Op0VT.isVector()) { 3085 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 3086 if (!isTypeLegal(BVT)) 3087 return SDValue(); 3088 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 3089 DAG.getUNDEF(BVT), Op0, 3090 DAG.getConstant(0, DL, XLenVT))); 3091 } 3092 return SDValue(); 3093 } 3094 // Custom-legalize bitcasts from fixed-length vector types to scalar types 3095 // thus: bitcast the vector to a one-element vector type whose element type 3096 // is the same as the result type, and extract the first element. 3097 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 3098 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 3099 if (!isTypeLegal(BVT)) 3100 return SDValue(); 3101 SDValue BVec = DAG.getBitcast(BVT, Op0); 3102 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 3103 DAG.getConstant(0, DL, XLenVT)); 3104 } 3105 return SDValue(); 3106 } 3107 case ISD::INTRINSIC_WO_CHAIN: 3108 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3109 case ISD::INTRINSIC_W_CHAIN: 3110 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3111 case ISD::INTRINSIC_VOID: 3112 return LowerINTRINSIC_VOID(Op, DAG); 3113 case ISD::BSWAP: 3114 case ISD::BITREVERSE: { 3115 MVT VT = Op.getSimpleValueType(); 3116 SDLoc DL(Op); 3117 if (Subtarget.hasStdExtZbp()) { 3118 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3119 // Start with the maximum immediate value which is the bitwidth - 1. 3120 unsigned Imm = VT.getSizeInBits() - 1; 3121 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3122 if (Op.getOpcode() == ISD::BSWAP) 3123 Imm &= ~0x7U; 3124 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3125 DAG.getConstant(Imm, DL, VT)); 3126 } 3127 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3128 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3129 // Expand bitreverse to a bswap(rev8) followed by brev8. 3130 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3131 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3132 // as brev8 by an isel pattern. 3133 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3134 DAG.getConstant(7, DL, VT)); 3135 } 3136 case ISD::FSHL: 3137 case ISD::FSHR: { 3138 MVT VT = Op.getSimpleValueType(); 3139 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3140 SDLoc DL(Op); 3141 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3142 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3143 // accidentally setting the extra bit. 3144 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3145 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3146 DAG.getConstant(ShAmtWidth, DL, VT)); 3147 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3148 // instruction use different orders. fshl will return its first operand for 3149 // shift of zero, fshr will return its second operand. fsl and fsr both 3150 // return rs1 so the ISD nodes need to have different operand orders. 3151 // Shift amount is in rs2. 3152 SDValue Op0 = Op.getOperand(0); 3153 SDValue Op1 = Op.getOperand(1); 3154 unsigned Opc = RISCVISD::FSL; 3155 if (Op.getOpcode() == ISD::FSHR) { 3156 std::swap(Op0, Op1); 3157 Opc = RISCVISD::FSR; 3158 } 3159 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3160 } 3161 case ISD::TRUNCATE: 3162 // Only custom-lower vector truncates 3163 if (!Op.getSimpleValueType().isVector()) 3164 return Op; 3165 return lowerVectorTruncLike(Op, DAG); 3166 case ISD::ANY_EXTEND: 3167 case ISD::ZERO_EXTEND: 3168 if (Op.getOperand(0).getValueType().isVector() && 3169 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3170 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3171 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3172 case ISD::SIGN_EXTEND: 3173 if (Op.getOperand(0).getValueType().isVector() && 3174 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3175 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3176 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3177 case ISD::SPLAT_VECTOR_PARTS: 3178 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3179 case ISD::INSERT_VECTOR_ELT: 3180 return lowerINSERT_VECTOR_ELT(Op, DAG); 3181 case ISD::EXTRACT_VECTOR_ELT: 3182 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3183 case ISD::VSCALE: { 3184 MVT VT = Op.getSimpleValueType(); 3185 SDLoc DL(Op); 3186 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3187 // We define our scalable vector types for lmul=1 to use a 64 bit known 3188 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3189 // vscale as VLENB / 8. 3190 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3191 if (Subtarget.getRealMinVLen() < RISCV::RVVBitsPerBlock) 3192 report_fatal_error("Support for VLEN==32 is incomplete."); 3193 // We assume VLENB is a multiple of 8. We manually choose the best shift 3194 // here because SimplifyDemandedBits isn't always able to simplify it. 3195 uint64_t Val = Op.getConstantOperandVal(0); 3196 if (isPowerOf2_64(Val)) { 3197 uint64_t Log2 = Log2_64(Val); 3198 if (Log2 < 3) 3199 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3200 DAG.getConstant(3 - Log2, DL, VT)); 3201 if (Log2 > 3) 3202 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3203 DAG.getConstant(Log2 - 3, DL, VT)); 3204 return VLENB; 3205 } 3206 // If the multiplier is a multiple of 8, scale it down to avoid needing 3207 // to shift the VLENB value. 3208 if ((Val % 8) == 0) 3209 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3210 DAG.getConstant(Val / 8, DL, VT)); 3211 3212 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3213 DAG.getConstant(3, DL, VT)); 3214 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3215 } 3216 case ISD::FPOWI: { 3217 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3218 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3219 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3220 Op.getOperand(1).getValueType() == MVT::i32) { 3221 SDLoc DL(Op); 3222 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3223 SDValue Powi = 3224 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3225 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3226 DAG.getIntPtrConstant(0, DL)); 3227 } 3228 return SDValue(); 3229 } 3230 case ISD::FP_EXTEND: 3231 case ISD::FP_ROUND: 3232 if (!Op.getValueType().isVector()) 3233 return Op; 3234 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3235 case ISD::FP_TO_SINT: 3236 case ISD::FP_TO_UINT: 3237 case ISD::SINT_TO_FP: 3238 case ISD::UINT_TO_FP: { 3239 // RVV can only do fp<->int conversions to types half/double the size as 3240 // the source. We custom-lower any conversions that do two hops into 3241 // sequences. 3242 MVT VT = Op.getSimpleValueType(); 3243 if (!VT.isVector()) 3244 return Op; 3245 SDLoc DL(Op); 3246 SDValue Src = Op.getOperand(0); 3247 MVT EltVT = VT.getVectorElementType(); 3248 MVT SrcVT = Src.getSimpleValueType(); 3249 MVT SrcEltVT = SrcVT.getVectorElementType(); 3250 unsigned EltSize = EltVT.getSizeInBits(); 3251 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3252 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3253 "Unexpected vector element types"); 3254 3255 bool IsInt2FP = SrcEltVT.isInteger(); 3256 // Widening conversions 3257 if (EltSize > (2 * SrcEltSize)) { 3258 if (IsInt2FP) { 3259 // Do a regular integer sign/zero extension then convert to float. 3260 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), 3261 VT.getVectorElementCount()); 3262 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3263 ? ISD::ZERO_EXTEND 3264 : ISD::SIGN_EXTEND; 3265 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3266 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3267 } 3268 // FP2Int 3269 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3270 // Do one doubling fp_extend then complete the operation by converting 3271 // to int. 3272 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3273 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3274 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3275 } 3276 3277 // Narrowing conversions 3278 if (SrcEltSize > (2 * EltSize)) { 3279 if (IsInt2FP) { 3280 // One narrowing int_to_fp, then an fp_round. 3281 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3282 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3283 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3284 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3285 } 3286 // FP2Int 3287 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3288 // representable by the integer, the result is poison. 3289 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 3290 VT.getVectorElementCount()); 3291 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3292 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3293 } 3294 3295 // Scalable vectors can exit here. Patterns will handle equally-sized 3296 // conversions halving/doubling ones. 3297 if (!VT.isFixedLengthVector()) 3298 return Op; 3299 3300 // For fixed-length vectors we lower to a custom "VL" node. 3301 unsigned RVVOpc = 0; 3302 switch (Op.getOpcode()) { 3303 default: 3304 llvm_unreachable("Impossible opcode"); 3305 case ISD::FP_TO_SINT: 3306 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3307 break; 3308 case ISD::FP_TO_UINT: 3309 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3310 break; 3311 case ISD::SINT_TO_FP: 3312 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3313 break; 3314 case ISD::UINT_TO_FP: 3315 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3316 break; 3317 } 3318 3319 MVT ContainerVT, SrcContainerVT; 3320 // Derive the reference container type from the larger vector type. 3321 if (SrcEltSize > EltSize) { 3322 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3323 ContainerVT = 3324 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3325 } else { 3326 ContainerVT = getContainerForFixedLengthVector(VT); 3327 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3328 } 3329 3330 SDValue Mask, VL; 3331 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3332 3333 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3334 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3335 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3336 } 3337 case ISD::FP_TO_SINT_SAT: 3338 case ISD::FP_TO_UINT_SAT: 3339 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3340 case ISD::FTRUNC: 3341 case ISD::FCEIL: 3342 case ISD::FFLOOR: 3343 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3344 case ISD::FROUND: 3345 return lowerFROUND(Op, DAG); 3346 case ISD::VECREDUCE_ADD: 3347 case ISD::VECREDUCE_UMAX: 3348 case ISD::VECREDUCE_SMAX: 3349 case ISD::VECREDUCE_UMIN: 3350 case ISD::VECREDUCE_SMIN: 3351 return lowerVECREDUCE(Op, DAG); 3352 case ISD::VECREDUCE_AND: 3353 case ISD::VECREDUCE_OR: 3354 case ISD::VECREDUCE_XOR: 3355 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3356 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3357 return lowerVECREDUCE(Op, DAG); 3358 case ISD::VECREDUCE_FADD: 3359 case ISD::VECREDUCE_SEQ_FADD: 3360 case ISD::VECREDUCE_FMIN: 3361 case ISD::VECREDUCE_FMAX: 3362 return lowerFPVECREDUCE(Op, DAG); 3363 case ISD::VP_REDUCE_ADD: 3364 case ISD::VP_REDUCE_UMAX: 3365 case ISD::VP_REDUCE_SMAX: 3366 case ISD::VP_REDUCE_UMIN: 3367 case ISD::VP_REDUCE_SMIN: 3368 case ISD::VP_REDUCE_FADD: 3369 case ISD::VP_REDUCE_SEQ_FADD: 3370 case ISD::VP_REDUCE_FMIN: 3371 case ISD::VP_REDUCE_FMAX: 3372 return lowerVPREDUCE(Op, DAG); 3373 case ISD::VP_REDUCE_AND: 3374 case ISD::VP_REDUCE_OR: 3375 case ISD::VP_REDUCE_XOR: 3376 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3377 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3378 return lowerVPREDUCE(Op, DAG); 3379 case ISD::INSERT_SUBVECTOR: 3380 return lowerINSERT_SUBVECTOR(Op, DAG); 3381 case ISD::EXTRACT_SUBVECTOR: 3382 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3383 case ISD::STEP_VECTOR: 3384 return lowerSTEP_VECTOR(Op, DAG); 3385 case ISD::VECTOR_REVERSE: 3386 return lowerVECTOR_REVERSE(Op, DAG); 3387 case ISD::VECTOR_SPLICE: 3388 return lowerVECTOR_SPLICE(Op, DAG); 3389 case ISD::BUILD_VECTOR: 3390 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3391 case ISD::SPLAT_VECTOR: 3392 if (Op.getValueType().getVectorElementType() == MVT::i1) 3393 return lowerVectorMaskSplat(Op, DAG); 3394 return SDValue(); 3395 case ISD::VECTOR_SHUFFLE: 3396 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3397 case ISD::CONCAT_VECTORS: { 3398 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3399 // better than going through the stack, as the default expansion does. 3400 SDLoc DL(Op); 3401 MVT VT = Op.getSimpleValueType(); 3402 unsigned NumOpElts = 3403 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3404 SDValue Vec = DAG.getUNDEF(VT); 3405 for (const auto &OpIdx : enumerate(Op->ops())) { 3406 SDValue SubVec = OpIdx.value(); 3407 // Don't insert undef subvectors. 3408 if (SubVec.isUndef()) 3409 continue; 3410 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3411 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3412 } 3413 return Vec; 3414 } 3415 case ISD::LOAD: 3416 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3417 return V; 3418 if (Op.getValueType().isFixedLengthVector()) 3419 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3420 return Op; 3421 case ISD::STORE: 3422 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3423 return V; 3424 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3425 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3426 return Op; 3427 case ISD::MLOAD: 3428 case ISD::VP_LOAD: 3429 return lowerMaskedLoad(Op, DAG); 3430 case ISD::MSTORE: 3431 case ISD::VP_STORE: 3432 return lowerMaskedStore(Op, DAG); 3433 case ISD::SETCC: 3434 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3435 case ISD::ADD: 3436 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3437 case ISD::SUB: 3438 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3439 case ISD::MUL: 3440 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3441 case ISD::MULHS: 3442 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3443 case ISD::MULHU: 3444 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3445 case ISD::AND: 3446 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3447 RISCVISD::AND_VL); 3448 case ISD::OR: 3449 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3450 RISCVISD::OR_VL); 3451 case ISD::XOR: 3452 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3453 RISCVISD::XOR_VL); 3454 case ISD::SDIV: 3455 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3456 case ISD::SREM: 3457 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3458 case ISD::UDIV: 3459 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3460 case ISD::UREM: 3461 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3462 case ISD::SHL: 3463 case ISD::SRA: 3464 case ISD::SRL: 3465 if (Op.getSimpleValueType().isFixedLengthVector()) 3466 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3467 // This can be called for an i32 shift amount that needs to be promoted. 3468 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3469 "Unexpected custom legalisation"); 3470 return SDValue(); 3471 case ISD::SADDSAT: 3472 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3473 case ISD::UADDSAT: 3474 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3475 case ISD::SSUBSAT: 3476 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3477 case ISD::USUBSAT: 3478 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3479 case ISD::FADD: 3480 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3481 case ISD::FSUB: 3482 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3483 case ISD::FMUL: 3484 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3485 case ISD::FDIV: 3486 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3487 case ISD::FNEG: 3488 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3489 case ISD::FABS: 3490 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3491 case ISD::FSQRT: 3492 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3493 case ISD::FMA: 3494 return lowerToScalableOp(Op, DAG, RISCVISD::VFMADD_VL); 3495 case ISD::SMIN: 3496 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3497 case ISD::SMAX: 3498 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3499 case ISD::UMIN: 3500 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3501 case ISD::UMAX: 3502 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3503 case ISD::FMINNUM: 3504 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3505 case ISD::FMAXNUM: 3506 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3507 case ISD::ABS: 3508 return lowerABS(Op, DAG); 3509 case ISD::CTLZ_ZERO_UNDEF: 3510 case ISD::CTTZ_ZERO_UNDEF: 3511 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3512 case ISD::VSELECT: 3513 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3514 case ISD::FCOPYSIGN: 3515 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3516 case ISD::MGATHER: 3517 case ISD::VP_GATHER: 3518 return lowerMaskedGather(Op, DAG); 3519 case ISD::MSCATTER: 3520 case ISD::VP_SCATTER: 3521 return lowerMaskedScatter(Op, DAG); 3522 case ISD::FLT_ROUNDS_: 3523 return lowerGET_ROUNDING(Op, DAG); 3524 case ISD::SET_ROUNDING: 3525 return lowerSET_ROUNDING(Op, DAG); 3526 case ISD::EH_DWARF_CFA: 3527 return lowerEH_DWARF_CFA(Op, DAG); 3528 case ISD::VP_SELECT: 3529 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3530 case ISD::VP_MERGE: 3531 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3532 case ISD::VP_ADD: 3533 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3534 case ISD::VP_SUB: 3535 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3536 case ISD::VP_MUL: 3537 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3538 case ISD::VP_SDIV: 3539 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3540 case ISD::VP_UDIV: 3541 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3542 case ISD::VP_SREM: 3543 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3544 case ISD::VP_UREM: 3545 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3546 case ISD::VP_AND: 3547 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3548 case ISD::VP_OR: 3549 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3550 case ISD::VP_XOR: 3551 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3552 case ISD::VP_ASHR: 3553 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3554 case ISD::VP_LSHR: 3555 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3556 case ISD::VP_SHL: 3557 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3558 case ISD::VP_FADD: 3559 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3560 case ISD::VP_FSUB: 3561 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3562 case ISD::VP_FMUL: 3563 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3564 case ISD::VP_FDIV: 3565 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3566 case ISD::VP_FNEG: 3567 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3568 case ISD::VP_FMA: 3569 return lowerVPOp(Op, DAG, RISCVISD::VFMADD_VL); 3570 case ISD::VP_SIGN_EXTEND: 3571 case ISD::VP_ZERO_EXTEND: 3572 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3573 return lowerVPExtMaskOp(Op, DAG); 3574 return lowerVPOp(Op, DAG, 3575 Op.getOpcode() == ISD::VP_SIGN_EXTEND 3576 ? RISCVISD::VSEXT_VL 3577 : RISCVISD::VZEXT_VL); 3578 case ISD::VP_TRUNCATE: 3579 return lowerVectorTruncLike(Op, DAG); 3580 case ISD::VP_FP_EXTEND: 3581 case ISD::VP_FP_ROUND: 3582 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3583 case ISD::VP_FPTOSI: 3584 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL); 3585 case ISD::VP_FPTOUI: 3586 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL); 3587 case ISD::VP_SITOFP: 3588 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL); 3589 case ISD::VP_UITOFP: 3590 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL); 3591 case ISD::VP_SETCC: 3592 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3593 return lowerVPSetCCMaskOp(Op, DAG); 3594 return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL); 3595 } 3596 } 3597 3598 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3599 SelectionDAG &DAG, unsigned Flags) { 3600 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3601 } 3602 3603 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3604 SelectionDAG &DAG, unsigned Flags) { 3605 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3606 Flags); 3607 } 3608 3609 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3610 SelectionDAG &DAG, unsigned Flags) { 3611 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3612 N->getOffset(), Flags); 3613 } 3614 3615 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3616 SelectionDAG &DAG, unsigned Flags) { 3617 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3618 } 3619 3620 template <class NodeTy> 3621 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3622 bool IsLocal) const { 3623 SDLoc DL(N); 3624 EVT Ty = getPointerTy(DAG.getDataLayout()); 3625 3626 if (isPositionIndependent()) { 3627 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3628 if (IsLocal) 3629 // Use PC-relative addressing to access the symbol. This generates the 3630 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3631 // %pcrel_lo(auipc)). 3632 return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr); 3633 3634 // Use PC-relative addressing to access the GOT for this symbol, then load 3635 // the address from the GOT. This generates the pattern (PseudoLA sym), 3636 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3637 MachineFunction &MF = DAG.getMachineFunction(); 3638 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3639 MachinePointerInfo::getGOT(MF), 3640 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3641 MachineMemOperand::MOInvariant, 3642 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3643 SDValue Load = 3644 DAG.getMemIntrinsicNode(RISCVISD::LA, DL, DAG.getVTList(Ty, MVT::Other), 3645 {DAG.getEntryNode(), Addr}, Ty, MemOp); 3646 return Load; 3647 } 3648 3649 switch (getTargetMachine().getCodeModel()) { 3650 default: 3651 report_fatal_error("Unsupported code model for lowering"); 3652 case CodeModel::Small: { 3653 // Generate a sequence for accessing addresses within the first 2 GiB of 3654 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3655 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3656 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3657 SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi); 3658 return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNHi, AddrLo); 3659 } 3660 case CodeModel::Medium: { 3661 // Generate a sequence for accessing addresses within any 2GiB range within 3662 // the address space. This generates the pattern (PseudoLLA sym), which 3663 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3664 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3665 return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr); 3666 } 3667 } 3668 } 3669 3670 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3671 SelectionDAG &DAG) const { 3672 SDLoc DL(Op); 3673 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3674 assert(N->getOffset() == 0 && "unexpected offset in global node"); 3675 3676 const GlobalValue *GV = N->getGlobal(); 3677 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3678 return getAddr(N, DAG, IsLocal); 3679 } 3680 3681 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3682 SelectionDAG &DAG) const { 3683 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3684 3685 return getAddr(N, DAG); 3686 } 3687 3688 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3689 SelectionDAG &DAG) const { 3690 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3691 3692 return getAddr(N, DAG); 3693 } 3694 3695 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3696 SelectionDAG &DAG) const { 3697 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3698 3699 return getAddr(N, DAG); 3700 } 3701 3702 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3703 SelectionDAG &DAG, 3704 bool UseGOT) const { 3705 SDLoc DL(N); 3706 EVT Ty = getPointerTy(DAG.getDataLayout()); 3707 const GlobalValue *GV = N->getGlobal(); 3708 MVT XLenVT = Subtarget.getXLenVT(); 3709 3710 if (UseGOT) { 3711 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3712 // load the address from the GOT and add the thread pointer. This generates 3713 // the pattern (PseudoLA_TLS_IE sym), which expands to 3714 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3715 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3716 MachineFunction &MF = DAG.getMachineFunction(); 3717 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3718 MachinePointerInfo::getGOT(MF), 3719 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3720 MachineMemOperand::MOInvariant, 3721 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3722 SDValue Load = DAG.getMemIntrinsicNode( 3723 RISCVISD::LA_TLS_IE, DL, DAG.getVTList(Ty, MVT::Other), 3724 {DAG.getEntryNode(), Addr}, Ty, MemOp); 3725 3726 // Add the thread pointer. 3727 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3728 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3729 } 3730 3731 // Generate a sequence for accessing the address relative to the thread 3732 // pointer, with the appropriate adjustment for the thread pointer offset. 3733 // This generates the pattern 3734 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3735 SDValue AddrHi = 3736 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3737 SDValue AddrAdd = 3738 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3739 SDValue AddrLo = 3740 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3741 3742 SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi); 3743 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3744 SDValue MNAdd = 3745 DAG.getNode(RISCVISD::ADD_TPREL, DL, Ty, MNHi, TPReg, AddrAdd); 3746 return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNAdd, AddrLo); 3747 } 3748 3749 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3750 SelectionDAG &DAG) const { 3751 SDLoc DL(N); 3752 EVT Ty = getPointerTy(DAG.getDataLayout()); 3753 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3754 const GlobalValue *GV = N->getGlobal(); 3755 3756 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3757 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3758 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3759 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3760 SDValue Load = DAG.getNode(RISCVISD::LA_TLS_GD, DL, Ty, Addr); 3761 3762 // Prepare argument list to generate call. 3763 ArgListTy Args; 3764 ArgListEntry Entry; 3765 Entry.Node = Load; 3766 Entry.Ty = CallTy; 3767 Args.push_back(Entry); 3768 3769 // Setup call to __tls_get_addr. 3770 TargetLowering::CallLoweringInfo CLI(DAG); 3771 CLI.setDebugLoc(DL) 3772 .setChain(DAG.getEntryNode()) 3773 .setLibCallee(CallingConv::C, CallTy, 3774 DAG.getExternalSymbol("__tls_get_addr", Ty), 3775 std::move(Args)); 3776 3777 return LowerCallTo(CLI).first; 3778 } 3779 3780 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3781 SelectionDAG &DAG) const { 3782 SDLoc DL(Op); 3783 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3784 assert(N->getOffset() == 0 && "unexpected offset in global node"); 3785 3786 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3787 3788 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3789 CallingConv::GHC) 3790 report_fatal_error("In GHC calling convention TLS is not supported"); 3791 3792 SDValue Addr; 3793 switch (Model) { 3794 case TLSModel::LocalExec: 3795 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3796 break; 3797 case TLSModel::InitialExec: 3798 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3799 break; 3800 case TLSModel::LocalDynamic: 3801 case TLSModel::GeneralDynamic: 3802 Addr = getDynamicTLSAddr(N, DAG); 3803 break; 3804 } 3805 3806 return Addr; 3807 } 3808 3809 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3810 SDValue CondV = Op.getOperand(0); 3811 SDValue TrueV = Op.getOperand(1); 3812 SDValue FalseV = Op.getOperand(2); 3813 SDLoc DL(Op); 3814 MVT VT = Op.getSimpleValueType(); 3815 MVT XLenVT = Subtarget.getXLenVT(); 3816 3817 // Lower vector SELECTs to VSELECTs by splatting the condition. 3818 if (VT.isVector()) { 3819 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3820 SDValue CondSplat = VT.isScalableVector() 3821 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3822 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3823 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3824 } 3825 3826 // If the result type is XLenVT and CondV is the output of a SETCC node 3827 // which also operated on XLenVT inputs, then merge the SETCC node into the 3828 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3829 // compare+branch instructions. i.e.: 3830 // (select (setcc lhs, rhs, cc), truev, falsev) 3831 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3832 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3833 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3834 SDValue LHS = CondV.getOperand(0); 3835 SDValue RHS = CondV.getOperand(1); 3836 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3837 ISD::CondCode CCVal = CC->get(); 3838 3839 // Special case for a select of 2 constants that have a diffence of 1. 3840 // Normally this is done by DAGCombine, but if the select is introduced by 3841 // type legalization or op legalization, we miss it. Restricting to SETLT 3842 // case for now because that is what signed saturating add/sub need. 3843 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3844 // but we would probably want to swap the true/false values if the condition 3845 // is SETGE/SETLE to avoid an XORI. 3846 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3847 CCVal == ISD::SETLT) { 3848 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3849 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3850 if (TrueVal - 1 == FalseVal) 3851 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3852 if (TrueVal + 1 == FalseVal) 3853 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3854 } 3855 3856 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3857 3858 SDValue TargetCC = DAG.getCondCode(CCVal); 3859 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3860 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3861 } 3862 3863 // Otherwise: 3864 // (select condv, truev, falsev) 3865 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3866 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3867 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3868 3869 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3870 3871 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3872 } 3873 3874 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3875 SDValue CondV = Op.getOperand(1); 3876 SDLoc DL(Op); 3877 MVT XLenVT = Subtarget.getXLenVT(); 3878 3879 if (CondV.getOpcode() == ISD::SETCC && 3880 CondV.getOperand(0).getValueType() == XLenVT) { 3881 SDValue LHS = CondV.getOperand(0); 3882 SDValue RHS = CondV.getOperand(1); 3883 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3884 3885 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3886 3887 SDValue TargetCC = DAG.getCondCode(CCVal); 3888 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3889 LHS, RHS, TargetCC, Op.getOperand(2)); 3890 } 3891 3892 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3893 CondV, DAG.getConstant(0, DL, XLenVT), 3894 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3895 } 3896 3897 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3898 MachineFunction &MF = DAG.getMachineFunction(); 3899 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3900 3901 SDLoc DL(Op); 3902 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3903 getPointerTy(MF.getDataLayout())); 3904 3905 // vastart just stores the address of the VarArgsFrameIndex slot into the 3906 // memory location argument. 3907 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3908 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3909 MachinePointerInfo(SV)); 3910 } 3911 3912 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3913 SelectionDAG &DAG) const { 3914 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3915 MachineFunction &MF = DAG.getMachineFunction(); 3916 MachineFrameInfo &MFI = MF.getFrameInfo(); 3917 MFI.setFrameAddressIsTaken(true); 3918 Register FrameReg = RI.getFrameRegister(MF); 3919 int XLenInBytes = Subtarget.getXLen() / 8; 3920 3921 EVT VT = Op.getValueType(); 3922 SDLoc DL(Op); 3923 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3924 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3925 while (Depth--) { 3926 int Offset = -(XLenInBytes * 2); 3927 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3928 DAG.getIntPtrConstant(Offset, DL)); 3929 FrameAddr = 3930 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3931 } 3932 return FrameAddr; 3933 } 3934 3935 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3936 SelectionDAG &DAG) const { 3937 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3938 MachineFunction &MF = DAG.getMachineFunction(); 3939 MachineFrameInfo &MFI = MF.getFrameInfo(); 3940 MFI.setReturnAddressIsTaken(true); 3941 MVT XLenVT = Subtarget.getXLenVT(); 3942 int XLenInBytes = Subtarget.getXLen() / 8; 3943 3944 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3945 return SDValue(); 3946 3947 EVT VT = Op.getValueType(); 3948 SDLoc DL(Op); 3949 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3950 if (Depth) { 3951 int Off = -XLenInBytes; 3952 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3953 SDValue Offset = DAG.getConstant(Off, DL, VT); 3954 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3955 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3956 MachinePointerInfo()); 3957 } 3958 3959 // Return the value of the return address register, marking it an implicit 3960 // live-in. 3961 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3962 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3963 } 3964 3965 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3966 SelectionDAG &DAG) const { 3967 SDLoc DL(Op); 3968 SDValue Lo = Op.getOperand(0); 3969 SDValue Hi = Op.getOperand(1); 3970 SDValue Shamt = Op.getOperand(2); 3971 EVT VT = Lo.getValueType(); 3972 3973 // if Shamt-XLEN < 0: // Shamt < XLEN 3974 // Lo = Lo << Shamt 3975 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 3976 // else: 3977 // Lo = 0 3978 // Hi = Lo << (Shamt-XLEN) 3979 3980 SDValue Zero = DAG.getConstant(0, DL, VT); 3981 SDValue One = DAG.getConstant(1, DL, VT); 3982 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3983 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3984 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3985 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 3986 3987 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3988 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3989 SDValue ShiftRightLo = 3990 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3991 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3992 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3993 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3994 3995 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3996 3997 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3998 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3999 4000 SDValue Parts[2] = {Lo, Hi}; 4001 return DAG.getMergeValues(Parts, DL); 4002 } 4003 4004 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 4005 bool IsSRA) const { 4006 SDLoc DL(Op); 4007 SDValue Lo = Op.getOperand(0); 4008 SDValue Hi = Op.getOperand(1); 4009 SDValue Shamt = Op.getOperand(2); 4010 EVT VT = Lo.getValueType(); 4011 4012 // SRA expansion: 4013 // if Shamt-XLEN < 0: // Shamt < XLEN 4014 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4015 // Hi = Hi >>s Shamt 4016 // else: 4017 // Lo = Hi >>s (Shamt-XLEN); 4018 // Hi = Hi >>s (XLEN-1) 4019 // 4020 // SRL expansion: 4021 // if Shamt-XLEN < 0: // Shamt < XLEN 4022 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4023 // Hi = Hi >>u Shamt 4024 // else: 4025 // Lo = Hi >>u (Shamt-XLEN); 4026 // Hi = 0; 4027 4028 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 4029 4030 SDValue Zero = DAG.getConstant(0, DL, VT); 4031 SDValue One = DAG.getConstant(1, DL, VT); 4032 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4033 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4034 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4035 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4036 4037 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 4038 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 4039 SDValue ShiftLeftHi = 4040 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 4041 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 4042 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 4043 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 4044 SDValue HiFalse = 4045 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 4046 4047 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4048 4049 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 4050 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4051 4052 SDValue Parts[2] = {Lo, Hi}; 4053 return DAG.getMergeValues(Parts, DL); 4054 } 4055 4056 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 4057 // legal equivalently-sized i8 type, so we can use that as a go-between. 4058 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4059 SelectionDAG &DAG) const { 4060 SDLoc DL(Op); 4061 MVT VT = Op.getSimpleValueType(); 4062 SDValue SplatVal = Op.getOperand(0); 4063 // All-zeros or all-ones splats are handled specially. 4064 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4065 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4066 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4067 } 4068 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4069 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4070 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4071 } 4072 MVT XLenVT = Subtarget.getXLenVT(); 4073 assert(SplatVal.getValueType() == XLenVT && 4074 "Unexpected type for i1 splat value"); 4075 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4076 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4077 DAG.getConstant(1, DL, XLenVT)); 4078 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4079 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4080 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4081 } 4082 4083 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4084 // illegal (currently only vXi64 RV32). 4085 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4086 // them to VMV_V_X_VL. 4087 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4088 SelectionDAG &DAG) const { 4089 SDLoc DL(Op); 4090 MVT VecVT = Op.getSimpleValueType(); 4091 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4092 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4093 4094 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4095 SDValue Lo = Op.getOperand(0); 4096 SDValue Hi = Op.getOperand(1); 4097 4098 if (VecVT.isFixedLengthVector()) { 4099 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4100 SDLoc DL(Op); 4101 SDValue Mask, VL; 4102 std::tie(Mask, VL) = 4103 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4104 4105 SDValue Res = 4106 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4107 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4108 } 4109 4110 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4111 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4112 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4113 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4114 // node in order to try and match RVV vector/scalar instructions. 4115 if ((LoC >> 31) == HiC) 4116 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4117 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4118 } 4119 4120 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4121 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4122 isa<ConstantSDNode>(Hi.getOperand(1)) && 4123 Hi.getConstantOperandVal(1) == 31) 4124 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4125 DAG.getRegister(RISCV::X0, MVT::i32)); 4126 4127 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4128 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4129 DAG.getUNDEF(VecVT), Lo, Hi, 4130 DAG.getRegister(RISCV::X0, MVT::i32)); 4131 } 4132 4133 // Custom-lower extensions from mask vectors by using a vselect either with 1 4134 // for zero/any-extension or -1 for sign-extension: 4135 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4136 // Note that any-extension is lowered identically to zero-extension. 4137 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4138 int64_t ExtTrueVal) const { 4139 SDLoc DL(Op); 4140 MVT VecVT = Op.getSimpleValueType(); 4141 SDValue Src = Op.getOperand(0); 4142 // Only custom-lower extensions from mask types 4143 assert(Src.getValueType().isVector() && 4144 Src.getValueType().getVectorElementType() == MVT::i1); 4145 4146 if (VecVT.isScalableVector()) { 4147 SDValue SplatZero = DAG.getConstant(0, DL, VecVT); 4148 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT); 4149 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4150 } 4151 4152 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4153 MVT I1ContainerVT = 4154 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4155 4156 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4157 4158 SDValue Mask, VL; 4159 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4160 4161 MVT XLenVT = Subtarget.getXLenVT(); 4162 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4163 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4164 4165 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4166 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4167 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4168 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4169 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4170 SplatTrueVal, SplatZero, VL); 4171 4172 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4173 } 4174 4175 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4176 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4177 MVT ExtVT = Op.getSimpleValueType(); 4178 // Only custom-lower extensions from fixed-length vector types. 4179 if (!ExtVT.isFixedLengthVector()) 4180 return Op; 4181 MVT VT = Op.getOperand(0).getSimpleValueType(); 4182 // Grab the canonical container type for the extended type. Infer the smaller 4183 // type from that to ensure the same number of vector elements, as we know 4184 // the LMUL will be sufficient to hold the smaller type. 4185 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4186 // Get the extended container type manually to ensure the same number of 4187 // vector elements between source and dest. 4188 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4189 ContainerExtVT.getVectorElementCount()); 4190 4191 SDValue Op1 = 4192 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4193 4194 SDLoc DL(Op); 4195 SDValue Mask, VL; 4196 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4197 4198 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4199 4200 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4201 } 4202 4203 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4204 // setcc operation: 4205 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4206 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op, 4207 SelectionDAG &DAG) const { 4208 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4209 SDLoc DL(Op); 4210 EVT MaskVT = Op.getValueType(); 4211 // Only expect to custom-lower truncations to mask types 4212 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4213 "Unexpected type for vector mask lowering"); 4214 SDValue Src = Op.getOperand(0); 4215 MVT VecVT = Src.getSimpleValueType(); 4216 SDValue Mask, VL; 4217 if (IsVPTrunc) { 4218 Mask = Op.getOperand(1); 4219 VL = Op.getOperand(2); 4220 } 4221 // If this is a fixed vector, we need to convert it to a scalable vector. 4222 MVT ContainerVT = VecVT; 4223 4224 if (VecVT.isFixedLengthVector()) { 4225 ContainerVT = getContainerForFixedLengthVector(VecVT); 4226 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4227 if (IsVPTrunc) { 4228 MVT MaskContainerVT = 4229 getContainerForFixedLengthVector(Mask.getSimpleValueType()); 4230 Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget); 4231 } 4232 } 4233 4234 if (!IsVPTrunc) { 4235 std::tie(Mask, VL) = 4236 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4237 } 4238 4239 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4240 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4241 4242 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4243 DAG.getUNDEF(ContainerVT), SplatOne, VL); 4244 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4245 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4246 4247 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4248 SDValue Trunc = 4249 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4250 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4251 DAG.getCondCode(ISD::SETNE), Mask, VL); 4252 if (MaskVT.isFixedLengthVector()) 4253 Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4254 return Trunc; 4255 } 4256 4257 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op, 4258 SelectionDAG &DAG) const { 4259 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4260 SDLoc DL(Op); 4261 4262 MVT VT = Op.getSimpleValueType(); 4263 // Only custom-lower vector truncates 4264 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4265 4266 // Truncates to mask types are handled differently 4267 if (VT.getVectorElementType() == MVT::i1) 4268 return lowerVectorMaskTruncLike(Op, DAG); 4269 4270 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 4271 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 4272 // truncate by one power of two at a time. 4273 MVT DstEltVT = VT.getVectorElementType(); 4274 4275 SDValue Src = Op.getOperand(0); 4276 MVT SrcVT = Src.getSimpleValueType(); 4277 MVT SrcEltVT = SrcVT.getVectorElementType(); 4278 4279 assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) && 4280 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 4281 "Unexpected vector truncate lowering"); 4282 4283 MVT ContainerVT = SrcVT; 4284 SDValue Mask, VL; 4285 if (IsVPTrunc) { 4286 Mask = Op.getOperand(1); 4287 VL = Op.getOperand(2); 4288 } 4289 if (SrcVT.isFixedLengthVector()) { 4290 ContainerVT = getContainerForFixedLengthVector(SrcVT); 4291 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4292 if (IsVPTrunc) { 4293 MVT MaskVT = getMaskTypeFor(ContainerVT); 4294 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4295 } 4296 } 4297 4298 SDValue Result = Src; 4299 if (!IsVPTrunc) { 4300 std::tie(Mask, VL) = 4301 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4302 } 4303 4304 LLVMContext &Context = *DAG.getContext(); 4305 const ElementCount Count = ContainerVT.getVectorElementCount(); 4306 do { 4307 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 4308 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 4309 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 4310 Mask, VL); 4311 } while (SrcEltVT != DstEltVT); 4312 4313 if (SrcVT.isFixedLengthVector()) 4314 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4315 4316 return Result; 4317 } 4318 4319 SDValue 4320 RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op, 4321 SelectionDAG &DAG) const { 4322 bool IsVP = 4323 Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND; 4324 bool IsExtend = 4325 Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND; 4326 // RVV can only do truncate fp to types half the size as the source. We 4327 // custom-lower f64->f16 rounds via RVV's round-to-odd float 4328 // conversion instruction. 4329 SDLoc DL(Op); 4330 MVT VT = Op.getSimpleValueType(); 4331 4332 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4333 4334 SDValue Src = Op.getOperand(0); 4335 MVT SrcVT = Src.getSimpleValueType(); 4336 4337 bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 || 4338 SrcVT.getVectorElementType() != MVT::f16); 4339 bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 || 4340 SrcVT.getVectorElementType() != MVT::f64); 4341 4342 bool IsDirectConv = IsDirectExtend || IsDirectTrunc; 4343 4344 // Prepare any fixed-length vector operands. 4345 MVT ContainerVT = VT; 4346 SDValue Mask, VL; 4347 if (IsVP) { 4348 Mask = Op.getOperand(1); 4349 VL = Op.getOperand(2); 4350 } 4351 if (VT.isFixedLengthVector()) { 4352 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 4353 ContainerVT = 4354 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 4355 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 4356 if (IsVP) { 4357 MVT MaskVT = getMaskTypeFor(ContainerVT); 4358 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4359 } 4360 } 4361 4362 if (!IsVP) 4363 std::tie(Mask, VL) = 4364 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4365 4366 unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL; 4367 4368 if (IsDirectConv) { 4369 Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL); 4370 if (VT.isFixedLengthVector()) 4371 Src = convertFromScalableVector(VT, Src, DAG, Subtarget); 4372 return Src; 4373 } 4374 4375 unsigned InterConvOpc = 4376 IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL; 4377 4378 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 4379 SDValue IntermediateConv = 4380 DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL); 4381 SDValue Result = 4382 DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL); 4383 if (VT.isFixedLengthVector()) 4384 return convertFromScalableVector(VT, Result, DAG, Subtarget); 4385 return Result; 4386 } 4387 4388 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4389 // first position of a vector, and that vector is slid up to the insert index. 4390 // By limiting the active vector length to index+1 and merging with the 4391 // original vector (with an undisturbed tail policy for elements >= VL), we 4392 // achieve the desired result of leaving all elements untouched except the one 4393 // at VL-1, which is replaced with the desired value. 4394 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4395 SelectionDAG &DAG) const { 4396 SDLoc DL(Op); 4397 MVT VecVT = Op.getSimpleValueType(); 4398 SDValue Vec = Op.getOperand(0); 4399 SDValue Val = Op.getOperand(1); 4400 SDValue Idx = Op.getOperand(2); 4401 4402 if (VecVT.getVectorElementType() == MVT::i1) { 4403 // FIXME: For now we just promote to an i8 vector and insert into that, 4404 // but this is probably not optimal. 4405 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4406 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4407 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4408 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4409 } 4410 4411 MVT ContainerVT = VecVT; 4412 // If the operand is a fixed-length vector, convert to a scalable one. 4413 if (VecVT.isFixedLengthVector()) { 4414 ContainerVT = getContainerForFixedLengthVector(VecVT); 4415 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4416 } 4417 4418 MVT XLenVT = Subtarget.getXLenVT(); 4419 4420 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4421 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4422 // Even i64-element vectors on RV32 can be lowered without scalar 4423 // legalization if the most-significant 32 bits of the value are not affected 4424 // by the sign-extension of the lower 32 bits. 4425 // TODO: We could also catch sign extensions of a 32-bit value. 4426 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4427 const auto *CVal = cast<ConstantSDNode>(Val); 4428 if (isInt<32>(CVal->getSExtValue())) { 4429 IsLegalInsert = true; 4430 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4431 } 4432 } 4433 4434 SDValue Mask, VL; 4435 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4436 4437 SDValue ValInVec; 4438 4439 if (IsLegalInsert) { 4440 unsigned Opc = 4441 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4442 if (isNullConstant(Idx)) { 4443 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4444 if (!VecVT.isFixedLengthVector()) 4445 return Vec; 4446 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4447 } 4448 ValInVec = 4449 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4450 } else { 4451 // On RV32, i64-element vectors must be specially handled to place the 4452 // value at element 0, by using two vslide1up instructions in sequence on 4453 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4454 // this. 4455 SDValue One = DAG.getConstant(1, DL, XLenVT); 4456 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4457 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4458 MVT I32ContainerVT = 4459 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4460 SDValue I32Mask = 4461 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4462 // Limit the active VL to two. 4463 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4464 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4465 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4466 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4467 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4468 // First slide in the hi value, then the lo in underneath it. 4469 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4470 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4471 I32Mask, InsertI64VL); 4472 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4473 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4474 I32Mask, InsertI64VL); 4475 // Bitcast back to the right container type. 4476 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4477 } 4478 4479 // Now that the value is in a vector, slide it into position. 4480 SDValue InsertVL = 4481 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4482 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4483 ValInVec, Idx, Mask, InsertVL); 4484 if (!VecVT.isFixedLengthVector()) 4485 return Slideup; 4486 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4487 } 4488 4489 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4490 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4491 // types this is done using VMV_X_S to allow us to glean information about the 4492 // sign bits of the result. 4493 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4494 SelectionDAG &DAG) const { 4495 SDLoc DL(Op); 4496 SDValue Idx = Op.getOperand(1); 4497 SDValue Vec = Op.getOperand(0); 4498 EVT EltVT = Op.getValueType(); 4499 MVT VecVT = Vec.getSimpleValueType(); 4500 MVT XLenVT = Subtarget.getXLenVT(); 4501 4502 if (VecVT.getVectorElementType() == MVT::i1) { 4503 if (VecVT.isFixedLengthVector()) { 4504 unsigned NumElts = VecVT.getVectorNumElements(); 4505 if (NumElts >= 8) { 4506 MVT WideEltVT; 4507 unsigned WidenVecLen; 4508 SDValue ExtractElementIdx; 4509 SDValue ExtractBitIdx; 4510 unsigned MaxEEW = Subtarget.getELEN(); 4511 MVT LargestEltVT = MVT::getIntegerVT( 4512 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4513 if (NumElts <= LargestEltVT.getSizeInBits()) { 4514 assert(isPowerOf2_32(NumElts) && 4515 "the number of elements should be power of 2"); 4516 WideEltVT = MVT::getIntegerVT(NumElts); 4517 WidenVecLen = 1; 4518 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4519 ExtractBitIdx = Idx; 4520 } else { 4521 WideEltVT = LargestEltVT; 4522 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4523 // extract element index = index / element width 4524 ExtractElementIdx = DAG.getNode( 4525 ISD::SRL, DL, XLenVT, Idx, 4526 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4527 // mask bit index = index % element width 4528 ExtractBitIdx = DAG.getNode( 4529 ISD::AND, DL, XLenVT, Idx, 4530 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4531 } 4532 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4533 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4534 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4535 Vec, ExtractElementIdx); 4536 // Extract the bit from GPR. 4537 SDValue ShiftRight = 4538 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4539 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4540 DAG.getConstant(1, DL, XLenVT)); 4541 } 4542 } 4543 // Otherwise, promote to an i8 vector and extract from that. 4544 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4545 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4546 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4547 } 4548 4549 // If this is a fixed vector, we need to convert it to a scalable vector. 4550 MVT ContainerVT = VecVT; 4551 if (VecVT.isFixedLengthVector()) { 4552 ContainerVT = getContainerForFixedLengthVector(VecVT); 4553 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4554 } 4555 4556 // If the index is 0, the vector is already in the right position. 4557 if (!isNullConstant(Idx)) { 4558 // Use a VL of 1 to avoid processing more elements than we need. 4559 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4560 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 4561 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4562 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4563 } 4564 4565 if (!EltVT.isInteger()) { 4566 // Floating-point extracts are handled in TableGen. 4567 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4568 DAG.getConstant(0, DL, XLenVT)); 4569 } 4570 4571 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4572 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4573 } 4574 4575 // Some RVV intrinsics may claim that they want an integer operand to be 4576 // promoted or expanded. 4577 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG, 4578 const RISCVSubtarget &Subtarget) { 4579 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4580 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4581 "Unexpected opcode"); 4582 4583 if (!Subtarget.hasVInstructions()) 4584 return SDValue(); 4585 4586 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4587 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4588 SDLoc DL(Op); 4589 4590 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4591 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4592 if (!II || !II->hasScalarOperand()) 4593 return SDValue(); 4594 4595 unsigned SplatOp = II->ScalarOperand + 1 + HasChain; 4596 assert(SplatOp < Op.getNumOperands()); 4597 4598 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4599 SDValue &ScalarOp = Operands[SplatOp]; 4600 MVT OpVT = ScalarOp.getSimpleValueType(); 4601 MVT XLenVT = Subtarget.getXLenVT(); 4602 4603 // If this isn't a scalar, or its type is XLenVT we're done. 4604 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4605 return SDValue(); 4606 4607 // Simplest case is that the operand needs to be promoted to XLenVT. 4608 if (OpVT.bitsLT(XLenVT)) { 4609 // If the operand is a constant, sign extend to increase our chances 4610 // of being able to use a .vi instruction. ANY_EXTEND would become a 4611 // a zero extend and the simm5 check in isel would fail. 4612 // FIXME: Should we ignore the upper bits in isel instead? 4613 unsigned ExtOpc = 4614 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4615 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4616 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4617 } 4618 4619 // Use the previous operand to get the vXi64 VT. The result might be a mask 4620 // VT for compares. Using the previous operand assumes that the previous 4621 // operand will never have a smaller element size than a scalar operand and 4622 // that a widening operation never uses SEW=64. 4623 // NOTE: If this fails the below assert, we can probably just find the 4624 // element count from any operand or result and use it to construct the VT. 4625 assert(II->ScalarOperand > 0 && "Unexpected splat operand!"); 4626 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4627 4628 // The more complex case is when the scalar is larger than XLenVT. 4629 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4630 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4631 4632 // If this is a sign-extended 32-bit value, we can truncate it and rely on the 4633 // instruction to sign-extend since SEW>XLEN. 4634 if (DAG.ComputeNumSignBits(ScalarOp) > 32) { 4635 ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp); 4636 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4637 } 4638 4639 switch (IntNo) { 4640 case Intrinsic::riscv_vslide1up: 4641 case Intrinsic::riscv_vslide1down: 4642 case Intrinsic::riscv_vslide1up_mask: 4643 case Intrinsic::riscv_vslide1down_mask: { 4644 // We need to special case these when the scalar is larger than XLen. 4645 unsigned NumOps = Op.getNumOperands(); 4646 bool IsMasked = NumOps == 7; 4647 4648 // Convert the vector source to the equivalent nxvXi32 vector. 4649 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4650 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4651 4652 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4653 DAG.getConstant(0, DL, XLenVT)); 4654 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4655 DAG.getConstant(1, DL, XLenVT)); 4656 4657 // Double the VL since we halved SEW. 4658 SDValue AVL = getVLOperand(Op); 4659 SDValue I32VL; 4660 4661 // Optimize for constant AVL 4662 if (isa<ConstantSDNode>(AVL)) { 4663 unsigned EltSize = VT.getScalarSizeInBits(); 4664 unsigned MinSize = VT.getSizeInBits().getKnownMinValue(); 4665 4666 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 4667 unsigned MaxVLMAX = 4668 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 4669 4670 unsigned VectorBitsMin = Subtarget.getRealMinVLen(); 4671 unsigned MinVLMAX = 4672 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize); 4673 4674 uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue(); 4675 if (AVLInt <= MinVLMAX) { 4676 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT); 4677 } else if (AVLInt >= 2 * MaxVLMAX) { 4678 // Just set vl to VLMAX in this situation 4679 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT); 4680 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4681 unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits()); 4682 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4683 SDValue SETVLMAX = DAG.getTargetConstant( 4684 Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32); 4685 I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW, 4686 LMUL); 4687 } else { 4688 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl 4689 // is related to the hardware implementation. 4690 // So let the following code handle 4691 } 4692 } 4693 if (!I32VL) { 4694 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT); 4695 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4696 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits()); 4697 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4698 SDValue SETVL = 4699 DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32); 4700 // Using vsetvli instruction to get actually used length which related to 4701 // the hardware implementation 4702 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL, 4703 SEW, LMUL); 4704 I32VL = 4705 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4706 } 4707 4708 SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG); 4709 4710 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4711 // instructions. 4712 SDValue Passthru; 4713 if (IsMasked) 4714 Passthru = DAG.getUNDEF(I32VT); 4715 else 4716 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4717 4718 if (IntNo == Intrinsic::riscv_vslide1up || 4719 IntNo == Intrinsic::riscv_vslide1up_mask) { 4720 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4721 ScalarHi, I32Mask, I32VL); 4722 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4723 ScalarLo, I32Mask, I32VL); 4724 } else { 4725 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4726 ScalarLo, I32Mask, I32VL); 4727 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4728 ScalarHi, I32Mask, I32VL); 4729 } 4730 4731 // Convert back to nxvXi64. 4732 Vec = DAG.getBitcast(VT, Vec); 4733 4734 if (!IsMasked) 4735 return Vec; 4736 // Apply mask after the operation. 4737 SDValue Mask = Operands[NumOps - 3]; 4738 SDValue MaskedOff = Operands[1]; 4739 // Assume Policy operand is the last operand. 4740 uint64_t Policy = 4741 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4742 // We don't need to select maskedoff if it's undef. 4743 if (MaskedOff.isUndef()) 4744 return Vec; 4745 // TAMU 4746 if (Policy == RISCVII::TAIL_AGNOSTIC) 4747 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4748 AVL); 4749 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4750 // It's fine because vmerge does not care mask policy. 4751 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, 4752 AVL); 4753 } 4754 } 4755 4756 // We need to convert the scalar to a splat vector. 4757 SDValue VL = getVLOperand(Op); 4758 assert(VL.getValueType() == XLenVT); 4759 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4760 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4761 } 4762 4763 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4764 SelectionDAG &DAG) const { 4765 unsigned IntNo = Op.getConstantOperandVal(0); 4766 SDLoc DL(Op); 4767 MVT XLenVT = Subtarget.getXLenVT(); 4768 4769 switch (IntNo) { 4770 default: 4771 break; // Don't custom lower most intrinsics. 4772 case Intrinsic::thread_pointer: { 4773 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4774 return DAG.getRegister(RISCV::X4, PtrVT); 4775 } 4776 case Intrinsic::riscv_orc_b: 4777 case Intrinsic::riscv_brev8: { 4778 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4779 unsigned Opc = 4780 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4781 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4782 DAG.getConstant(7, DL, XLenVT)); 4783 } 4784 case Intrinsic::riscv_grev: 4785 case Intrinsic::riscv_gorc: { 4786 unsigned Opc = 4787 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4788 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4789 } 4790 case Intrinsic::riscv_zip: 4791 case Intrinsic::riscv_unzip: { 4792 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4793 // For i32 the immediate is 15. For i64 the immediate is 31. 4794 unsigned Opc = 4795 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4796 unsigned BitWidth = Op.getValueSizeInBits(); 4797 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4798 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4799 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4800 } 4801 case Intrinsic::riscv_shfl: 4802 case Intrinsic::riscv_unshfl: { 4803 unsigned Opc = 4804 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4805 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4806 } 4807 case Intrinsic::riscv_bcompress: 4808 case Intrinsic::riscv_bdecompress: { 4809 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4810 : RISCVISD::BDECOMPRESS; 4811 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4812 } 4813 case Intrinsic::riscv_bfp: 4814 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4815 Op.getOperand(2)); 4816 case Intrinsic::riscv_fsl: 4817 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4818 Op.getOperand(2), Op.getOperand(3)); 4819 case Intrinsic::riscv_fsr: 4820 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4821 Op.getOperand(2), Op.getOperand(3)); 4822 case Intrinsic::riscv_vmv_x_s: 4823 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4824 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4825 Op.getOperand(1)); 4826 case Intrinsic::riscv_vmv_v_x: 4827 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4828 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4829 Subtarget); 4830 case Intrinsic::riscv_vfmv_v_f: 4831 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4832 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4833 case Intrinsic::riscv_vmv_s_x: { 4834 SDValue Scalar = Op.getOperand(2); 4835 4836 if (Scalar.getValueType().bitsLE(XLenVT)) { 4837 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4838 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4839 Op.getOperand(1), Scalar, Op.getOperand(3)); 4840 } 4841 4842 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4843 4844 // This is an i64 value that lives in two scalar registers. We have to 4845 // insert this in a convoluted way. First we build vXi64 splat containing 4846 // the two values that we assemble using some bit math. Next we'll use 4847 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4848 // to merge element 0 from our splat into the source vector. 4849 // FIXME: This is probably not the best way to do this, but it is 4850 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4851 // point. 4852 // sw lo, (a0) 4853 // sw hi, 4(a0) 4854 // vlse vX, (a0) 4855 // 4856 // vid.v vVid 4857 // vmseq.vx mMask, vVid, 0 4858 // vmerge.vvm vDest, vSrc, vVal, mMask 4859 MVT VT = Op.getSimpleValueType(); 4860 SDValue Vec = Op.getOperand(1); 4861 SDValue VL = getVLOperand(Op); 4862 4863 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4864 if (Op.getOperand(1).isUndef()) 4865 return SplattedVal; 4866 SDValue SplattedIdx = 4867 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4868 DAG.getConstant(0, DL, MVT::i32), VL); 4869 4870 MVT MaskVT = getMaskTypeFor(VT); 4871 SDValue Mask = getAllOnesMask(VT, VL, DL, DAG); 4872 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4873 SDValue SelectCond = 4874 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4875 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4876 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4877 Vec, VL); 4878 } 4879 } 4880 4881 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4882 } 4883 4884 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4885 SelectionDAG &DAG) const { 4886 unsigned IntNo = Op.getConstantOperandVal(1); 4887 switch (IntNo) { 4888 default: 4889 break; 4890 case Intrinsic::riscv_masked_strided_load: { 4891 SDLoc DL(Op); 4892 MVT XLenVT = Subtarget.getXLenVT(); 4893 4894 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4895 // the selection of the masked intrinsics doesn't do this for us. 4896 SDValue Mask = Op.getOperand(5); 4897 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4898 4899 MVT VT = Op->getSimpleValueType(0); 4900 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4901 4902 SDValue PassThru = Op.getOperand(2); 4903 if (!IsUnmasked) { 4904 MVT MaskVT = getMaskTypeFor(ContainerVT); 4905 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4906 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4907 } 4908 4909 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4910 4911 SDValue IntID = DAG.getTargetConstant( 4912 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4913 XLenVT); 4914 4915 auto *Load = cast<MemIntrinsicSDNode>(Op); 4916 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4917 if (IsUnmasked) 4918 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4919 else 4920 Ops.push_back(PassThru); 4921 Ops.push_back(Op.getOperand(3)); // Ptr 4922 Ops.push_back(Op.getOperand(4)); // Stride 4923 if (!IsUnmasked) 4924 Ops.push_back(Mask); 4925 Ops.push_back(VL); 4926 if (!IsUnmasked) { 4927 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4928 Ops.push_back(Policy); 4929 } 4930 4931 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4932 SDValue Result = 4933 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4934 Load->getMemoryVT(), Load->getMemOperand()); 4935 SDValue Chain = Result.getValue(1); 4936 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4937 return DAG.getMergeValues({Result, Chain}, DL); 4938 } 4939 case Intrinsic::riscv_seg2_load: 4940 case Intrinsic::riscv_seg3_load: 4941 case Intrinsic::riscv_seg4_load: 4942 case Intrinsic::riscv_seg5_load: 4943 case Intrinsic::riscv_seg6_load: 4944 case Intrinsic::riscv_seg7_load: 4945 case Intrinsic::riscv_seg8_load: { 4946 SDLoc DL(Op); 4947 static const Intrinsic::ID VlsegInts[7] = { 4948 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 4949 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 4950 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 4951 Intrinsic::riscv_vlseg8}; 4952 unsigned NF = Op->getNumValues() - 1; 4953 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 4954 MVT XLenVT = Subtarget.getXLenVT(); 4955 MVT VT = Op->getSimpleValueType(0); 4956 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4957 4958 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4959 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 4960 auto *Load = cast<MemIntrinsicSDNode>(Op); 4961 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 4962 ContainerVTs.push_back(MVT::Other); 4963 SDVTList VTs = DAG.getVTList(ContainerVTs); 4964 SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID}; 4965 Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT)); 4966 Ops.push_back(Op.getOperand(2)); 4967 Ops.push_back(VL); 4968 SDValue Result = 4969 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4970 Load->getMemoryVT(), Load->getMemOperand()); 4971 SmallVector<SDValue, 9> Results; 4972 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 4973 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 4974 DAG, Subtarget)); 4975 Results.push_back(Result.getValue(NF)); 4976 return DAG.getMergeValues(Results, DL); 4977 } 4978 } 4979 4980 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4981 } 4982 4983 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4984 SelectionDAG &DAG) const { 4985 unsigned IntNo = Op.getConstantOperandVal(1); 4986 switch (IntNo) { 4987 default: 4988 break; 4989 case Intrinsic::riscv_masked_strided_store: { 4990 SDLoc DL(Op); 4991 MVT XLenVT = Subtarget.getXLenVT(); 4992 4993 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4994 // the selection of the masked intrinsics doesn't do this for us. 4995 SDValue Mask = Op.getOperand(5); 4996 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4997 4998 SDValue Val = Op.getOperand(2); 4999 MVT VT = Val.getSimpleValueType(); 5000 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5001 5002 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5003 if (!IsUnmasked) { 5004 MVT MaskVT = getMaskTypeFor(ContainerVT); 5005 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5006 } 5007 5008 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5009 5010 SDValue IntID = DAG.getTargetConstant( 5011 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 5012 XLenVT); 5013 5014 auto *Store = cast<MemIntrinsicSDNode>(Op); 5015 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 5016 Ops.push_back(Val); 5017 Ops.push_back(Op.getOperand(3)); // Ptr 5018 Ops.push_back(Op.getOperand(4)); // Stride 5019 if (!IsUnmasked) 5020 Ops.push_back(Mask); 5021 Ops.push_back(VL); 5022 5023 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 5024 Ops, Store->getMemoryVT(), 5025 Store->getMemOperand()); 5026 } 5027 } 5028 5029 return SDValue(); 5030 } 5031 5032 static MVT getLMUL1VT(MVT VT) { 5033 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 5034 "Unexpected vector MVT"); 5035 return MVT::getScalableVectorVT( 5036 VT.getVectorElementType(), 5037 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 5038 } 5039 5040 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 5041 switch (ISDOpcode) { 5042 default: 5043 llvm_unreachable("Unhandled reduction"); 5044 case ISD::VECREDUCE_ADD: 5045 return RISCVISD::VECREDUCE_ADD_VL; 5046 case ISD::VECREDUCE_UMAX: 5047 return RISCVISD::VECREDUCE_UMAX_VL; 5048 case ISD::VECREDUCE_SMAX: 5049 return RISCVISD::VECREDUCE_SMAX_VL; 5050 case ISD::VECREDUCE_UMIN: 5051 return RISCVISD::VECREDUCE_UMIN_VL; 5052 case ISD::VECREDUCE_SMIN: 5053 return RISCVISD::VECREDUCE_SMIN_VL; 5054 case ISD::VECREDUCE_AND: 5055 return RISCVISD::VECREDUCE_AND_VL; 5056 case ISD::VECREDUCE_OR: 5057 return RISCVISD::VECREDUCE_OR_VL; 5058 case ISD::VECREDUCE_XOR: 5059 return RISCVISD::VECREDUCE_XOR_VL; 5060 } 5061 } 5062 5063 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 5064 SelectionDAG &DAG, 5065 bool IsVP) const { 5066 SDLoc DL(Op); 5067 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 5068 MVT VecVT = Vec.getSimpleValueType(); 5069 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 5070 Op.getOpcode() == ISD::VECREDUCE_OR || 5071 Op.getOpcode() == ISD::VECREDUCE_XOR || 5072 Op.getOpcode() == ISD::VP_REDUCE_AND || 5073 Op.getOpcode() == ISD::VP_REDUCE_OR || 5074 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5075 "Unexpected reduction lowering"); 5076 5077 MVT XLenVT = Subtarget.getXLenVT(); 5078 assert(Op.getValueType() == XLenVT && 5079 "Expected reduction output to be legalized to XLenVT"); 5080 5081 MVT ContainerVT = VecVT; 5082 if (VecVT.isFixedLengthVector()) { 5083 ContainerVT = getContainerForFixedLengthVector(VecVT); 5084 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5085 } 5086 5087 SDValue Mask, VL; 5088 if (IsVP) { 5089 Mask = Op.getOperand(2); 5090 VL = Op.getOperand(3); 5091 } else { 5092 std::tie(Mask, VL) = 5093 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5094 } 5095 5096 unsigned BaseOpc; 5097 ISD::CondCode CC; 5098 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5099 5100 switch (Op.getOpcode()) { 5101 default: 5102 llvm_unreachable("Unhandled reduction"); 5103 case ISD::VECREDUCE_AND: 5104 case ISD::VP_REDUCE_AND: { 5105 // vcpop ~x == 0 5106 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5107 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5108 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5109 CC = ISD::SETEQ; 5110 BaseOpc = ISD::AND; 5111 break; 5112 } 5113 case ISD::VECREDUCE_OR: 5114 case ISD::VP_REDUCE_OR: 5115 // vcpop x != 0 5116 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5117 CC = ISD::SETNE; 5118 BaseOpc = ISD::OR; 5119 break; 5120 case ISD::VECREDUCE_XOR: 5121 case ISD::VP_REDUCE_XOR: { 5122 // ((vcpop x) & 1) != 0 5123 SDValue One = DAG.getConstant(1, DL, XLenVT); 5124 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5125 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5126 CC = ISD::SETNE; 5127 BaseOpc = ISD::XOR; 5128 break; 5129 } 5130 } 5131 5132 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5133 5134 if (!IsVP) 5135 return SetCC; 5136 5137 // Now include the start value in the operation. 5138 // Note that we must return the start value when no elements are operated 5139 // upon. The vcpop instructions we've emitted in each case above will return 5140 // 0 for an inactive vector, and so we've already received the neutral value: 5141 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5142 // can simply include the start value. 5143 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5144 } 5145 5146 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5147 SelectionDAG &DAG) const { 5148 SDLoc DL(Op); 5149 SDValue Vec = Op.getOperand(0); 5150 EVT VecEVT = Vec.getValueType(); 5151 5152 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5153 5154 // Due to ordering in legalize types we may have a vector type that needs to 5155 // be split. Do that manually so we can get down to a legal type. 5156 while (getTypeAction(*DAG.getContext(), VecEVT) == 5157 TargetLowering::TypeSplitVector) { 5158 SDValue Lo, Hi; 5159 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5160 VecEVT = Lo.getValueType(); 5161 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5162 } 5163 5164 // TODO: The type may need to be widened rather than split. Or widened before 5165 // it can be split. 5166 if (!isTypeLegal(VecEVT)) 5167 return SDValue(); 5168 5169 MVT VecVT = VecEVT.getSimpleVT(); 5170 MVT VecEltVT = VecVT.getVectorElementType(); 5171 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5172 5173 MVT ContainerVT = VecVT; 5174 if (VecVT.isFixedLengthVector()) { 5175 ContainerVT = getContainerForFixedLengthVector(VecVT); 5176 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5177 } 5178 5179 MVT M1VT = getLMUL1VT(ContainerVT); 5180 MVT XLenVT = Subtarget.getXLenVT(); 5181 5182 SDValue Mask, VL; 5183 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5184 5185 SDValue NeutralElem = 5186 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5187 SDValue IdentitySplat = 5188 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5189 M1VT, DL, DAG, Subtarget); 5190 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5191 IdentitySplat, Mask, VL); 5192 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5193 DAG.getConstant(0, DL, XLenVT)); 5194 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5195 } 5196 5197 // Given a reduction op, this function returns the matching reduction opcode, 5198 // the vector SDValue and the scalar SDValue required to lower this to a 5199 // RISCVISD node. 5200 static std::tuple<unsigned, SDValue, SDValue> 5201 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5202 SDLoc DL(Op); 5203 auto Flags = Op->getFlags(); 5204 unsigned Opcode = Op.getOpcode(); 5205 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5206 switch (Opcode) { 5207 default: 5208 llvm_unreachable("Unhandled reduction"); 5209 case ISD::VECREDUCE_FADD: { 5210 // Use positive zero if we can. It is cheaper to materialize. 5211 SDValue Zero = 5212 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5213 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5214 } 5215 case ISD::VECREDUCE_SEQ_FADD: 5216 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5217 Op.getOperand(0)); 5218 case ISD::VECREDUCE_FMIN: 5219 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5220 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5221 case ISD::VECREDUCE_FMAX: 5222 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5223 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5224 } 5225 } 5226 5227 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5228 SelectionDAG &DAG) const { 5229 SDLoc DL(Op); 5230 MVT VecEltVT = Op.getSimpleValueType(); 5231 5232 unsigned RVVOpcode; 5233 SDValue VectorVal, ScalarVal; 5234 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5235 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5236 MVT VecVT = VectorVal.getSimpleValueType(); 5237 5238 MVT ContainerVT = VecVT; 5239 if (VecVT.isFixedLengthVector()) { 5240 ContainerVT = getContainerForFixedLengthVector(VecVT); 5241 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5242 } 5243 5244 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5245 MVT XLenVT = Subtarget.getXLenVT(); 5246 5247 SDValue Mask, VL; 5248 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5249 5250 SDValue ScalarSplat = 5251 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5252 M1VT, DL, DAG, Subtarget); 5253 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5254 VectorVal, ScalarSplat, Mask, VL); 5255 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5256 DAG.getConstant(0, DL, XLenVT)); 5257 } 5258 5259 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5260 switch (ISDOpcode) { 5261 default: 5262 llvm_unreachable("Unhandled reduction"); 5263 case ISD::VP_REDUCE_ADD: 5264 return RISCVISD::VECREDUCE_ADD_VL; 5265 case ISD::VP_REDUCE_UMAX: 5266 return RISCVISD::VECREDUCE_UMAX_VL; 5267 case ISD::VP_REDUCE_SMAX: 5268 return RISCVISD::VECREDUCE_SMAX_VL; 5269 case ISD::VP_REDUCE_UMIN: 5270 return RISCVISD::VECREDUCE_UMIN_VL; 5271 case ISD::VP_REDUCE_SMIN: 5272 return RISCVISD::VECREDUCE_SMIN_VL; 5273 case ISD::VP_REDUCE_AND: 5274 return RISCVISD::VECREDUCE_AND_VL; 5275 case ISD::VP_REDUCE_OR: 5276 return RISCVISD::VECREDUCE_OR_VL; 5277 case ISD::VP_REDUCE_XOR: 5278 return RISCVISD::VECREDUCE_XOR_VL; 5279 case ISD::VP_REDUCE_FADD: 5280 return RISCVISD::VECREDUCE_FADD_VL; 5281 case ISD::VP_REDUCE_SEQ_FADD: 5282 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5283 case ISD::VP_REDUCE_FMAX: 5284 return RISCVISD::VECREDUCE_FMAX_VL; 5285 case ISD::VP_REDUCE_FMIN: 5286 return RISCVISD::VECREDUCE_FMIN_VL; 5287 } 5288 } 5289 5290 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5291 SelectionDAG &DAG) const { 5292 SDLoc DL(Op); 5293 SDValue Vec = Op.getOperand(1); 5294 EVT VecEVT = Vec.getValueType(); 5295 5296 // TODO: The type may need to be widened rather than split. Or widened before 5297 // it can be split. 5298 if (!isTypeLegal(VecEVT)) 5299 return SDValue(); 5300 5301 MVT VecVT = VecEVT.getSimpleVT(); 5302 MVT VecEltVT = VecVT.getVectorElementType(); 5303 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5304 5305 MVT ContainerVT = VecVT; 5306 if (VecVT.isFixedLengthVector()) { 5307 ContainerVT = getContainerForFixedLengthVector(VecVT); 5308 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5309 } 5310 5311 SDValue VL = Op.getOperand(3); 5312 SDValue Mask = Op.getOperand(2); 5313 5314 MVT M1VT = getLMUL1VT(ContainerVT); 5315 MVT XLenVT = Subtarget.getXLenVT(); 5316 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5317 5318 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5319 DAG.getConstant(1, DL, XLenVT), M1VT, 5320 DL, DAG, Subtarget); 5321 SDValue Reduction = 5322 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5323 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5324 DAG.getConstant(0, DL, XLenVT)); 5325 if (!VecVT.isInteger()) 5326 return Elt0; 5327 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5328 } 5329 5330 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5331 SelectionDAG &DAG) const { 5332 SDValue Vec = Op.getOperand(0); 5333 SDValue SubVec = Op.getOperand(1); 5334 MVT VecVT = Vec.getSimpleValueType(); 5335 MVT SubVecVT = SubVec.getSimpleValueType(); 5336 5337 SDLoc DL(Op); 5338 MVT XLenVT = Subtarget.getXLenVT(); 5339 unsigned OrigIdx = Op.getConstantOperandVal(2); 5340 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5341 5342 // We don't have the ability to slide mask vectors up indexed by their i1 5343 // elements; the smallest we can do is i8. Often we are able to bitcast to 5344 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5345 // into a scalable one, we might not necessarily have enough scalable 5346 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5347 if (SubVecVT.getVectorElementType() == MVT::i1 && 5348 (OrigIdx != 0 || !Vec.isUndef())) { 5349 if (VecVT.getVectorMinNumElements() >= 8 && 5350 SubVecVT.getVectorMinNumElements() >= 8) { 5351 assert(OrigIdx % 8 == 0 && "Invalid index"); 5352 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5353 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5354 "Unexpected mask vector lowering"); 5355 OrigIdx /= 8; 5356 SubVecVT = 5357 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5358 SubVecVT.isScalableVector()); 5359 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5360 VecVT.isScalableVector()); 5361 Vec = DAG.getBitcast(VecVT, Vec); 5362 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5363 } else { 5364 // We can't slide this mask vector up indexed by its i1 elements. 5365 // This poses a problem when we wish to insert a scalable vector which 5366 // can't be re-expressed as a larger type. Just choose the slow path and 5367 // extend to a larger type, then truncate back down. 5368 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5369 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5370 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5371 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5372 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5373 Op.getOperand(2)); 5374 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5375 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5376 } 5377 } 5378 5379 // If the subvector vector is a fixed-length type, we cannot use subregister 5380 // manipulation to simplify the codegen; we don't know which register of a 5381 // LMUL group contains the specific subvector as we only know the minimum 5382 // register size. Therefore we must slide the vector group up the full 5383 // amount. 5384 if (SubVecVT.isFixedLengthVector()) { 5385 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5386 return Op; 5387 MVT ContainerVT = VecVT; 5388 if (VecVT.isFixedLengthVector()) { 5389 ContainerVT = getContainerForFixedLengthVector(VecVT); 5390 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5391 } 5392 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5393 DAG.getUNDEF(ContainerVT), SubVec, 5394 DAG.getConstant(0, DL, XLenVT)); 5395 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5396 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5397 return DAG.getBitcast(Op.getValueType(), SubVec); 5398 } 5399 SDValue Mask = 5400 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5401 // Set the vector length to only the number of elements we care about. Note 5402 // that for slideup this includes the offset. 5403 SDValue VL = 5404 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5405 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5406 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5407 SubVec, SlideupAmt, Mask, VL); 5408 if (VecVT.isFixedLengthVector()) 5409 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5410 return DAG.getBitcast(Op.getValueType(), Slideup); 5411 } 5412 5413 unsigned SubRegIdx, RemIdx; 5414 std::tie(SubRegIdx, RemIdx) = 5415 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5416 VecVT, SubVecVT, OrigIdx, TRI); 5417 5418 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5419 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5420 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5421 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5422 5423 // 1. If the Idx has been completely eliminated and this subvector's size is 5424 // a vector register or a multiple thereof, or the surrounding elements are 5425 // undef, then this is a subvector insert which naturally aligns to a vector 5426 // register. These can easily be handled using subregister manipulation. 5427 // 2. If the subvector is smaller than a vector register, then the insertion 5428 // must preserve the undisturbed elements of the register. We do this by 5429 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5430 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5431 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5432 // LMUL=1 type back into the larger vector (resolving to another subregister 5433 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5434 // to avoid allocating a large register group to hold our subvector. 5435 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5436 return Op; 5437 5438 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5439 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5440 // (in our case undisturbed). This means we can set up a subvector insertion 5441 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5442 // size of the subvector. 5443 MVT InterSubVT = VecVT; 5444 SDValue AlignedExtract = Vec; 5445 unsigned AlignedIdx = OrigIdx - RemIdx; 5446 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5447 InterSubVT = getLMUL1VT(VecVT); 5448 // Extract a subvector equal to the nearest full vector register type. This 5449 // should resolve to a EXTRACT_SUBREG instruction. 5450 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5451 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5452 } 5453 5454 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5455 // For scalable vectors this must be further multiplied by vscale. 5456 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5457 5458 SDValue Mask, VL; 5459 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5460 5461 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5462 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5463 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5464 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5465 5466 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5467 DAG.getUNDEF(InterSubVT), SubVec, 5468 DAG.getConstant(0, DL, XLenVT)); 5469 5470 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5471 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5472 5473 // If required, insert this subvector back into the correct vector register. 5474 // This should resolve to an INSERT_SUBREG instruction. 5475 if (VecVT.bitsGT(InterSubVT)) 5476 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5477 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5478 5479 // We might have bitcast from a mask type: cast back to the original type if 5480 // required. 5481 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5482 } 5483 5484 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5485 SelectionDAG &DAG) const { 5486 SDValue Vec = Op.getOperand(0); 5487 MVT SubVecVT = Op.getSimpleValueType(); 5488 MVT VecVT = Vec.getSimpleValueType(); 5489 5490 SDLoc DL(Op); 5491 MVT XLenVT = Subtarget.getXLenVT(); 5492 unsigned OrigIdx = Op.getConstantOperandVal(1); 5493 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5494 5495 // We don't have the ability to slide mask vectors down indexed by their i1 5496 // elements; the smallest we can do is i8. Often we are able to bitcast to 5497 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5498 // from a scalable one, we might not necessarily have enough scalable 5499 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5500 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5501 if (VecVT.getVectorMinNumElements() >= 8 && 5502 SubVecVT.getVectorMinNumElements() >= 8) { 5503 assert(OrigIdx % 8 == 0 && "Invalid index"); 5504 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5505 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5506 "Unexpected mask vector lowering"); 5507 OrigIdx /= 8; 5508 SubVecVT = 5509 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5510 SubVecVT.isScalableVector()); 5511 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5512 VecVT.isScalableVector()); 5513 Vec = DAG.getBitcast(VecVT, Vec); 5514 } else { 5515 // We can't slide this mask vector down, indexed by its i1 elements. 5516 // This poses a problem when we wish to extract a scalable vector which 5517 // can't be re-expressed as a larger type. Just choose the slow path and 5518 // extend to a larger type, then truncate back down. 5519 // TODO: We could probably improve this when extracting certain fixed 5520 // from fixed, where we can extract as i8 and shift the correct element 5521 // right to reach the desired subvector? 5522 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5523 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5524 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5525 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5526 Op.getOperand(1)); 5527 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5528 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5529 } 5530 } 5531 5532 // If the subvector vector is a fixed-length type, we cannot use subregister 5533 // manipulation to simplify the codegen; we don't know which register of a 5534 // LMUL group contains the specific subvector as we only know the minimum 5535 // register size. Therefore we must slide the vector group down the full 5536 // amount. 5537 if (SubVecVT.isFixedLengthVector()) { 5538 // With an index of 0 this is a cast-like subvector, which can be performed 5539 // with subregister operations. 5540 if (OrigIdx == 0) 5541 return Op; 5542 MVT ContainerVT = VecVT; 5543 if (VecVT.isFixedLengthVector()) { 5544 ContainerVT = getContainerForFixedLengthVector(VecVT); 5545 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5546 } 5547 SDValue Mask = 5548 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5549 // Set the vector length to only the number of elements we care about. This 5550 // avoids sliding down elements we're going to discard straight away. 5551 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5552 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5553 SDValue Slidedown = 5554 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5555 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5556 // Now we can use a cast-like subvector extract to get the result. 5557 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5558 DAG.getConstant(0, DL, XLenVT)); 5559 return DAG.getBitcast(Op.getValueType(), Slidedown); 5560 } 5561 5562 unsigned SubRegIdx, RemIdx; 5563 std::tie(SubRegIdx, RemIdx) = 5564 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5565 VecVT, SubVecVT, OrigIdx, TRI); 5566 5567 // If the Idx has been completely eliminated then this is a subvector extract 5568 // which naturally aligns to a vector register. These can easily be handled 5569 // using subregister manipulation. 5570 if (RemIdx == 0) 5571 return Op; 5572 5573 // Else we must shift our vector register directly to extract the subvector. 5574 // Do this using VSLIDEDOWN. 5575 5576 // If the vector type is an LMUL-group type, extract a subvector equal to the 5577 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5578 // instruction. 5579 MVT InterSubVT = VecVT; 5580 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5581 InterSubVT = getLMUL1VT(VecVT); 5582 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5583 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5584 } 5585 5586 // Slide this vector register down by the desired number of elements in order 5587 // to place the desired subvector starting at element 0. 5588 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5589 // For scalable vectors this must be further multiplied by vscale. 5590 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5591 5592 SDValue Mask, VL; 5593 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5594 SDValue Slidedown = 5595 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5596 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5597 5598 // Now the vector is in the right position, extract our final subvector. This 5599 // should resolve to a COPY. 5600 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5601 DAG.getConstant(0, DL, XLenVT)); 5602 5603 // We might have bitcast from a mask type: cast back to the original type if 5604 // required. 5605 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5606 } 5607 5608 // Lower step_vector to the vid instruction. Any non-identity step value must 5609 // be accounted for my manual expansion. 5610 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5611 SelectionDAG &DAG) const { 5612 SDLoc DL(Op); 5613 MVT VT = Op.getSimpleValueType(); 5614 MVT XLenVT = Subtarget.getXLenVT(); 5615 SDValue Mask, VL; 5616 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5617 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5618 uint64_t StepValImm = Op.getConstantOperandVal(0); 5619 if (StepValImm != 1) { 5620 if (isPowerOf2_64(StepValImm)) { 5621 SDValue StepVal = 5622 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5623 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5624 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5625 } else { 5626 SDValue StepVal = lowerScalarSplat( 5627 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5628 VL, VT, DL, DAG, Subtarget); 5629 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5630 } 5631 } 5632 return StepVec; 5633 } 5634 5635 // Implement vector_reverse using vrgather.vv with indices determined by 5636 // subtracting the id of each element from (VLMAX-1). This will convert 5637 // the indices like so: 5638 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5639 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5640 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5641 SelectionDAG &DAG) const { 5642 SDLoc DL(Op); 5643 MVT VecVT = Op.getSimpleValueType(); 5644 if (VecVT.getVectorElementType() == MVT::i1) { 5645 MVT WidenVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 5646 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenVT, Op.getOperand(0)); 5647 SDValue Op2 = DAG.getNode(ISD::VECTOR_REVERSE, DL, WidenVT, Op1); 5648 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Op2); 5649 } 5650 unsigned EltSize = VecVT.getScalarSizeInBits(); 5651 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5652 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 5653 unsigned MaxVLMAX = 5654 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 5655 5656 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5657 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5658 5659 // If this is SEW=8 and VLMAX is potentially more than 256, we need 5660 // to use vrgatherei16.vv. 5661 // TODO: It's also possible to use vrgatherei16.vv for other types to 5662 // decrease register width for the index calculation. 5663 if (MaxVLMAX > 256 && EltSize == 8) { 5664 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5665 // Reverse each half, then reassemble them in reverse order. 5666 // NOTE: It's also possible that after splitting that VLMAX no longer 5667 // requires vrgatherei16.vv. 5668 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5669 SDValue Lo, Hi; 5670 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5671 EVT LoVT, HiVT; 5672 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5673 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5674 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5675 // Reassemble the low and high pieces reversed. 5676 // FIXME: This is a CONCAT_VECTORS. 5677 SDValue Res = 5678 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5679 DAG.getIntPtrConstant(0, DL)); 5680 return DAG.getNode( 5681 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5682 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5683 } 5684 5685 // Just promote the int type to i16 which will double the LMUL. 5686 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5687 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5688 } 5689 5690 MVT XLenVT = Subtarget.getXLenVT(); 5691 SDValue Mask, VL; 5692 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5693 5694 // Calculate VLMAX-1 for the desired SEW. 5695 unsigned MinElts = VecVT.getVectorMinNumElements(); 5696 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5697 DAG.getConstant(MinElts, DL, XLenVT)); 5698 SDValue VLMinus1 = 5699 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5700 5701 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5702 bool IsRV32E64 = 5703 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5704 SDValue SplatVL; 5705 if (!IsRV32E64) 5706 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5707 else 5708 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5709 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5710 5711 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5712 SDValue Indices = 5713 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5714 5715 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, 5716 DAG.getUNDEF(VecVT), VL); 5717 } 5718 5719 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5720 SelectionDAG &DAG) const { 5721 SDLoc DL(Op); 5722 SDValue V1 = Op.getOperand(0); 5723 SDValue V2 = Op.getOperand(1); 5724 MVT XLenVT = Subtarget.getXLenVT(); 5725 MVT VecVT = Op.getSimpleValueType(); 5726 5727 unsigned MinElts = VecVT.getVectorMinNumElements(); 5728 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5729 DAG.getConstant(MinElts, DL, XLenVT)); 5730 5731 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5732 SDValue DownOffset, UpOffset; 5733 if (ImmValue >= 0) { 5734 // The operand is a TargetConstant, we need to rebuild it as a regular 5735 // constant. 5736 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5737 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5738 } else { 5739 // The operand is a TargetConstant, we need to rebuild it as a regular 5740 // constant rather than negating the original operand. 5741 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5742 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5743 } 5744 5745 SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG); 5746 5747 SDValue SlideDown = 5748 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5749 DownOffset, TrueMask, UpOffset); 5750 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5751 TrueMask, 5752 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 5753 } 5754 5755 SDValue 5756 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5757 SelectionDAG &DAG) const { 5758 SDLoc DL(Op); 5759 auto *Load = cast<LoadSDNode>(Op); 5760 5761 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5762 Load->getMemoryVT(), 5763 *Load->getMemOperand()) && 5764 "Expecting a correctly-aligned load"); 5765 5766 MVT VT = Op.getSimpleValueType(); 5767 MVT XLenVT = Subtarget.getXLenVT(); 5768 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5769 5770 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5771 5772 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5773 SDValue IntID = DAG.getTargetConstant( 5774 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 5775 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 5776 if (!IsMaskOp) 5777 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5778 Ops.push_back(Load->getBasePtr()); 5779 Ops.push_back(VL); 5780 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5781 SDValue NewLoad = 5782 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5783 Load->getMemoryVT(), Load->getMemOperand()); 5784 5785 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5786 return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL); 5787 } 5788 5789 SDValue 5790 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5791 SelectionDAG &DAG) const { 5792 SDLoc DL(Op); 5793 auto *Store = cast<StoreSDNode>(Op); 5794 5795 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5796 Store->getMemoryVT(), 5797 *Store->getMemOperand()) && 5798 "Expecting a correctly-aligned store"); 5799 5800 SDValue StoreVal = Store->getValue(); 5801 MVT VT = StoreVal.getSimpleValueType(); 5802 MVT XLenVT = Subtarget.getXLenVT(); 5803 5804 // If the size less than a byte, we need to pad with zeros to make a byte. 5805 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5806 VT = MVT::v8i1; 5807 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5808 DAG.getConstant(0, DL, VT), StoreVal, 5809 DAG.getIntPtrConstant(0, DL)); 5810 } 5811 5812 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5813 5814 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5815 5816 SDValue NewValue = 5817 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5818 5819 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5820 SDValue IntID = DAG.getTargetConstant( 5821 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 5822 return DAG.getMemIntrinsicNode( 5823 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 5824 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 5825 Store->getMemoryVT(), Store->getMemOperand()); 5826 } 5827 5828 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5829 SelectionDAG &DAG) const { 5830 SDLoc DL(Op); 5831 MVT VT = Op.getSimpleValueType(); 5832 5833 const auto *MemSD = cast<MemSDNode>(Op); 5834 EVT MemVT = MemSD->getMemoryVT(); 5835 MachineMemOperand *MMO = MemSD->getMemOperand(); 5836 SDValue Chain = MemSD->getChain(); 5837 SDValue BasePtr = MemSD->getBasePtr(); 5838 5839 SDValue Mask, PassThru, VL; 5840 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5841 Mask = VPLoad->getMask(); 5842 PassThru = DAG.getUNDEF(VT); 5843 VL = VPLoad->getVectorLength(); 5844 } else { 5845 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5846 Mask = MLoad->getMask(); 5847 PassThru = MLoad->getPassThru(); 5848 } 5849 5850 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5851 5852 MVT XLenVT = Subtarget.getXLenVT(); 5853 5854 MVT ContainerVT = VT; 5855 if (VT.isFixedLengthVector()) { 5856 ContainerVT = getContainerForFixedLengthVector(VT); 5857 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5858 if (!IsUnmasked) { 5859 MVT MaskVT = getMaskTypeFor(ContainerVT); 5860 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5861 } 5862 } 5863 5864 if (!VL) 5865 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5866 5867 unsigned IntID = 5868 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5869 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5870 if (IsUnmasked) 5871 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5872 else 5873 Ops.push_back(PassThru); 5874 Ops.push_back(BasePtr); 5875 if (!IsUnmasked) 5876 Ops.push_back(Mask); 5877 Ops.push_back(VL); 5878 if (!IsUnmasked) 5879 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5880 5881 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5882 5883 SDValue Result = 5884 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5885 Chain = Result.getValue(1); 5886 5887 if (VT.isFixedLengthVector()) 5888 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5889 5890 return DAG.getMergeValues({Result, Chain}, DL); 5891 } 5892 5893 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5894 SelectionDAG &DAG) const { 5895 SDLoc DL(Op); 5896 5897 const auto *MemSD = cast<MemSDNode>(Op); 5898 EVT MemVT = MemSD->getMemoryVT(); 5899 MachineMemOperand *MMO = MemSD->getMemOperand(); 5900 SDValue Chain = MemSD->getChain(); 5901 SDValue BasePtr = MemSD->getBasePtr(); 5902 SDValue Val, Mask, VL; 5903 5904 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5905 Val = VPStore->getValue(); 5906 Mask = VPStore->getMask(); 5907 VL = VPStore->getVectorLength(); 5908 } else { 5909 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5910 Val = MStore->getValue(); 5911 Mask = MStore->getMask(); 5912 } 5913 5914 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5915 5916 MVT VT = Val.getSimpleValueType(); 5917 MVT XLenVT = Subtarget.getXLenVT(); 5918 5919 MVT ContainerVT = VT; 5920 if (VT.isFixedLengthVector()) { 5921 ContainerVT = getContainerForFixedLengthVector(VT); 5922 5923 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5924 if (!IsUnmasked) { 5925 MVT MaskVT = getMaskTypeFor(ContainerVT); 5926 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5927 } 5928 } 5929 5930 if (!VL) 5931 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5932 5933 unsigned IntID = 5934 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5935 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5936 Ops.push_back(Val); 5937 Ops.push_back(BasePtr); 5938 if (!IsUnmasked) 5939 Ops.push_back(Mask); 5940 Ops.push_back(VL); 5941 5942 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5943 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5944 } 5945 5946 SDValue 5947 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5948 SelectionDAG &DAG) const { 5949 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5950 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5951 5952 MVT VT = Op.getSimpleValueType(); 5953 5954 SDValue Op1 = 5955 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5956 SDValue Op2 = 5957 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5958 5959 SDLoc DL(Op); 5960 SDValue VL = 5961 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5962 5963 MVT MaskVT = getMaskTypeFor(ContainerVT); 5964 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 5965 5966 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5967 Op.getOperand(2), Mask, VL); 5968 5969 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5970 } 5971 5972 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5973 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5974 MVT VT = Op.getSimpleValueType(); 5975 5976 if (VT.getVectorElementType() == MVT::i1) 5977 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5978 5979 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5980 } 5981 5982 SDValue 5983 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5984 SelectionDAG &DAG) const { 5985 unsigned Opc; 5986 switch (Op.getOpcode()) { 5987 default: llvm_unreachable("Unexpected opcode!"); 5988 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5989 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5990 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5991 } 5992 5993 return lowerToScalableOp(Op, DAG, Opc); 5994 } 5995 5996 // Lower vector ABS to smax(X, sub(0, X)). 5997 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5998 SDLoc DL(Op); 5999 MVT VT = Op.getSimpleValueType(); 6000 SDValue X = Op.getOperand(0); 6001 6002 assert(VT.isFixedLengthVector() && "Unexpected type"); 6003 6004 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6005 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 6006 6007 SDValue Mask, VL; 6008 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6009 6010 SDValue SplatZero = DAG.getNode( 6011 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 6012 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 6013 SDValue NegX = 6014 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 6015 SDValue Max = 6016 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 6017 6018 return convertFromScalableVector(VT, Max, DAG, Subtarget); 6019 } 6020 6021 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 6022 SDValue Op, SelectionDAG &DAG) const { 6023 SDLoc DL(Op); 6024 MVT VT = Op.getSimpleValueType(); 6025 SDValue Mag = Op.getOperand(0); 6026 SDValue Sign = Op.getOperand(1); 6027 assert(Mag.getValueType() == Sign.getValueType() && 6028 "Can only handle COPYSIGN with matching types."); 6029 6030 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6031 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 6032 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 6033 6034 SDValue Mask, VL; 6035 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6036 6037 SDValue CopySign = 6038 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 6039 6040 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 6041 } 6042 6043 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 6044 SDValue Op, SelectionDAG &DAG) const { 6045 MVT VT = Op.getSimpleValueType(); 6046 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6047 6048 MVT I1ContainerVT = 6049 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6050 6051 SDValue CC = 6052 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 6053 SDValue Op1 = 6054 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 6055 SDValue Op2 = 6056 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 6057 6058 SDLoc DL(Op); 6059 SDValue Mask, VL; 6060 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6061 6062 SDValue Select = 6063 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 6064 6065 return convertFromScalableVector(VT, Select, DAG, Subtarget); 6066 } 6067 6068 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 6069 unsigned NewOpc, 6070 bool HasMask) const { 6071 MVT VT = Op.getSimpleValueType(); 6072 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6073 6074 // Create list of operands by converting existing ones to scalable types. 6075 SmallVector<SDValue, 6> Ops; 6076 for (const SDValue &V : Op->op_values()) { 6077 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6078 6079 // Pass through non-vector operands. 6080 if (!V.getValueType().isVector()) { 6081 Ops.push_back(V); 6082 continue; 6083 } 6084 6085 // "cast" fixed length vector to a scalable vector. 6086 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6087 "Only fixed length vectors are supported!"); 6088 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6089 } 6090 6091 SDLoc DL(Op); 6092 SDValue Mask, VL; 6093 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6094 if (HasMask) 6095 Ops.push_back(Mask); 6096 Ops.push_back(VL); 6097 6098 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6099 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6100 } 6101 6102 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6103 // * Operands of each node are assumed to be in the same order. 6104 // * The EVL operand is promoted from i32 to i64 on RV64. 6105 // * Fixed-length vectors are converted to their scalable-vector container 6106 // types. 6107 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6108 unsigned RISCVISDOpc) const { 6109 SDLoc DL(Op); 6110 MVT VT = Op.getSimpleValueType(); 6111 SmallVector<SDValue, 4> Ops; 6112 6113 for (const auto &OpIdx : enumerate(Op->ops())) { 6114 SDValue V = OpIdx.value(); 6115 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6116 // Pass through operands which aren't fixed-length vectors. 6117 if (!V.getValueType().isFixedLengthVector()) { 6118 Ops.push_back(V); 6119 continue; 6120 } 6121 // "cast" fixed length vector to a scalable vector. 6122 MVT OpVT = V.getSimpleValueType(); 6123 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6124 assert(useRVVForFixedLengthVectorVT(OpVT) && 6125 "Only fixed length vectors are supported!"); 6126 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6127 } 6128 6129 if (!VT.isFixedLengthVector()) 6130 return DAG.getNode(RISCVISDOpc, DL, VT, Ops, Op->getFlags()); 6131 6132 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6133 6134 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops, Op->getFlags()); 6135 6136 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6137 } 6138 6139 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op, 6140 SelectionDAG &DAG) const { 6141 SDLoc DL(Op); 6142 MVT VT = Op.getSimpleValueType(); 6143 6144 SDValue Src = Op.getOperand(0); 6145 // NOTE: Mask is dropped. 6146 SDValue VL = Op.getOperand(2); 6147 6148 MVT ContainerVT = VT; 6149 if (VT.isFixedLengthVector()) { 6150 ContainerVT = getContainerForFixedLengthVector(VT); 6151 MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6152 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6153 } 6154 6155 MVT XLenVT = Subtarget.getXLenVT(); 6156 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6157 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6158 DAG.getUNDEF(ContainerVT), Zero, VL); 6159 6160 SDValue SplatValue = DAG.getConstant( 6161 Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT); 6162 SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6163 DAG.getUNDEF(ContainerVT), SplatValue, VL); 6164 6165 SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src, 6166 Splat, ZeroSplat, VL); 6167 if (!VT.isFixedLengthVector()) 6168 return Result; 6169 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6170 } 6171 6172 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op, 6173 SelectionDAG &DAG) const { 6174 SDLoc DL(Op); 6175 MVT VT = Op.getSimpleValueType(); 6176 6177 SDValue Op1 = Op.getOperand(0); 6178 SDValue Op2 = Op.getOperand(1); 6179 ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 6180 // NOTE: Mask is dropped. 6181 SDValue VL = Op.getOperand(4); 6182 6183 MVT ContainerVT = VT; 6184 if (VT.isFixedLengthVector()) { 6185 ContainerVT = getContainerForFixedLengthVector(VT); 6186 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6187 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6188 } 6189 6190 SDValue Result; 6191 SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 6192 6193 switch (Condition) { 6194 default: 6195 break; 6196 // X != Y --> (X^Y) 6197 case ISD::SETNE: 6198 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6199 break; 6200 // X == Y --> ~(X^Y) 6201 case ISD::SETEQ: { 6202 SDValue Temp = 6203 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6204 Result = 6205 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL); 6206 break; 6207 } 6208 // X >s Y --> X == 0 & Y == 1 --> ~X & Y 6209 // X <u Y --> X == 0 & Y == 1 --> ~X & Y 6210 case ISD::SETGT: 6211 case ISD::SETULT: { 6212 SDValue Temp = 6213 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6214 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL); 6215 break; 6216 } 6217 // X <s Y --> X == 1 & Y == 0 --> ~Y & X 6218 // X >u Y --> X == 1 & Y == 0 --> ~Y & X 6219 case ISD::SETLT: 6220 case ISD::SETUGT: { 6221 SDValue Temp = 6222 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6223 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL); 6224 break; 6225 } 6226 // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 6227 // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 6228 case ISD::SETGE: 6229 case ISD::SETULE: { 6230 SDValue Temp = 6231 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6232 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL); 6233 break; 6234 } 6235 // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 6236 // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 6237 case ISD::SETLE: 6238 case ISD::SETUGE: { 6239 SDValue Temp = 6240 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6241 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL); 6242 break; 6243 } 6244 } 6245 6246 if (!VT.isFixedLengthVector()) 6247 return Result; 6248 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6249 } 6250 6251 // Lower Floating-Point/Integer Type-Convert VP SDNodes 6252 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG, 6253 unsigned RISCVISDOpc) const { 6254 SDLoc DL(Op); 6255 6256 SDValue Src = Op.getOperand(0); 6257 SDValue Mask = Op.getOperand(1); 6258 SDValue VL = Op.getOperand(2); 6259 6260 MVT DstVT = Op.getSimpleValueType(); 6261 MVT SrcVT = Src.getSimpleValueType(); 6262 if (DstVT.isFixedLengthVector()) { 6263 DstVT = getContainerForFixedLengthVector(DstVT); 6264 SrcVT = getContainerForFixedLengthVector(SrcVT); 6265 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6266 MVT MaskVT = getMaskTypeFor(DstVT); 6267 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6268 } 6269 6270 unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL || 6271 RISCVISDOpc == RISCVISD::FP_TO_SINT_VL) 6272 ? RISCVISD::VSEXT_VL 6273 : RISCVISD::VZEXT_VL; 6274 6275 unsigned DstEltSize = DstVT.getScalarSizeInBits(); 6276 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 6277 6278 SDValue Result; 6279 if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion. 6280 if (SrcVT.isInteger()) { 6281 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6282 6283 // Do we need to do any pre-widening before converting? 6284 if (SrcEltSize == 1) { 6285 MVT IntVT = DstVT.changeVectorElementTypeToInteger(); 6286 MVT XLenVT = Subtarget.getXLenVT(); 6287 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6288 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6289 DAG.getUNDEF(IntVT), Zero, VL); 6290 SDValue One = DAG.getConstant( 6291 RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT); 6292 SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6293 DAG.getUNDEF(IntVT), One, VL); 6294 Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat, 6295 ZeroSplat, VL); 6296 } else if (DstEltSize > (2 * SrcEltSize)) { 6297 // Widen before converting. 6298 MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2), 6299 DstVT.getVectorElementCount()); 6300 Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL); 6301 } 6302 6303 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6304 } else { 6305 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6306 "Wrong input/output vector types"); 6307 6308 // Convert f16 to f32 then convert f32 to i64. 6309 if (DstEltSize > (2 * SrcEltSize)) { 6310 assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6311 MVT InterimFVT = 6312 MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6313 Src = 6314 DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL); 6315 } 6316 6317 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6318 } 6319 } else { // Narrowing + Conversion 6320 if (SrcVT.isInteger()) { 6321 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6322 // First do a narrowing convert to an FP type half the size, then round 6323 // the FP type to a small FP type if needed. 6324 6325 MVT InterimFVT = DstVT; 6326 if (SrcEltSize > (2 * DstEltSize)) { 6327 assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!"); 6328 assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6329 InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6330 } 6331 6332 Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL); 6333 6334 if (InterimFVT != DstVT) { 6335 Src = Result; 6336 Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL); 6337 } 6338 } else { 6339 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6340 "Wrong input/output vector types"); 6341 // First do a narrowing conversion to an integer half the size, then 6342 // truncate if needed. 6343 6344 if (DstEltSize == 1) { 6345 // First convert to the same size integer, then convert to mask using 6346 // setcc. 6347 assert(SrcEltSize >= 16 && "Unexpected FP type!"); 6348 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize), 6349 DstVT.getVectorElementCount()); 6350 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6351 6352 // Compare the integer result to 0. The integer should be 0 or 1/-1, 6353 // otherwise the conversion was undefined. 6354 MVT XLenVT = Subtarget.getXLenVT(); 6355 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 6356 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT, 6357 DAG.getUNDEF(InterimIVT), SplatZero); 6358 Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero, 6359 DAG.getCondCode(ISD::SETNE), Mask, VL); 6360 } else { 6361 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6362 DstVT.getVectorElementCount()); 6363 6364 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6365 6366 while (InterimIVT != DstVT) { 6367 SrcEltSize /= 2; 6368 Src = Result; 6369 InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6370 DstVT.getVectorElementCount()); 6371 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT, 6372 Src, Mask, VL); 6373 } 6374 } 6375 } 6376 } 6377 6378 MVT VT = Op.getSimpleValueType(); 6379 if (!VT.isFixedLengthVector()) 6380 return Result; 6381 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6382 } 6383 6384 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6385 unsigned MaskOpc, 6386 unsigned VecOpc) const { 6387 MVT VT = Op.getSimpleValueType(); 6388 if (VT.getVectorElementType() != MVT::i1) 6389 return lowerVPOp(Op, DAG, VecOpc); 6390 6391 // It is safe to drop mask parameter as masked-off elements are undef. 6392 SDValue Op1 = Op->getOperand(0); 6393 SDValue Op2 = Op->getOperand(1); 6394 SDValue VL = Op->getOperand(3); 6395 6396 MVT ContainerVT = VT; 6397 const bool IsFixed = VT.isFixedLengthVector(); 6398 if (IsFixed) { 6399 ContainerVT = getContainerForFixedLengthVector(VT); 6400 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6401 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6402 } 6403 6404 SDLoc DL(Op); 6405 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6406 if (!IsFixed) 6407 return Val; 6408 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6409 } 6410 6411 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6412 // matched to a RVV indexed load. The RVV indexed load instructions only 6413 // support the "unsigned unscaled" addressing mode; indices are implicitly 6414 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6415 // signed or scaled indexing is extended to the XLEN value type and scaled 6416 // accordingly. 6417 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6418 SelectionDAG &DAG) const { 6419 SDLoc DL(Op); 6420 MVT VT = Op.getSimpleValueType(); 6421 6422 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6423 EVT MemVT = MemSD->getMemoryVT(); 6424 MachineMemOperand *MMO = MemSD->getMemOperand(); 6425 SDValue Chain = MemSD->getChain(); 6426 SDValue BasePtr = MemSD->getBasePtr(); 6427 6428 ISD::LoadExtType LoadExtType; 6429 SDValue Index, Mask, PassThru, VL; 6430 6431 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6432 Index = VPGN->getIndex(); 6433 Mask = VPGN->getMask(); 6434 PassThru = DAG.getUNDEF(VT); 6435 VL = VPGN->getVectorLength(); 6436 // VP doesn't support extending loads. 6437 LoadExtType = ISD::NON_EXTLOAD; 6438 } else { 6439 // Else it must be a MGATHER. 6440 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6441 Index = MGN->getIndex(); 6442 Mask = MGN->getMask(); 6443 PassThru = MGN->getPassThru(); 6444 LoadExtType = MGN->getExtensionType(); 6445 } 6446 6447 MVT IndexVT = Index.getSimpleValueType(); 6448 MVT XLenVT = Subtarget.getXLenVT(); 6449 6450 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6451 "Unexpected VTs!"); 6452 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6453 // Targets have to explicitly opt-in for extending vector loads. 6454 assert(LoadExtType == ISD::NON_EXTLOAD && 6455 "Unexpected extending MGATHER/VP_GATHER"); 6456 (void)LoadExtType; 6457 6458 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6459 // the selection of the masked intrinsics doesn't do this for us. 6460 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6461 6462 MVT ContainerVT = VT; 6463 if (VT.isFixedLengthVector()) { 6464 ContainerVT = getContainerForFixedLengthVector(VT); 6465 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6466 ContainerVT.getVectorElementCount()); 6467 6468 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6469 6470 if (!IsUnmasked) { 6471 MVT MaskVT = getMaskTypeFor(ContainerVT); 6472 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6473 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6474 } 6475 } 6476 6477 if (!VL) 6478 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6479 6480 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6481 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6482 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6483 VL); 6484 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6485 TrueMask, VL); 6486 } 6487 6488 unsigned IntID = 6489 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6490 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6491 if (IsUnmasked) 6492 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6493 else 6494 Ops.push_back(PassThru); 6495 Ops.push_back(BasePtr); 6496 Ops.push_back(Index); 6497 if (!IsUnmasked) 6498 Ops.push_back(Mask); 6499 Ops.push_back(VL); 6500 if (!IsUnmasked) 6501 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6502 6503 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6504 SDValue Result = 6505 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6506 Chain = Result.getValue(1); 6507 6508 if (VT.isFixedLengthVector()) 6509 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6510 6511 return DAG.getMergeValues({Result, Chain}, DL); 6512 } 6513 6514 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6515 // matched to a RVV indexed store. The RVV indexed store instructions only 6516 // support the "unsigned unscaled" addressing mode; indices are implicitly 6517 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6518 // signed or scaled indexing is extended to the XLEN value type and scaled 6519 // accordingly. 6520 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6521 SelectionDAG &DAG) const { 6522 SDLoc DL(Op); 6523 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6524 EVT MemVT = MemSD->getMemoryVT(); 6525 MachineMemOperand *MMO = MemSD->getMemOperand(); 6526 SDValue Chain = MemSD->getChain(); 6527 SDValue BasePtr = MemSD->getBasePtr(); 6528 6529 bool IsTruncatingStore = false; 6530 SDValue Index, Mask, Val, VL; 6531 6532 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6533 Index = VPSN->getIndex(); 6534 Mask = VPSN->getMask(); 6535 Val = VPSN->getValue(); 6536 VL = VPSN->getVectorLength(); 6537 // VP doesn't support truncating stores. 6538 IsTruncatingStore = false; 6539 } else { 6540 // Else it must be a MSCATTER. 6541 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6542 Index = MSN->getIndex(); 6543 Mask = MSN->getMask(); 6544 Val = MSN->getValue(); 6545 IsTruncatingStore = MSN->isTruncatingStore(); 6546 } 6547 6548 MVT VT = Val.getSimpleValueType(); 6549 MVT IndexVT = Index.getSimpleValueType(); 6550 MVT XLenVT = Subtarget.getXLenVT(); 6551 6552 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6553 "Unexpected VTs!"); 6554 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6555 // Targets have to explicitly opt-in for extending vector loads and 6556 // truncating vector stores. 6557 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6558 (void)IsTruncatingStore; 6559 6560 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6561 // the selection of the masked intrinsics doesn't do this for us. 6562 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6563 6564 MVT ContainerVT = VT; 6565 if (VT.isFixedLengthVector()) { 6566 ContainerVT = getContainerForFixedLengthVector(VT); 6567 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6568 ContainerVT.getVectorElementCount()); 6569 6570 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6571 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6572 6573 if (!IsUnmasked) { 6574 MVT MaskVT = getMaskTypeFor(ContainerVT); 6575 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6576 } 6577 } 6578 6579 if (!VL) 6580 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6581 6582 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6583 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6584 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6585 VL); 6586 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6587 TrueMask, VL); 6588 } 6589 6590 unsigned IntID = 6591 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6592 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6593 Ops.push_back(Val); 6594 Ops.push_back(BasePtr); 6595 Ops.push_back(Index); 6596 if (!IsUnmasked) 6597 Ops.push_back(Mask); 6598 Ops.push_back(VL); 6599 6600 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6601 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6602 } 6603 6604 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6605 SelectionDAG &DAG) const { 6606 const MVT XLenVT = Subtarget.getXLenVT(); 6607 SDLoc DL(Op); 6608 SDValue Chain = Op->getOperand(0); 6609 SDValue SysRegNo = DAG.getTargetConstant( 6610 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6611 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6612 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6613 6614 // Encoding used for rounding mode in RISCV differs from that used in 6615 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6616 // table, which consists of a sequence of 4-bit fields, each representing 6617 // corresponding FLT_ROUNDS mode. 6618 static const int Table = 6619 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6620 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6621 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6622 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6623 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6624 6625 SDValue Shift = 6626 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6627 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6628 DAG.getConstant(Table, DL, XLenVT), Shift); 6629 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6630 DAG.getConstant(7, DL, XLenVT)); 6631 6632 return DAG.getMergeValues({Masked, Chain}, DL); 6633 } 6634 6635 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6636 SelectionDAG &DAG) const { 6637 const MVT XLenVT = Subtarget.getXLenVT(); 6638 SDLoc DL(Op); 6639 SDValue Chain = Op->getOperand(0); 6640 SDValue RMValue = Op->getOperand(1); 6641 SDValue SysRegNo = DAG.getTargetConstant( 6642 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6643 6644 // Encoding used for rounding mode in RISCV differs from that used in 6645 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6646 // a table, which consists of a sequence of 4-bit fields, each representing 6647 // corresponding RISCV mode. 6648 static const unsigned Table = 6649 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6650 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6651 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6652 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6653 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6654 6655 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6656 DAG.getConstant(2, DL, XLenVT)); 6657 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6658 DAG.getConstant(Table, DL, XLenVT), Shift); 6659 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6660 DAG.getConstant(0x7, DL, XLenVT)); 6661 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6662 RMValue); 6663 } 6664 6665 SDValue RISCVTargetLowering::lowerEH_DWARF_CFA(SDValue Op, 6666 SelectionDAG &DAG) const { 6667 MachineFunction &MF = DAG.getMachineFunction(); 6668 6669 bool isRISCV64 = Subtarget.is64Bit(); 6670 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6671 6672 int FI = MF.getFrameInfo().CreateFixedObject(isRISCV64 ? 8 : 4, 0, false); 6673 return DAG.getFrameIndex(FI, PtrVT); 6674 } 6675 6676 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6677 switch (IntNo) { 6678 default: 6679 llvm_unreachable("Unexpected Intrinsic"); 6680 case Intrinsic::riscv_bcompress: 6681 return RISCVISD::BCOMPRESSW; 6682 case Intrinsic::riscv_bdecompress: 6683 return RISCVISD::BDECOMPRESSW; 6684 case Intrinsic::riscv_bfp: 6685 return RISCVISD::BFPW; 6686 case Intrinsic::riscv_fsl: 6687 return RISCVISD::FSLW; 6688 case Intrinsic::riscv_fsr: 6689 return RISCVISD::FSRW; 6690 } 6691 } 6692 6693 // Converts the given intrinsic to a i64 operation with any extension. 6694 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6695 unsigned IntNo) { 6696 SDLoc DL(N); 6697 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6698 // Deal with the Instruction Operands 6699 SmallVector<SDValue, 3> NewOps; 6700 for (SDValue Op : drop_begin(N->ops())) 6701 // Promote the operand to i64 type 6702 NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op)); 6703 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps); 6704 // ReplaceNodeResults requires we maintain the same type for the return value. 6705 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6706 } 6707 6708 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6709 // form of the given Opcode. 6710 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6711 switch (Opcode) { 6712 default: 6713 llvm_unreachable("Unexpected opcode"); 6714 case ISD::SHL: 6715 return RISCVISD::SLLW; 6716 case ISD::SRA: 6717 return RISCVISD::SRAW; 6718 case ISD::SRL: 6719 return RISCVISD::SRLW; 6720 case ISD::SDIV: 6721 return RISCVISD::DIVW; 6722 case ISD::UDIV: 6723 return RISCVISD::DIVUW; 6724 case ISD::UREM: 6725 return RISCVISD::REMUW; 6726 case ISD::ROTL: 6727 return RISCVISD::ROLW; 6728 case ISD::ROTR: 6729 return RISCVISD::RORW; 6730 } 6731 } 6732 6733 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6734 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6735 // otherwise be promoted to i64, making it difficult to select the 6736 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6737 // type i8/i16/i32 is lost. 6738 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6739 unsigned ExtOpc = ISD::ANY_EXTEND) { 6740 SDLoc DL(N); 6741 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6742 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6743 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6744 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6745 // ReplaceNodeResults requires we maintain the same type for the return value. 6746 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6747 } 6748 6749 // Converts the given 32-bit operation to a i64 operation with signed extension 6750 // semantic to reduce the signed extension instructions. 6751 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6752 SDLoc DL(N); 6753 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6754 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6755 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6756 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6757 DAG.getValueType(MVT::i32)); 6758 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6759 } 6760 6761 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6762 SmallVectorImpl<SDValue> &Results, 6763 SelectionDAG &DAG) const { 6764 SDLoc DL(N); 6765 switch (N->getOpcode()) { 6766 default: 6767 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6768 case ISD::STRICT_FP_TO_SINT: 6769 case ISD::STRICT_FP_TO_UINT: 6770 case ISD::FP_TO_SINT: 6771 case ISD::FP_TO_UINT: { 6772 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6773 "Unexpected custom legalisation"); 6774 bool IsStrict = N->isStrictFPOpcode(); 6775 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6776 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6777 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6778 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6779 TargetLowering::TypeSoftenFloat) { 6780 if (!isTypeLegal(Op0.getValueType())) 6781 return; 6782 if (IsStrict) { 6783 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6784 : RISCVISD::STRICT_FCVT_WU_RV64; 6785 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6786 SDValue Res = DAG.getNode( 6787 Opc, DL, VTs, N->getOperand(0), Op0, 6788 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6789 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6790 Results.push_back(Res.getValue(1)); 6791 return; 6792 } 6793 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6794 SDValue Res = 6795 DAG.getNode(Opc, DL, MVT::i64, Op0, 6796 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6797 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6798 return; 6799 } 6800 // If the FP type needs to be softened, emit a library call using the 'si' 6801 // version. If we left it to default legalization we'd end up with 'di'. If 6802 // the FP type doesn't need to be softened just let generic type 6803 // legalization promote the result type. 6804 RTLIB::Libcall LC; 6805 if (IsSigned) 6806 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6807 else 6808 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6809 MakeLibCallOptions CallOptions; 6810 EVT OpVT = Op0.getValueType(); 6811 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6812 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6813 SDValue Result; 6814 std::tie(Result, Chain) = 6815 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6816 Results.push_back(Result); 6817 if (IsStrict) 6818 Results.push_back(Chain); 6819 break; 6820 } 6821 case ISD::READCYCLECOUNTER: { 6822 assert(!Subtarget.is64Bit() && 6823 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6824 6825 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6826 SDValue RCW = 6827 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6828 6829 Results.push_back( 6830 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6831 Results.push_back(RCW.getValue(2)); 6832 break; 6833 } 6834 case ISD::MUL: { 6835 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6836 unsigned XLen = Subtarget.getXLen(); 6837 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6838 if (Size > XLen) { 6839 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6840 SDValue LHS = N->getOperand(0); 6841 SDValue RHS = N->getOperand(1); 6842 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6843 6844 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6845 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6846 // We need exactly one side to be unsigned. 6847 if (LHSIsU == RHSIsU) 6848 return; 6849 6850 auto MakeMULPair = [&](SDValue S, SDValue U) { 6851 MVT XLenVT = Subtarget.getXLenVT(); 6852 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6853 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6854 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6855 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6856 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6857 }; 6858 6859 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6860 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6861 6862 // The other operand should be signed, but still prefer MULH when 6863 // possible. 6864 if (RHSIsU && LHSIsS && !RHSIsS) 6865 Results.push_back(MakeMULPair(LHS, RHS)); 6866 else if (LHSIsU && RHSIsS && !LHSIsS) 6867 Results.push_back(MakeMULPair(RHS, LHS)); 6868 6869 return; 6870 } 6871 LLVM_FALLTHROUGH; 6872 } 6873 case ISD::ADD: 6874 case ISD::SUB: 6875 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6876 "Unexpected custom legalisation"); 6877 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6878 break; 6879 case ISD::SHL: 6880 case ISD::SRA: 6881 case ISD::SRL: 6882 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6883 "Unexpected custom legalisation"); 6884 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6885 // If we can use a BSET instruction, allow default promotion to apply. 6886 if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() && 6887 isOneConstant(N->getOperand(0))) 6888 break; 6889 Results.push_back(customLegalizeToWOp(N, DAG)); 6890 break; 6891 } 6892 6893 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6894 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6895 // shift amount. 6896 if (N->getOpcode() == ISD::SHL) { 6897 SDLoc DL(N); 6898 SDValue NewOp0 = 6899 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6900 SDValue NewOp1 = 6901 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6902 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6903 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6904 DAG.getValueType(MVT::i32)); 6905 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6906 } 6907 6908 break; 6909 case ISD::ROTL: 6910 case ISD::ROTR: 6911 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6912 "Unexpected custom legalisation"); 6913 Results.push_back(customLegalizeToWOp(N, DAG)); 6914 break; 6915 case ISD::CTTZ: 6916 case ISD::CTTZ_ZERO_UNDEF: 6917 case ISD::CTLZ: 6918 case ISD::CTLZ_ZERO_UNDEF: { 6919 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6920 "Unexpected custom legalisation"); 6921 6922 SDValue NewOp0 = 6923 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6924 bool IsCTZ = 6925 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6926 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6927 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6928 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6929 return; 6930 } 6931 case ISD::SDIV: 6932 case ISD::UDIV: 6933 case ISD::UREM: { 6934 MVT VT = N->getSimpleValueType(0); 6935 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6936 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6937 "Unexpected custom legalisation"); 6938 // Don't promote division/remainder by constant since we should expand those 6939 // to multiply by magic constant. 6940 // FIXME: What if the expansion is disabled for minsize. 6941 if (N->getOperand(1).getOpcode() == ISD::Constant) 6942 return; 6943 6944 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6945 // the upper 32 bits. For other types we need to sign or zero extend 6946 // based on the opcode. 6947 unsigned ExtOpc = ISD::ANY_EXTEND; 6948 if (VT != MVT::i32) 6949 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6950 : ISD::ZERO_EXTEND; 6951 6952 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6953 break; 6954 } 6955 case ISD::UADDO: 6956 case ISD::USUBO: { 6957 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6958 "Unexpected custom legalisation"); 6959 bool IsAdd = N->getOpcode() == ISD::UADDO; 6960 // Create an ADDW or SUBW. 6961 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6962 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6963 SDValue Res = 6964 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6965 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6966 DAG.getValueType(MVT::i32)); 6967 6968 SDValue Overflow; 6969 if (IsAdd && isOneConstant(RHS)) { 6970 // Special case uaddo X, 1 overflowed if the addition result is 0. 6971 // The general case (X + C) < C is not necessarily beneficial. Although we 6972 // reduce the live range of X, we may introduce the materialization of 6973 // constant C, especially when the setcc result is used by branch. We have 6974 // no compare with constant and branch instructions. 6975 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, 6976 DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ); 6977 } else { 6978 // Sign extend the LHS and perform an unsigned compare with the ADDW 6979 // result. Since the inputs are sign extended from i32, this is equivalent 6980 // to comparing the lower 32 bits. 6981 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6982 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6983 IsAdd ? ISD::SETULT : ISD::SETUGT); 6984 } 6985 6986 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6987 Results.push_back(Overflow); 6988 return; 6989 } 6990 case ISD::UADDSAT: 6991 case ISD::USUBSAT: { 6992 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6993 "Unexpected custom legalisation"); 6994 if (Subtarget.hasStdExtZbb()) { 6995 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6996 // sign extend allows overflow of the lower 32 bits to be detected on 6997 // the promoted size. 6998 SDValue LHS = 6999 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 7000 SDValue RHS = 7001 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 7002 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 7003 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7004 return; 7005 } 7006 7007 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 7008 // promotion for UADDO/USUBO. 7009 Results.push_back(expandAddSubSat(N, DAG)); 7010 return; 7011 } 7012 case ISD::ABS: { 7013 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7014 "Unexpected custom legalisation"); 7015 7016 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 7017 7018 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7019 7020 // Freeze the source so we can increase it's use count. 7021 Src = DAG.getFreeze(Src); 7022 7023 // Copy sign bit to all bits using the sraiw pattern. 7024 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 7025 DAG.getValueType(MVT::i32)); 7026 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 7027 DAG.getConstant(31, DL, MVT::i64)); 7028 7029 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 7030 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 7031 7032 // NOTE: The result is only required to be anyextended, but sext is 7033 // consistent with type legalization of sub. 7034 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 7035 DAG.getValueType(MVT::i32)); 7036 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 7037 return; 7038 } 7039 case ISD::BITCAST: { 7040 EVT VT = N->getValueType(0); 7041 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 7042 SDValue Op0 = N->getOperand(0); 7043 EVT Op0VT = Op0.getValueType(); 7044 MVT XLenVT = Subtarget.getXLenVT(); 7045 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 7046 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 7047 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 7048 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 7049 Subtarget.hasStdExtF()) { 7050 SDValue FPConv = 7051 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 7052 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 7053 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 7054 isTypeLegal(Op0VT)) { 7055 // Custom-legalize bitcasts from fixed-length vector types to illegal 7056 // scalar types in order to improve codegen. Bitcast the vector to a 7057 // one-element vector type whose element type is the same as the result 7058 // type, and extract the first element. 7059 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 7060 if (isTypeLegal(BVT)) { 7061 SDValue BVec = DAG.getBitcast(BVT, Op0); 7062 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 7063 DAG.getConstant(0, DL, XLenVT))); 7064 } 7065 } 7066 break; 7067 } 7068 case RISCVISD::GREV: 7069 case RISCVISD::GORC: 7070 case RISCVISD::SHFL: { 7071 MVT VT = N->getSimpleValueType(0); 7072 MVT XLenVT = Subtarget.getXLenVT(); 7073 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) && 7074 "Unexpected custom legalisation"); 7075 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 7076 assert((Subtarget.hasStdExtZbp() || 7077 (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV && 7078 N->getConstantOperandVal(1) == 7)) && 7079 "Unexpected extension"); 7080 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7081 SDValue NewOp1 = 7082 DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1)); 7083 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1); 7084 // ReplaceNodeResults requires we maintain the same type for the return 7085 // value. 7086 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes)); 7087 break; 7088 } 7089 case ISD::BSWAP: 7090 case ISD::BITREVERSE: { 7091 MVT VT = N->getSimpleValueType(0); 7092 MVT XLenVT = Subtarget.getXLenVT(); 7093 assert((VT == MVT::i8 || VT == MVT::i16 || 7094 (VT == MVT::i32 && Subtarget.is64Bit())) && 7095 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 7096 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7097 unsigned Imm = VT.getSizeInBits() - 1; 7098 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 7099 if (N->getOpcode() == ISD::BSWAP) 7100 Imm &= ~0x7U; 7101 SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0, 7102 DAG.getConstant(Imm, DL, XLenVT)); 7103 // ReplaceNodeResults requires we maintain the same type for the return 7104 // value. 7105 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 7106 break; 7107 } 7108 case ISD::FSHL: 7109 case ISD::FSHR: { 7110 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7111 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 7112 SDValue NewOp0 = 7113 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7114 SDValue NewOp1 = 7115 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7116 SDValue NewShAmt = 7117 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7118 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 7119 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 7120 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 7121 DAG.getConstant(0x1f, DL, MVT::i64)); 7122 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 7123 // instruction use different orders. fshl will return its first operand for 7124 // shift of zero, fshr will return its second operand. fsl and fsr both 7125 // return rs1 so the ISD nodes need to have different operand orders. 7126 // Shift amount is in rs2. 7127 unsigned Opc = RISCVISD::FSLW; 7128 if (N->getOpcode() == ISD::FSHR) { 7129 std::swap(NewOp0, NewOp1); 7130 Opc = RISCVISD::FSRW; 7131 } 7132 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 7133 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 7134 break; 7135 } 7136 case ISD::EXTRACT_VECTOR_ELT: { 7137 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 7138 // type is illegal (currently only vXi64 RV32). 7139 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 7140 // transferred to the destination register. We issue two of these from the 7141 // upper- and lower- halves of the SEW-bit vector element, slid down to the 7142 // first element. 7143 SDValue Vec = N->getOperand(0); 7144 SDValue Idx = N->getOperand(1); 7145 7146 // The vector type hasn't been legalized yet so we can't issue target 7147 // specific nodes if it needs legalization. 7148 // FIXME: We would manually legalize if it's important. 7149 if (!isTypeLegal(Vec.getValueType())) 7150 return; 7151 7152 MVT VecVT = Vec.getSimpleValueType(); 7153 7154 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 7155 VecVT.getVectorElementType() == MVT::i64 && 7156 "Unexpected EXTRACT_VECTOR_ELT legalization"); 7157 7158 // If this is a fixed vector, we need to convert it to a scalable vector. 7159 MVT ContainerVT = VecVT; 7160 if (VecVT.isFixedLengthVector()) { 7161 ContainerVT = getContainerForFixedLengthVector(VecVT); 7162 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 7163 } 7164 7165 MVT XLenVT = Subtarget.getXLenVT(); 7166 7167 // Use a VL of 1 to avoid processing more elements than we need. 7168 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7169 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 7170 7171 // Unless the index is known to be 0, we must slide the vector down to get 7172 // the desired element into index 0. 7173 if (!isNullConstant(Idx)) { 7174 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 7175 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 7176 } 7177 7178 // Extract the lower XLEN bits of the correct vector element. 7179 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7180 7181 // To extract the upper XLEN bits of the vector element, shift the first 7182 // element right by 32 bits and re-extract the lower XLEN bits. 7183 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 7184 DAG.getUNDEF(ContainerVT), 7185 DAG.getConstant(32, DL, XLenVT), VL); 7186 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 7187 ThirtyTwoV, Mask, VL); 7188 7189 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7190 7191 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7192 break; 7193 } 7194 case ISD::INTRINSIC_WO_CHAIN: { 7195 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7196 switch (IntNo) { 7197 default: 7198 llvm_unreachable( 7199 "Don't know how to custom type legalize this intrinsic!"); 7200 case Intrinsic::riscv_grev: 7201 case Intrinsic::riscv_gorc: { 7202 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7203 "Unexpected custom legalisation"); 7204 SDValue NewOp1 = 7205 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7206 SDValue NewOp2 = 7207 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7208 unsigned Opc = 7209 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 7210 // If the control is a constant, promote the node by clearing any extra 7211 // bits bits in the control. isel will form greviw/gorciw if the result is 7212 // sign extended. 7213 if (isa<ConstantSDNode>(NewOp2)) { 7214 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7215 DAG.getConstant(0x1f, DL, MVT::i64)); 7216 Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 7217 } 7218 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7219 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7220 break; 7221 } 7222 case Intrinsic::riscv_bcompress: 7223 case Intrinsic::riscv_bdecompress: 7224 case Intrinsic::riscv_bfp: 7225 case Intrinsic::riscv_fsl: 7226 case Intrinsic::riscv_fsr: { 7227 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7228 "Unexpected custom legalisation"); 7229 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 7230 break; 7231 } 7232 case Intrinsic::riscv_orc_b: { 7233 // Lower to the GORCI encoding for orc.b with the operand extended. 7234 SDValue NewOp = 7235 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7236 SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp, 7237 DAG.getConstant(7, DL, MVT::i64)); 7238 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7239 return; 7240 } 7241 case Intrinsic::riscv_shfl: 7242 case Intrinsic::riscv_unshfl: { 7243 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7244 "Unexpected custom legalisation"); 7245 SDValue NewOp1 = 7246 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7247 SDValue NewOp2 = 7248 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7249 unsigned Opc = 7250 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 7251 // There is no (UN)SHFLIW. If the control word is a constant, we can use 7252 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 7253 // will be shuffled the same way as the lower 32 bit half, but the two 7254 // halves won't cross. 7255 if (isa<ConstantSDNode>(NewOp2)) { 7256 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7257 DAG.getConstant(0xf, DL, MVT::i64)); 7258 Opc = 7259 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 7260 } 7261 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7262 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7263 break; 7264 } 7265 case Intrinsic::riscv_vmv_x_s: { 7266 EVT VT = N->getValueType(0); 7267 MVT XLenVT = Subtarget.getXLenVT(); 7268 if (VT.bitsLT(XLenVT)) { 7269 // Simple case just extract using vmv.x.s and truncate. 7270 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 7271 Subtarget.getXLenVT(), N->getOperand(1)); 7272 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 7273 return; 7274 } 7275 7276 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 7277 "Unexpected custom legalization"); 7278 7279 // We need to do the move in two steps. 7280 SDValue Vec = N->getOperand(1); 7281 MVT VecVT = Vec.getSimpleValueType(); 7282 7283 // First extract the lower XLEN bits of the element. 7284 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7285 7286 // To extract the upper XLEN bits of the vector element, shift the first 7287 // element right by 32 bits and re-extract the lower XLEN bits. 7288 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7289 SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG); 7290 7291 SDValue ThirtyTwoV = 7292 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 7293 DAG.getConstant(32, DL, XLenVT), VL); 7294 SDValue LShr32 = 7295 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 7296 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7297 7298 Results.push_back( 7299 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7300 break; 7301 } 7302 } 7303 break; 7304 } 7305 case ISD::VECREDUCE_ADD: 7306 case ISD::VECREDUCE_AND: 7307 case ISD::VECREDUCE_OR: 7308 case ISD::VECREDUCE_XOR: 7309 case ISD::VECREDUCE_SMAX: 7310 case ISD::VECREDUCE_UMAX: 7311 case ISD::VECREDUCE_SMIN: 7312 case ISD::VECREDUCE_UMIN: 7313 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 7314 Results.push_back(V); 7315 break; 7316 case ISD::VP_REDUCE_ADD: 7317 case ISD::VP_REDUCE_AND: 7318 case ISD::VP_REDUCE_OR: 7319 case ISD::VP_REDUCE_XOR: 7320 case ISD::VP_REDUCE_SMAX: 7321 case ISD::VP_REDUCE_UMAX: 7322 case ISD::VP_REDUCE_SMIN: 7323 case ISD::VP_REDUCE_UMIN: 7324 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 7325 Results.push_back(V); 7326 break; 7327 case ISD::FLT_ROUNDS_: { 7328 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7329 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7330 Results.push_back(Res.getValue(0)); 7331 Results.push_back(Res.getValue(1)); 7332 break; 7333 } 7334 } 7335 } 7336 7337 // A structure to hold one of the bit-manipulation patterns below. Together, a 7338 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7339 // (or (and (shl x, 1), 0xAAAAAAAA), 7340 // (and (srl x, 1), 0x55555555)) 7341 struct RISCVBitmanipPat { 7342 SDValue Op; 7343 unsigned ShAmt; 7344 bool IsSHL; 7345 7346 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7347 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7348 } 7349 }; 7350 7351 // Matches patterns of the form 7352 // (and (shl x, C2), (C1 << C2)) 7353 // (and (srl x, C2), C1) 7354 // (shl (and x, C1), C2) 7355 // (srl (and x, (C1 << C2)), C2) 7356 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7357 // The expected masks for each shift amount are specified in BitmanipMasks where 7358 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7359 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7360 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7361 // XLen is 64. 7362 static Optional<RISCVBitmanipPat> 7363 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7364 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7365 "Unexpected number of masks"); 7366 Optional<uint64_t> Mask; 7367 // Optionally consume a mask around the shift operation. 7368 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7369 Mask = Op.getConstantOperandVal(1); 7370 Op = Op.getOperand(0); 7371 } 7372 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7373 return None; 7374 bool IsSHL = Op.getOpcode() == ISD::SHL; 7375 7376 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7377 return None; 7378 uint64_t ShAmt = Op.getConstantOperandVal(1); 7379 7380 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7381 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7382 return None; 7383 // If we don't have enough masks for 64 bit, then we must be trying to 7384 // match SHFL so we're only allowed to shift 1/4 of the width. 7385 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7386 return None; 7387 7388 SDValue Src = Op.getOperand(0); 7389 7390 // The expected mask is shifted left when the AND is found around SHL 7391 // patterns. 7392 // ((x >> 1) & 0x55555555) 7393 // ((x << 1) & 0xAAAAAAAA) 7394 bool SHLExpMask = IsSHL; 7395 7396 if (!Mask) { 7397 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7398 // the mask is all ones: consume that now. 7399 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7400 Mask = Src.getConstantOperandVal(1); 7401 Src = Src.getOperand(0); 7402 // The expected mask is now in fact shifted left for SRL, so reverse the 7403 // decision. 7404 // ((x & 0xAAAAAAAA) >> 1) 7405 // ((x & 0x55555555) << 1) 7406 SHLExpMask = !SHLExpMask; 7407 } else { 7408 // Use a default shifted mask of all-ones if there's no AND, truncated 7409 // down to the expected width. This simplifies the logic later on. 7410 Mask = maskTrailingOnes<uint64_t>(Width); 7411 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7412 } 7413 } 7414 7415 unsigned MaskIdx = Log2_32(ShAmt); 7416 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7417 7418 if (SHLExpMask) 7419 ExpMask <<= ShAmt; 7420 7421 if (Mask != ExpMask) 7422 return None; 7423 7424 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7425 } 7426 7427 // Matches any of the following bit-manipulation patterns: 7428 // (and (shl x, 1), (0x55555555 << 1)) 7429 // (and (srl x, 1), 0x55555555) 7430 // (shl (and x, 0x55555555), 1) 7431 // (srl (and x, (0x55555555 << 1)), 1) 7432 // where the shift amount and mask may vary thus: 7433 // [1] = 0x55555555 / 0xAAAAAAAA 7434 // [2] = 0x33333333 / 0xCCCCCCCC 7435 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7436 // [8] = 0x00FF00FF / 0xFF00FF00 7437 // [16] = 0x0000FFFF / 0xFFFFFFFF 7438 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7439 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7440 // These are the unshifted masks which we use to match bit-manipulation 7441 // patterns. They may be shifted left in certain circumstances. 7442 static const uint64_t BitmanipMasks[] = { 7443 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7444 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7445 7446 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7447 } 7448 7449 // Try to fold (<bop> x, (reduction.<bop> vec, start)) 7450 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) { 7451 auto BinOpToRVVReduce = [](unsigned Opc) { 7452 switch (Opc) { 7453 default: 7454 llvm_unreachable("Unhandled binary to transfrom reduction"); 7455 case ISD::ADD: 7456 return RISCVISD::VECREDUCE_ADD_VL; 7457 case ISD::UMAX: 7458 return RISCVISD::VECREDUCE_UMAX_VL; 7459 case ISD::SMAX: 7460 return RISCVISD::VECREDUCE_SMAX_VL; 7461 case ISD::UMIN: 7462 return RISCVISD::VECREDUCE_UMIN_VL; 7463 case ISD::SMIN: 7464 return RISCVISD::VECREDUCE_SMIN_VL; 7465 case ISD::AND: 7466 return RISCVISD::VECREDUCE_AND_VL; 7467 case ISD::OR: 7468 return RISCVISD::VECREDUCE_OR_VL; 7469 case ISD::XOR: 7470 return RISCVISD::VECREDUCE_XOR_VL; 7471 case ISD::FADD: 7472 return RISCVISD::VECREDUCE_FADD_VL; 7473 case ISD::FMAXNUM: 7474 return RISCVISD::VECREDUCE_FMAX_VL; 7475 case ISD::FMINNUM: 7476 return RISCVISD::VECREDUCE_FMIN_VL; 7477 } 7478 }; 7479 7480 auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) { 7481 return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7482 isNullConstant(V.getOperand(1)) && 7483 V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc); 7484 }; 7485 7486 unsigned Opc = N->getOpcode(); 7487 unsigned ReduceIdx; 7488 if (IsReduction(N->getOperand(0), Opc)) 7489 ReduceIdx = 0; 7490 else if (IsReduction(N->getOperand(1), Opc)) 7491 ReduceIdx = 1; 7492 else 7493 return SDValue(); 7494 7495 // Skip if FADD disallows reassociation but the combiner needs. 7496 if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation()) 7497 return SDValue(); 7498 7499 SDValue Extract = N->getOperand(ReduceIdx); 7500 SDValue Reduce = Extract.getOperand(0); 7501 if (!Reduce.hasOneUse()) 7502 return SDValue(); 7503 7504 SDValue ScalarV = Reduce.getOperand(2); 7505 7506 // Make sure that ScalarV is a splat with VL=1. 7507 if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL && 7508 ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL && 7509 ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL) 7510 return SDValue(); 7511 7512 if (!isOneConstant(ScalarV.getOperand(2))) 7513 return SDValue(); 7514 7515 // TODO: Deal with value other than neutral element. 7516 auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) { 7517 if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() && 7518 isNullFPConstant(V)) 7519 return true; 7520 return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(), 7521 N->getFlags()) == V; 7522 }; 7523 7524 // Check the scalar of ScalarV is neutral element 7525 if (!IsRVVNeutralElement(N, ScalarV.getOperand(1))) 7526 return SDValue(); 7527 7528 if (!ScalarV.hasOneUse()) 7529 return SDValue(); 7530 7531 EVT SplatVT = ScalarV.getValueType(); 7532 SDValue NewStart = N->getOperand(1 - ReduceIdx); 7533 unsigned SplatOpc = RISCVISD::VFMV_S_F_VL; 7534 if (SplatVT.isInteger()) { 7535 auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode()); 7536 if (!C || C->isZero() || !isInt<5>(C->getSExtValue())) 7537 SplatOpc = RISCVISD::VMV_S_X_VL; 7538 else 7539 SplatOpc = RISCVISD::VMV_V_X_VL; 7540 } 7541 7542 SDValue NewScalarV = 7543 DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart, 7544 ScalarV.getOperand(2)); 7545 SDValue NewReduce = 7546 DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(), 7547 Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV, 7548 Reduce.getOperand(3), Reduce.getOperand(4)); 7549 return DAG.getNode(Extract.getOpcode(), SDLoc(Extract), 7550 Extract.getValueType(), NewReduce, Extract.getOperand(1)); 7551 } 7552 7553 // Match the following pattern as a GREVI(W) operation 7554 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7555 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7556 const RISCVSubtarget &Subtarget) { 7557 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7558 EVT VT = Op.getValueType(); 7559 7560 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7561 auto LHS = matchGREVIPat(Op.getOperand(0)); 7562 auto RHS = matchGREVIPat(Op.getOperand(1)); 7563 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7564 SDLoc DL(Op); 7565 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7566 DAG.getConstant(LHS->ShAmt, DL, VT)); 7567 } 7568 } 7569 return SDValue(); 7570 } 7571 7572 // Matches any the following pattern as a GORCI(W) operation 7573 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7574 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7575 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7576 // Note that with the variant of 3., 7577 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7578 // the inner pattern will first be matched as GREVI and then the outer 7579 // pattern will be matched to GORC via the first rule above. 7580 // 4. (or (rotl/rotr x, bitwidth/2), x) 7581 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7582 const RISCVSubtarget &Subtarget) { 7583 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7584 EVT VT = Op.getValueType(); 7585 7586 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7587 SDLoc DL(Op); 7588 SDValue Op0 = Op.getOperand(0); 7589 SDValue Op1 = Op.getOperand(1); 7590 7591 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7592 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7593 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7594 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7595 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7596 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7597 if ((Reverse.getOpcode() == ISD::ROTL || 7598 Reverse.getOpcode() == ISD::ROTR) && 7599 Reverse.getOperand(0) == X && 7600 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7601 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7602 if (RotAmt == (VT.getSizeInBits() / 2)) 7603 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7604 DAG.getConstant(RotAmt, DL, VT)); 7605 } 7606 return SDValue(); 7607 }; 7608 7609 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7610 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7611 return V; 7612 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7613 return V; 7614 7615 // OR is commutable so canonicalize its OR operand to the left 7616 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7617 std::swap(Op0, Op1); 7618 if (Op0.getOpcode() != ISD::OR) 7619 return SDValue(); 7620 SDValue OrOp0 = Op0.getOperand(0); 7621 SDValue OrOp1 = Op0.getOperand(1); 7622 auto LHS = matchGREVIPat(OrOp0); 7623 // OR is commutable so swap the operands and try again: x might have been 7624 // on the left 7625 if (!LHS) { 7626 std::swap(OrOp0, OrOp1); 7627 LHS = matchGREVIPat(OrOp0); 7628 } 7629 auto RHS = matchGREVIPat(Op1); 7630 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7631 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7632 DAG.getConstant(LHS->ShAmt, DL, VT)); 7633 } 7634 } 7635 return SDValue(); 7636 } 7637 7638 // Matches any of the following bit-manipulation patterns: 7639 // (and (shl x, 1), (0x22222222 << 1)) 7640 // (and (srl x, 1), 0x22222222) 7641 // (shl (and x, 0x22222222), 1) 7642 // (srl (and x, (0x22222222 << 1)), 1) 7643 // where the shift amount and mask may vary thus: 7644 // [1] = 0x22222222 / 0x44444444 7645 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7646 // [4] = 0x00F000F0 / 0x0F000F00 7647 // [8] = 0x0000FF00 / 0x00FF0000 7648 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7649 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7650 // These are the unshifted masks which we use to match bit-manipulation 7651 // patterns. They may be shifted left in certain circumstances. 7652 static const uint64_t BitmanipMasks[] = { 7653 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7654 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7655 7656 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7657 } 7658 7659 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7660 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7661 const RISCVSubtarget &Subtarget) { 7662 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7663 EVT VT = Op.getValueType(); 7664 7665 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7666 return SDValue(); 7667 7668 SDValue Op0 = Op.getOperand(0); 7669 SDValue Op1 = Op.getOperand(1); 7670 7671 // Or is commutable so canonicalize the second OR to the LHS. 7672 if (Op0.getOpcode() != ISD::OR) 7673 std::swap(Op0, Op1); 7674 if (Op0.getOpcode() != ISD::OR) 7675 return SDValue(); 7676 7677 // We found an inner OR, so our operands are the operands of the inner OR 7678 // and the other operand of the outer OR. 7679 SDValue A = Op0.getOperand(0); 7680 SDValue B = Op0.getOperand(1); 7681 SDValue C = Op1; 7682 7683 auto Match1 = matchSHFLPat(A); 7684 auto Match2 = matchSHFLPat(B); 7685 7686 // If neither matched, we failed. 7687 if (!Match1 && !Match2) 7688 return SDValue(); 7689 7690 // We had at least one match. if one failed, try the remaining C operand. 7691 if (!Match1) { 7692 std::swap(A, C); 7693 Match1 = matchSHFLPat(A); 7694 if (!Match1) 7695 return SDValue(); 7696 } else if (!Match2) { 7697 std::swap(B, C); 7698 Match2 = matchSHFLPat(B); 7699 if (!Match2) 7700 return SDValue(); 7701 } 7702 assert(Match1 && Match2); 7703 7704 // Make sure our matches pair up. 7705 if (!Match1->formsPairWith(*Match2)) 7706 return SDValue(); 7707 7708 // All the remains is to make sure C is an AND with the same input, that masks 7709 // out the bits that are being shuffled. 7710 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7711 C.getOperand(0) != Match1->Op) 7712 return SDValue(); 7713 7714 uint64_t Mask = C.getConstantOperandVal(1); 7715 7716 static const uint64_t BitmanipMasks[] = { 7717 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7718 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7719 }; 7720 7721 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7722 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7723 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7724 7725 if (Mask != ExpMask) 7726 return SDValue(); 7727 7728 SDLoc DL(Op); 7729 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7730 DAG.getConstant(Match1->ShAmt, DL, VT)); 7731 } 7732 7733 // Optimize (add (shl x, c0), (shl y, c1)) -> 7734 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7735 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7736 const RISCVSubtarget &Subtarget) { 7737 // Perform this optimization only in the zba extension. 7738 if (!Subtarget.hasStdExtZba()) 7739 return SDValue(); 7740 7741 // Skip for vector types and larger types. 7742 EVT VT = N->getValueType(0); 7743 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7744 return SDValue(); 7745 7746 // The two operand nodes must be SHL and have no other use. 7747 SDValue N0 = N->getOperand(0); 7748 SDValue N1 = N->getOperand(1); 7749 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7750 !N0->hasOneUse() || !N1->hasOneUse()) 7751 return SDValue(); 7752 7753 // Check c0 and c1. 7754 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7755 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7756 if (!N0C || !N1C) 7757 return SDValue(); 7758 int64_t C0 = N0C->getSExtValue(); 7759 int64_t C1 = N1C->getSExtValue(); 7760 if (C0 <= 0 || C1 <= 0) 7761 return SDValue(); 7762 7763 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7764 int64_t Bits = std::min(C0, C1); 7765 int64_t Diff = std::abs(C0 - C1); 7766 if (Diff != 1 && Diff != 2 && Diff != 3) 7767 return SDValue(); 7768 7769 // Build nodes. 7770 SDLoc DL(N); 7771 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7772 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7773 SDValue NA0 = 7774 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7775 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7776 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7777 } 7778 7779 // Combine 7780 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7781 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7782 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7783 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7784 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7785 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7786 // The grev patterns represents BSWAP. 7787 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7788 // off the grev. 7789 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7790 const RISCVSubtarget &Subtarget) { 7791 bool IsWInstruction = 7792 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7793 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7794 IsWInstruction) && 7795 "Unexpected opcode!"); 7796 SDValue Src = N->getOperand(0); 7797 EVT VT = N->getValueType(0); 7798 SDLoc DL(N); 7799 7800 if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV) 7801 return SDValue(); 7802 7803 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7804 !isa<ConstantSDNode>(Src.getOperand(1))) 7805 return SDValue(); 7806 7807 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7808 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7809 7810 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7811 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7812 unsigned ShAmt1 = N->getConstantOperandVal(1); 7813 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7814 if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7815 return SDValue(); 7816 7817 Src = Src.getOperand(0); 7818 7819 // Toggle bit the MSB of the shift. 7820 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7821 if (CombinedShAmt == 0) 7822 return Src; 7823 7824 SDValue Res = DAG.getNode( 7825 RISCVISD::GREV, DL, VT, Src, 7826 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7827 if (!IsWInstruction) 7828 return Res; 7829 7830 // Sign extend the result to match the behavior of the rotate. This will be 7831 // selected to GREVIW in isel. 7832 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res, 7833 DAG.getValueType(MVT::i32)); 7834 } 7835 7836 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7837 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7838 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7839 // not undo itself, but they are redundant. 7840 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7841 bool IsGORC = N->getOpcode() == RISCVISD::GORC; 7842 assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode"); 7843 SDValue Src = N->getOperand(0); 7844 7845 if (Src.getOpcode() != N->getOpcode()) 7846 return SDValue(); 7847 7848 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7849 !isa<ConstantSDNode>(Src.getOperand(1))) 7850 return SDValue(); 7851 7852 unsigned ShAmt1 = N->getConstantOperandVal(1); 7853 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7854 Src = Src.getOperand(0); 7855 7856 unsigned CombinedShAmt; 7857 if (IsGORC) 7858 CombinedShAmt = ShAmt1 | ShAmt2; 7859 else 7860 CombinedShAmt = ShAmt1 ^ ShAmt2; 7861 7862 if (CombinedShAmt == 0) 7863 return Src; 7864 7865 SDLoc DL(N); 7866 return DAG.getNode( 7867 N->getOpcode(), DL, N->getValueType(0), Src, 7868 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7869 } 7870 7871 // Combine a constant select operand into its use: 7872 // 7873 // (and (select cond, -1, c), x) 7874 // -> (select cond, x, (and x, c)) [AllOnes=1] 7875 // (or (select cond, 0, c), x) 7876 // -> (select cond, x, (or x, c)) [AllOnes=0] 7877 // (xor (select cond, 0, c), x) 7878 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7879 // (add (select cond, 0, c), x) 7880 // -> (select cond, x, (add x, c)) [AllOnes=0] 7881 // (sub x, (select cond, 0, c)) 7882 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7883 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7884 SelectionDAG &DAG, bool AllOnes) { 7885 EVT VT = N->getValueType(0); 7886 7887 // Skip vectors. 7888 if (VT.isVector()) 7889 return SDValue(); 7890 7891 if ((Slct.getOpcode() != ISD::SELECT && 7892 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7893 !Slct.hasOneUse()) 7894 return SDValue(); 7895 7896 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7897 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7898 }; 7899 7900 bool SwapSelectOps; 7901 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7902 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7903 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7904 SDValue NonConstantVal; 7905 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7906 SwapSelectOps = false; 7907 NonConstantVal = FalseVal; 7908 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7909 SwapSelectOps = true; 7910 NonConstantVal = TrueVal; 7911 } else 7912 return SDValue(); 7913 7914 // Slct is now know to be the desired identity constant when CC is true. 7915 TrueVal = OtherOp; 7916 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7917 // Unless SwapSelectOps says the condition should be false. 7918 if (SwapSelectOps) 7919 std::swap(TrueVal, FalseVal); 7920 7921 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7922 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7923 {Slct.getOperand(0), Slct.getOperand(1), 7924 Slct.getOperand(2), TrueVal, FalseVal}); 7925 7926 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7927 {Slct.getOperand(0), TrueVal, FalseVal}); 7928 } 7929 7930 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7931 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7932 bool AllOnes) { 7933 SDValue N0 = N->getOperand(0); 7934 SDValue N1 = N->getOperand(1); 7935 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7936 return Result; 7937 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7938 return Result; 7939 return SDValue(); 7940 } 7941 7942 // Transform (add (mul x, c0), c1) -> 7943 // (add (mul (add x, c1/c0), c0), c1%c0). 7944 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7945 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7946 // to an infinite loop in DAGCombine if transformed. 7947 // Or transform (add (mul x, c0), c1) -> 7948 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7949 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7950 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7951 // lead to an infinite loop in DAGCombine if transformed. 7952 // Or transform (add (mul x, c0), c1) -> 7953 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7954 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7955 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7956 // lead to an infinite loop in DAGCombine if transformed. 7957 // Or transform (add (mul x, c0), c1) -> 7958 // (mul (add x, c1/c0), c0). 7959 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7960 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7961 const RISCVSubtarget &Subtarget) { 7962 // Skip for vector types and larger types. 7963 EVT VT = N->getValueType(0); 7964 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7965 return SDValue(); 7966 // The first operand node must be a MUL and has no other use. 7967 SDValue N0 = N->getOperand(0); 7968 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7969 return SDValue(); 7970 // Check if c0 and c1 match above conditions. 7971 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7972 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7973 if (!N0C || !N1C) 7974 return SDValue(); 7975 // If N0C has multiple uses it's possible one of the cases in 7976 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 7977 // in an infinite loop. 7978 if (!N0C->hasOneUse()) 7979 return SDValue(); 7980 int64_t C0 = N0C->getSExtValue(); 7981 int64_t C1 = N1C->getSExtValue(); 7982 int64_t CA, CB; 7983 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7984 return SDValue(); 7985 // Search for proper CA (non-zero) and CB that both are simm12. 7986 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7987 !isInt<12>(C0 * (C1 / C0))) { 7988 CA = C1 / C0; 7989 CB = C1 % C0; 7990 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7991 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7992 CA = C1 / C0 + 1; 7993 CB = C1 % C0 - C0; 7994 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7995 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7996 CA = C1 / C0 - 1; 7997 CB = C1 % C0 + C0; 7998 } else 7999 return SDValue(); 8000 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 8001 SDLoc DL(N); 8002 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 8003 DAG.getConstant(CA, DL, VT)); 8004 SDValue New1 = 8005 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 8006 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 8007 } 8008 8009 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 8010 const RISCVSubtarget &Subtarget) { 8011 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 8012 return V; 8013 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 8014 return V; 8015 if (SDValue V = combineBinOpToReduce(N, DAG)) 8016 return V; 8017 // fold (add (select lhs, rhs, cc, 0, y), x) -> 8018 // (select lhs, rhs, cc, x, (add x, y)) 8019 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8020 } 8021 8022 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 8023 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 8024 // (select lhs, rhs, cc, x, (sub x, y)) 8025 SDValue N0 = N->getOperand(0); 8026 SDValue N1 = N->getOperand(1); 8027 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 8028 } 8029 8030 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG, 8031 const RISCVSubtarget &Subtarget) { 8032 SDValue N0 = N->getOperand(0); 8033 // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero 8034 // extending X. This is safe since we only need the LSB after the shift and 8035 // shift amounts larger than 31 would produce poison. If we wait until 8036 // type legalization, we'll create RISCVISD::SRLW and we can't recover it 8037 // to use a BEXT instruction. 8038 if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() && 8039 N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) && 8040 N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) && 8041 N0.hasOneUse()) { 8042 SDLoc DL(N); 8043 SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0)); 8044 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1)); 8045 SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1); 8046 SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl, 8047 DAG.getConstant(1, DL, MVT::i64)); 8048 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And); 8049 } 8050 8051 if (SDValue V = combineBinOpToReduce(N, DAG)) 8052 return V; 8053 8054 // fold (and (select lhs, rhs, cc, -1, y), x) -> 8055 // (select lhs, rhs, cc, x, (and x, y)) 8056 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 8057 } 8058 8059 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 8060 const RISCVSubtarget &Subtarget) { 8061 if (Subtarget.hasStdExtZbp()) { 8062 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 8063 return GREV; 8064 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 8065 return GORC; 8066 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 8067 return SHFL; 8068 } 8069 8070 if (SDValue V = combineBinOpToReduce(N, DAG)) 8071 return V; 8072 // fold (or (select cond, 0, y), x) -> 8073 // (select cond, x, (or x, y)) 8074 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8075 } 8076 8077 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 8078 SDValue N0 = N->getOperand(0); 8079 SDValue N1 = N->getOperand(1); 8080 8081 // fold (xor (sllw 1, x), -1) -> (rolw ~1, x) 8082 // NOTE: Assumes ROL being legal means ROLW is legal. 8083 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8084 if (N0.getOpcode() == RISCVISD::SLLW && 8085 isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) && 8086 TLI.isOperationLegal(ISD::ROTL, MVT::i64)) { 8087 SDLoc DL(N); 8088 return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64, 8089 DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1)); 8090 } 8091 8092 if (SDValue V = combineBinOpToReduce(N, DAG)) 8093 return V; 8094 // fold (xor (select cond, 0, y), x) -> 8095 // (select cond, x, (xor x, y)) 8096 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8097 } 8098 8099 static SDValue 8100 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 8101 const RISCVSubtarget &Subtarget) { 8102 SDValue Src = N->getOperand(0); 8103 EVT VT = N->getValueType(0); 8104 8105 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 8106 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8107 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 8108 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 8109 Src.getOperand(0)); 8110 8111 // Fold (i64 (sext_inreg (abs X), i32)) -> 8112 // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits. 8113 // The (sext_inreg (neg X), i32) will be selected to negw by isel. This 8114 // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user 8115 // of the (i32 (abs X)) is a sext or setcc or something else that causes type 8116 // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have 8117 // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg 8118 // may get combined into an earlier operation so we need to use 8119 // ComputeNumSignBits. 8120 // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for 8121 // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so 8122 // we can't assume that X has 33 sign bits. We must check. 8123 if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() && 8124 Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 && 8125 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 && 8126 DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) { 8127 SDLoc DL(N); 8128 SDValue Freeze = DAG.getFreeze(Src.getOperand(0)); 8129 SDValue Neg = 8130 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze); 8131 Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg, 8132 DAG.getValueType(MVT::i32)); 8133 return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg); 8134 } 8135 8136 return SDValue(); 8137 } 8138 8139 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 8140 // vwadd(u).vv/vx or vwsub(u).vv/vx. 8141 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 8142 bool Commute = false) { 8143 assert((N->getOpcode() == RISCVISD::ADD_VL || 8144 N->getOpcode() == RISCVISD::SUB_VL) && 8145 "Unexpected opcode"); 8146 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 8147 SDValue Op0 = N->getOperand(0); 8148 SDValue Op1 = N->getOperand(1); 8149 if (Commute) 8150 std::swap(Op0, Op1); 8151 8152 MVT VT = N->getSimpleValueType(0); 8153 8154 // Determine the narrow size for a widening add/sub. 8155 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8156 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8157 VT.getVectorElementCount()); 8158 8159 SDValue Mask = N->getOperand(2); 8160 SDValue VL = N->getOperand(3); 8161 8162 SDLoc DL(N); 8163 8164 // If the RHS is a sext or zext, we can form a widening op. 8165 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 8166 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 8167 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 8168 unsigned ExtOpc = Op1.getOpcode(); 8169 Op1 = Op1.getOperand(0); 8170 // Re-introduce narrower extends if needed. 8171 if (Op1.getValueType() != NarrowVT) 8172 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8173 8174 unsigned WOpc; 8175 if (ExtOpc == RISCVISD::VSEXT_VL) 8176 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 8177 else 8178 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 8179 8180 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 8181 } 8182 8183 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 8184 // sext/zext? 8185 8186 return SDValue(); 8187 } 8188 8189 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 8190 // vwsub(u).vv/vx. 8191 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 8192 SDValue Op0 = N->getOperand(0); 8193 SDValue Op1 = N->getOperand(1); 8194 SDValue Mask = N->getOperand(2); 8195 SDValue VL = N->getOperand(3); 8196 8197 MVT VT = N->getSimpleValueType(0); 8198 MVT NarrowVT = Op1.getSimpleValueType(); 8199 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 8200 8201 unsigned VOpc; 8202 switch (N->getOpcode()) { 8203 default: llvm_unreachable("Unexpected opcode"); 8204 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 8205 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 8206 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 8207 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 8208 } 8209 8210 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 8211 N->getOpcode() == RISCVISD::VWSUB_W_VL; 8212 8213 SDLoc DL(N); 8214 8215 // If the LHS is a sext or zext, we can narrow this op to the same size as 8216 // the RHS. 8217 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 8218 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 8219 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 8220 unsigned ExtOpc = Op0.getOpcode(); 8221 Op0 = Op0.getOperand(0); 8222 // Re-introduce narrower extends if needed. 8223 if (Op0.getValueType() != NarrowVT) 8224 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8225 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 8226 } 8227 8228 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 8229 N->getOpcode() == RISCVISD::VWADDU_W_VL; 8230 8231 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 8232 // to commute and use a vwadd(u).vx instead. 8233 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 8234 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 8235 Op0 = Op0.getOperand(1); 8236 8237 // See if have enough sign bits or zero bits in the scalar to use a 8238 // widening add/sub by splatting to smaller element size. 8239 unsigned EltBits = VT.getScalarSizeInBits(); 8240 unsigned ScalarBits = Op0.getValueSizeInBits(); 8241 // Make sure we're getting all element bits from the scalar register. 8242 // FIXME: Support implicit sign extension of vmv.v.x? 8243 if (ScalarBits < EltBits) 8244 return SDValue(); 8245 8246 if (IsSigned) { 8247 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 8248 return SDValue(); 8249 } else { 8250 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8251 if (!DAG.MaskedValueIsZero(Op0, Mask)) 8252 return SDValue(); 8253 } 8254 8255 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8256 DAG.getUNDEF(NarrowVT), Op0, VL); 8257 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 8258 } 8259 8260 return SDValue(); 8261 } 8262 8263 // Try to form VWMUL, VWMULU or VWMULSU. 8264 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 8265 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 8266 bool Commute) { 8267 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 8268 SDValue Op0 = N->getOperand(0); 8269 SDValue Op1 = N->getOperand(1); 8270 if (Commute) 8271 std::swap(Op0, Op1); 8272 8273 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 8274 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 8275 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 8276 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 8277 return SDValue(); 8278 8279 SDValue Mask = N->getOperand(2); 8280 SDValue VL = N->getOperand(3); 8281 8282 // Make sure the mask and VL match. 8283 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 8284 return SDValue(); 8285 8286 MVT VT = N->getSimpleValueType(0); 8287 8288 // Determine the narrow size for a widening multiply. 8289 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8290 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8291 VT.getVectorElementCount()); 8292 8293 SDLoc DL(N); 8294 8295 // See if the other operand is the same opcode. 8296 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 8297 if (!Op1.hasOneUse()) 8298 return SDValue(); 8299 8300 // Make sure the mask and VL match. 8301 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 8302 return SDValue(); 8303 8304 Op1 = Op1.getOperand(0); 8305 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 8306 // The operand is a splat of a scalar. 8307 8308 // The pasthru must be undef for tail agnostic 8309 if (!Op1.getOperand(0).isUndef()) 8310 return SDValue(); 8311 // The VL must be the same. 8312 if (Op1.getOperand(2) != VL) 8313 return SDValue(); 8314 8315 // Get the scalar value. 8316 Op1 = Op1.getOperand(1); 8317 8318 // See if have enough sign bits or zero bits in the scalar to use a 8319 // widening multiply by splatting to smaller element size. 8320 unsigned EltBits = VT.getScalarSizeInBits(); 8321 unsigned ScalarBits = Op1.getValueSizeInBits(); 8322 // Make sure we're getting all element bits from the scalar register. 8323 // FIXME: Support implicit sign extension of vmv.v.x? 8324 if (ScalarBits < EltBits) 8325 return SDValue(); 8326 8327 // If the LHS is a sign extend, try to use vwmul. 8328 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 8329 // Can use vwmul. 8330 } else { 8331 // Otherwise try to use vwmulu or vwmulsu. 8332 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8333 if (DAG.MaskedValueIsZero(Op1, Mask)) 8334 IsVWMULSU = IsSignExt; 8335 else 8336 return SDValue(); 8337 } 8338 8339 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8340 DAG.getUNDEF(NarrowVT), Op1, VL); 8341 } else 8342 return SDValue(); 8343 8344 Op0 = Op0.getOperand(0); 8345 8346 // Re-introduce narrower extends if needed. 8347 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 8348 if (Op0.getValueType() != NarrowVT) 8349 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8350 // vwmulsu requires second operand to be zero extended. 8351 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 8352 if (Op1.getValueType() != NarrowVT) 8353 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8354 8355 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 8356 if (!IsVWMULSU) 8357 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 8358 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 8359 } 8360 8361 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 8362 switch (Op.getOpcode()) { 8363 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 8364 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 8365 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 8366 case ISD::FCEIL: return RISCVFPRndMode::RUP; 8367 case ISD::FROUND: return RISCVFPRndMode::RMM; 8368 } 8369 8370 return RISCVFPRndMode::Invalid; 8371 } 8372 8373 // Fold 8374 // (fp_to_int (froundeven X)) -> fcvt X, rne 8375 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 8376 // (fp_to_int (ffloor X)) -> fcvt X, rdn 8377 // (fp_to_int (fceil X)) -> fcvt X, rup 8378 // (fp_to_int (fround X)) -> fcvt X, rmm 8379 static SDValue performFP_TO_INTCombine(SDNode *N, 8380 TargetLowering::DAGCombinerInfo &DCI, 8381 const RISCVSubtarget &Subtarget) { 8382 SelectionDAG &DAG = DCI.DAG; 8383 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8384 MVT XLenVT = Subtarget.getXLenVT(); 8385 8386 // Only handle XLen or i32 types. Other types narrower than XLen will 8387 // eventually be legalized to XLenVT. 8388 EVT VT = N->getValueType(0); 8389 if (VT != MVT::i32 && VT != XLenVT) 8390 return SDValue(); 8391 8392 SDValue Src = N->getOperand(0); 8393 8394 // Ensure the FP type is also legal. 8395 if (!TLI.isTypeLegal(Src.getValueType())) 8396 return SDValue(); 8397 8398 // Don't do this for f16 with Zfhmin and not Zfh. 8399 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8400 return SDValue(); 8401 8402 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8403 if (FRM == RISCVFPRndMode::Invalid) 8404 return SDValue(); 8405 8406 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8407 8408 unsigned Opc; 8409 if (VT == XLenVT) 8410 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8411 else 8412 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8413 8414 SDLoc DL(N); 8415 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 8416 DAG.getTargetConstant(FRM, DL, XLenVT)); 8417 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 8418 } 8419 8420 // Fold 8421 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 8422 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 8423 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8424 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8425 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8426 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8427 TargetLowering::DAGCombinerInfo &DCI, 8428 const RISCVSubtarget &Subtarget) { 8429 SelectionDAG &DAG = DCI.DAG; 8430 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8431 MVT XLenVT = Subtarget.getXLenVT(); 8432 8433 // Only handle XLen types. Other types narrower than XLen will eventually be 8434 // legalized to XLenVT. 8435 EVT DstVT = N->getValueType(0); 8436 if (DstVT != XLenVT) 8437 return SDValue(); 8438 8439 SDValue Src = N->getOperand(0); 8440 8441 // Ensure the FP type is also legal. 8442 if (!TLI.isTypeLegal(Src.getValueType())) 8443 return SDValue(); 8444 8445 // Don't do this for f16 with Zfhmin and not Zfh. 8446 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8447 return SDValue(); 8448 8449 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8450 8451 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8452 if (FRM == RISCVFPRndMode::Invalid) 8453 return SDValue(); 8454 8455 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8456 8457 unsigned Opc; 8458 if (SatVT == DstVT) 8459 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8460 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8461 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8462 else 8463 return SDValue(); 8464 // FIXME: Support other SatVTs by clamping before or after the conversion. 8465 8466 Src = Src.getOperand(0); 8467 8468 SDLoc DL(N); 8469 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8470 DAG.getTargetConstant(FRM, DL, XLenVT)); 8471 8472 // RISCV FP-to-int conversions saturate to the destination register size, but 8473 // don't produce 0 for nan. 8474 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8475 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8476 } 8477 8478 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is 8479 // smaller than XLenVT. 8480 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG, 8481 const RISCVSubtarget &Subtarget) { 8482 assert(Subtarget.hasStdExtZbkb() && "Unexpected extension"); 8483 8484 SDValue Src = N->getOperand(0); 8485 if (Src.getOpcode() != ISD::BSWAP) 8486 return SDValue(); 8487 8488 EVT VT = N->getValueType(0); 8489 if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() || 8490 !isPowerOf2_32(VT.getSizeInBits())) 8491 return SDValue(); 8492 8493 SDLoc DL(N); 8494 return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0), 8495 DAG.getConstant(7, DL, VT)); 8496 } 8497 8498 // Convert from one FMA opcode to another based on whether we are negating the 8499 // multiply result and/or the accumulator. 8500 // NOTE: Only supports RVV operations with VL. 8501 static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc) { 8502 assert((NegMul || NegAcc) && "Not negating anything?"); 8503 8504 // Negating the multiply result changes ADD<->SUB and toggles 'N'. 8505 if (NegMul) { 8506 // clang-format off 8507 switch (Opcode) { 8508 default: llvm_unreachable("Unexpected opcode"); 8509 case RISCVISD::VFMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break; 8510 case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFMADD_VL; break; 8511 case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFMSUB_VL; break; 8512 case RISCVISD::VFMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break; 8513 } 8514 // clang-format on 8515 } 8516 8517 // Negating the accumulator changes ADD<->SUB. 8518 if (NegAcc) { 8519 // clang-format off 8520 switch (Opcode) { 8521 default: llvm_unreachable("Unexpected opcode"); 8522 case RISCVISD::VFMADD_VL: Opcode = RISCVISD::VFMSUB_VL; break; 8523 case RISCVISD::VFMSUB_VL: Opcode = RISCVISD::VFMADD_VL; break; 8524 case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break; 8525 case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break; 8526 } 8527 // clang-format on 8528 } 8529 8530 return Opcode; 8531 } 8532 8533 // Combine (sra (shl X, 32), 32 - C) -> (shl (sext_inreg X, i32), C) 8534 // FIXME: Should this be a generic combine? There's a similar combine on X86. 8535 // 8536 // Also try these folds where an add or sub is in the middle. 8537 // (sra (add (shl X, 32), C1), 32 - C) -> (shl (sext_inreg (add X, C1), C) 8538 // (sra (sub C1, (shl X, 32)), 32 - C) -> (shl (sext_inreg (sub C1, X), C) 8539 static SDValue performSRACombine(SDNode *N, SelectionDAG &DAG, 8540 const RISCVSubtarget &Subtarget) { 8541 assert(N->getOpcode() == ISD::SRA && "Unexpected opcode"); 8542 8543 if (N->getValueType(0) != MVT::i64 || !Subtarget.is64Bit()) 8544 return SDValue(); 8545 8546 auto *ShAmtC = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8547 if (!ShAmtC || ShAmtC->getZExtValue() > 32) 8548 return SDValue(); 8549 8550 SDValue N0 = N->getOperand(0); 8551 8552 SDValue Shl; 8553 ConstantSDNode *AddC = nullptr; 8554 8555 // We might have an ADD or SUB between the SRA and SHL. 8556 bool IsAdd = N0.getOpcode() == ISD::ADD; 8557 if ((IsAdd || N0.getOpcode() == ISD::SUB)) { 8558 if (!N0.hasOneUse()) 8559 return SDValue(); 8560 // Other operand needs to be a constant we can modify. 8561 AddC = dyn_cast<ConstantSDNode>(N0.getOperand(IsAdd ? 1 : 0)); 8562 if (!AddC) 8563 return SDValue(); 8564 8565 // AddC needs to have at least 32 trailing zeros. 8566 if (AddC->getAPIntValue().countTrailingZeros() < 32) 8567 return SDValue(); 8568 8569 Shl = N0.getOperand(IsAdd ? 0 : 1); 8570 } else { 8571 // Not an ADD or SUB. 8572 Shl = N0; 8573 } 8574 8575 // Look for a shift left by 32. 8576 if (Shl.getOpcode() != ISD::SHL || !Shl.hasOneUse() || 8577 !isa<ConstantSDNode>(Shl.getOperand(1)) || 8578 Shl.getConstantOperandVal(1) != 32) 8579 return SDValue(); 8580 8581 SDLoc DL(N); 8582 SDValue In = Shl.getOperand(0); 8583 8584 // If we looked through an ADD or SUB, we need to rebuild it with the shifted 8585 // constant. 8586 if (AddC) { 8587 SDValue ShiftedAddC = 8588 DAG.getConstant(AddC->getAPIntValue().lshr(32), DL, MVT::i64); 8589 if (IsAdd) 8590 In = DAG.getNode(ISD::ADD, DL, MVT::i64, In, ShiftedAddC); 8591 else 8592 In = DAG.getNode(ISD::SUB, DL, MVT::i64, ShiftedAddC, In); 8593 } 8594 8595 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, In, 8596 DAG.getValueType(MVT::i32)); 8597 if (ShAmtC->getZExtValue() == 32) 8598 return SExt; 8599 8600 return DAG.getNode( 8601 ISD::SHL, DL, MVT::i64, SExt, 8602 DAG.getConstant(32 - ShAmtC->getZExtValue(), DL, MVT::i64)); 8603 } 8604 8605 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8606 DAGCombinerInfo &DCI) const { 8607 SelectionDAG &DAG = DCI.DAG; 8608 8609 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8610 // bits are demanded. N will be added to the Worklist if it was not deleted. 8611 // Caller should return SDValue(N, 0) if this returns true. 8612 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8613 SDValue Op = N->getOperand(OpNo); 8614 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8615 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8616 return false; 8617 8618 if (N->getOpcode() != ISD::DELETED_NODE) 8619 DCI.AddToWorklist(N); 8620 return true; 8621 }; 8622 8623 switch (N->getOpcode()) { 8624 default: 8625 break; 8626 case RISCVISD::SplitF64: { 8627 SDValue Op0 = N->getOperand(0); 8628 // If the input to SplitF64 is just BuildPairF64 then the operation is 8629 // redundant. Instead, use BuildPairF64's operands directly. 8630 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8631 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8632 8633 if (Op0->isUndef()) { 8634 SDValue Lo = DAG.getUNDEF(MVT::i32); 8635 SDValue Hi = DAG.getUNDEF(MVT::i32); 8636 return DCI.CombineTo(N, Lo, Hi); 8637 } 8638 8639 SDLoc DL(N); 8640 8641 // It's cheaper to materialise two 32-bit integers than to load a double 8642 // from the constant pool and transfer it to integer registers through the 8643 // stack. 8644 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8645 APInt V = C->getValueAPF().bitcastToAPInt(); 8646 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8647 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8648 return DCI.CombineTo(N, Lo, Hi); 8649 } 8650 8651 // This is a target-specific version of a DAGCombine performed in 8652 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8653 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8654 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8655 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8656 !Op0.getNode()->hasOneUse()) 8657 break; 8658 SDValue NewSplitF64 = 8659 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8660 Op0.getOperand(0)); 8661 SDValue Lo = NewSplitF64.getValue(0); 8662 SDValue Hi = NewSplitF64.getValue(1); 8663 APInt SignBit = APInt::getSignMask(32); 8664 if (Op0.getOpcode() == ISD::FNEG) { 8665 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8666 DAG.getConstant(SignBit, DL, MVT::i32)); 8667 return DCI.CombineTo(N, Lo, NewHi); 8668 } 8669 assert(Op0.getOpcode() == ISD::FABS); 8670 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8671 DAG.getConstant(~SignBit, DL, MVT::i32)); 8672 return DCI.CombineTo(N, Lo, NewHi); 8673 } 8674 case RISCVISD::SLLW: 8675 case RISCVISD::SRAW: 8676 case RISCVISD::SRLW: { 8677 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8678 if (SimplifyDemandedLowBitsHelper(0, 32) || 8679 SimplifyDemandedLowBitsHelper(1, 5)) 8680 return SDValue(N, 0); 8681 8682 break; 8683 } 8684 case ISD::ROTR: 8685 case ISD::ROTL: 8686 case RISCVISD::RORW: 8687 case RISCVISD::ROLW: { 8688 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8689 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8690 if (SimplifyDemandedLowBitsHelper(0, 32) || 8691 SimplifyDemandedLowBitsHelper(1, 5)) 8692 return SDValue(N, 0); 8693 } 8694 8695 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8696 } 8697 case RISCVISD::CLZW: 8698 case RISCVISD::CTZW: { 8699 // Only the lower 32 bits of the first operand are read 8700 if (SimplifyDemandedLowBitsHelper(0, 32)) 8701 return SDValue(N, 0); 8702 break; 8703 } 8704 case RISCVISD::GREV: 8705 case RISCVISD::GORC: { 8706 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8707 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8708 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8709 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8710 return SDValue(N, 0); 8711 8712 return combineGREVI_GORCI(N, DAG); 8713 } 8714 case RISCVISD::GREVW: 8715 case RISCVISD::GORCW: { 8716 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8717 if (SimplifyDemandedLowBitsHelper(0, 32) || 8718 SimplifyDemandedLowBitsHelper(1, 5)) 8719 return SDValue(N, 0); 8720 8721 break; 8722 } 8723 case RISCVISD::SHFL: 8724 case RISCVISD::UNSHFL: { 8725 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8726 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8727 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8728 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8729 return SDValue(N, 0); 8730 8731 break; 8732 } 8733 case RISCVISD::SHFLW: 8734 case RISCVISD::UNSHFLW: { 8735 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8736 if (SimplifyDemandedLowBitsHelper(0, 32) || 8737 SimplifyDemandedLowBitsHelper(1, 4)) 8738 return SDValue(N, 0); 8739 8740 break; 8741 } 8742 case RISCVISD::BCOMPRESSW: 8743 case RISCVISD::BDECOMPRESSW: { 8744 // Only the lower 32 bits of LHS and RHS are read. 8745 if (SimplifyDemandedLowBitsHelper(0, 32) || 8746 SimplifyDemandedLowBitsHelper(1, 32)) 8747 return SDValue(N, 0); 8748 8749 break; 8750 } 8751 case RISCVISD::FSR: 8752 case RISCVISD::FSL: 8753 case RISCVISD::FSRW: 8754 case RISCVISD::FSLW: { 8755 bool IsWInstruction = 8756 N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW; 8757 unsigned BitWidth = 8758 IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits(); 8759 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8760 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 8761 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1)) 8762 return SDValue(N, 0); 8763 8764 break; 8765 } 8766 case RISCVISD::FMV_X_ANYEXTH: 8767 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8768 SDLoc DL(N); 8769 SDValue Op0 = N->getOperand(0); 8770 MVT VT = N->getSimpleValueType(0); 8771 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8772 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8773 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8774 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8775 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8776 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8777 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8778 assert(Op0.getOperand(0).getValueType() == VT && 8779 "Unexpected value type!"); 8780 return Op0.getOperand(0); 8781 } 8782 8783 // This is a target-specific version of a DAGCombine performed in 8784 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8785 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8786 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8787 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8788 !Op0.getNode()->hasOneUse()) 8789 break; 8790 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8791 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8792 APInt SignBit = APInt::getSignMask(FPBits).sext(VT.getSizeInBits()); 8793 if (Op0.getOpcode() == ISD::FNEG) 8794 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8795 DAG.getConstant(SignBit, DL, VT)); 8796 8797 assert(Op0.getOpcode() == ISD::FABS); 8798 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8799 DAG.getConstant(~SignBit, DL, VT)); 8800 } 8801 case ISD::ADD: 8802 return performADDCombine(N, DAG, Subtarget); 8803 case ISD::SUB: 8804 return performSUBCombine(N, DAG); 8805 case ISD::AND: 8806 return performANDCombine(N, DAG, Subtarget); 8807 case ISD::OR: 8808 return performORCombine(N, DAG, Subtarget); 8809 case ISD::XOR: 8810 return performXORCombine(N, DAG); 8811 case ISD::FADD: 8812 case ISD::UMAX: 8813 case ISD::UMIN: 8814 case ISD::SMAX: 8815 case ISD::SMIN: 8816 case ISD::FMAXNUM: 8817 case ISD::FMINNUM: 8818 return combineBinOpToReduce(N, DAG); 8819 case ISD::SIGN_EXTEND_INREG: 8820 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 8821 case ISD::ZERO_EXTEND: 8822 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8823 // type legalization. This is safe because fp_to_uint produces poison if 8824 // it overflows. 8825 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8826 SDValue Src = N->getOperand(0); 8827 if (Src.getOpcode() == ISD::FP_TO_UINT && 8828 isTypeLegal(Src.getOperand(0).getValueType())) 8829 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8830 Src.getOperand(0)); 8831 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8832 isTypeLegal(Src.getOperand(1).getValueType())) { 8833 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8834 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8835 Src.getOperand(0), Src.getOperand(1)); 8836 DCI.CombineTo(N, Res); 8837 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8838 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8839 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8840 } 8841 } 8842 return SDValue(); 8843 case RISCVISD::SELECT_CC: { 8844 // Transform 8845 SDValue LHS = N->getOperand(0); 8846 SDValue RHS = N->getOperand(1); 8847 SDValue TrueV = N->getOperand(3); 8848 SDValue FalseV = N->getOperand(4); 8849 8850 // If the True and False values are the same, we don't need a select_cc. 8851 if (TrueV == FalseV) 8852 return TrueV; 8853 8854 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8855 if (!ISD::isIntEqualitySetCC(CCVal)) 8856 break; 8857 8858 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8859 // (select_cc X, Y, lt, trueV, falseV) 8860 // Sometimes the setcc is introduced after select_cc has been formed. 8861 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8862 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8863 // If we're looking for eq 0 instead of ne 0, we need to invert the 8864 // condition. 8865 bool Invert = CCVal == ISD::SETEQ; 8866 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8867 if (Invert) 8868 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8869 8870 SDLoc DL(N); 8871 RHS = LHS.getOperand(1); 8872 LHS = LHS.getOperand(0); 8873 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8874 8875 SDValue TargetCC = DAG.getCondCode(CCVal); 8876 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8877 {LHS, RHS, TargetCC, TrueV, FalseV}); 8878 } 8879 8880 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8881 // (select_cc X, Y, eq/ne, trueV, falseV) 8882 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8883 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8884 {LHS.getOperand(0), LHS.getOperand(1), 8885 N->getOperand(2), TrueV, FalseV}); 8886 // (select_cc X, 1, setne, trueV, falseV) -> 8887 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8888 // This can occur when legalizing some floating point comparisons. 8889 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8890 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8891 SDLoc DL(N); 8892 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8893 SDValue TargetCC = DAG.getCondCode(CCVal); 8894 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8895 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8896 {LHS, RHS, TargetCC, TrueV, FalseV}); 8897 } 8898 8899 break; 8900 } 8901 case RISCVISD::BR_CC: { 8902 SDValue LHS = N->getOperand(1); 8903 SDValue RHS = N->getOperand(2); 8904 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8905 if (!ISD::isIntEqualitySetCC(CCVal)) 8906 break; 8907 8908 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8909 // (br_cc X, Y, lt, dest) 8910 // Sometimes the setcc is introduced after br_cc has been formed. 8911 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8912 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8913 // If we're looking for eq 0 instead of ne 0, we need to invert the 8914 // condition. 8915 bool Invert = CCVal == ISD::SETEQ; 8916 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8917 if (Invert) 8918 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8919 8920 SDLoc DL(N); 8921 RHS = LHS.getOperand(1); 8922 LHS = LHS.getOperand(0); 8923 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8924 8925 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8926 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8927 N->getOperand(4)); 8928 } 8929 8930 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8931 // (br_cc X, Y, eq/ne, trueV, falseV) 8932 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8933 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8934 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8935 N->getOperand(3), N->getOperand(4)); 8936 8937 // (br_cc X, 1, setne, br_cc) -> 8938 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8939 // This can occur when legalizing some floating point comparisons. 8940 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8941 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8942 SDLoc DL(N); 8943 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8944 SDValue TargetCC = DAG.getCondCode(CCVal); 8945 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8946 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8947 N->getOperand(0), LHS, RHS, TargetCC, 8948 N->getOperand(4)); 8949 } 8950 break; 8951 } 8952 case ISD::BITREVERSE: 8953 return performBITREVERSECombine(N, DAG, Subtarget); 8954 case ISD::FP_TO_SINT: 8955 case ISD::FP_TO_UINT: 8956 return performFP_TO_INTCombine(N, DCI, Subtarget); 8957 case ISD::FP_TO_SINT_SAT: 8958 case ISD::FP_TO_UINT_SAT: 8959 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8960 case ISD::FCOPYSIGN: { 8961 EVT VT = N->getValueType(0); 8962 if (!VT.isVector()) 8963 break; 8964 // There is a form of VFSGNJ which injects the negated sign of its second 8965 // operand. Try and bubble any FNEG up after the extend/round to produce 8966 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8967 // TRUNC=1. 8968 SDValue In2 = N->getOperand(1); 8969 // Avoid cases where the extend/round has multiple uses, as duplicating 8970 // those is typically more expensive than removing a fneg. 8971 if (!In2.hasOneUse()) 8972 break; 8973 if (In2.getOpcode() != ISD::FP_EXTEND && 8974 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8975 break; 8976 In2 = In2.getOperand(0); 8977 if (In2.getOpcode() != ISD::FNEG) 8978 break; 8979 SDLoc DL(N); 8980 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8981 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8982 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8983 } 8984 case ISD::MGATHER: 8985 case ISD::MSCATTER: 8986 case ISD::VP_GATHER: 8987 case ISD::VP_SCATTER: { 8988 if (!DCI.isBeforeLegalize()) 8989 break; 8990 SDValue Index, ScaleOp; 8991 bool IsIndexScaled = false; 8992 bool IsIndexSigned = false; 8993 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8994 Index = VPGSN->getIndex(); 8995 ScaleOp = VPGSN->getScale(); 8996 IsIndexScaled = VPGSN->isIndexScaled(); 8997 IsIndexSigned = VPGSN->isIndexSigned(); 8998 } else { 8999 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 9000 Index = MGSN->getIndex(); 9001 ScaleOp = MGSN->getScale(); 9002 IsIndexScaled = MGSN->isIndexScaled(); 9003 IsIndexSigned = MGSN->isIndexSigned(); 9004 } 9005 EVT IndexVT = Index.getValueType(); 9006 MVT XLenVT = Subtarget.getXLenVT(); 9007 // RISCV indexed loads only support the "unsigned unscaled" addressing 9008 // mode, so anything else must be manually legalized. 9009 bool NeedsIdxLegalization = 9010 IsIndexScaled || 9011 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 9012 if (!NeedsIdxLegalization) 9013 break; 9014 9015 SDLoc DL(N); 9016 9017 // Any index legalization should first promote to XLenVT, so we don't lose 9018 // bits when scaling. This may create an illegal index type so we let 9019 // LLVM's legalization take care of the splitting. 9020 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 9021 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 9022 IndexVT = IndexVT.changeVectorElementType(XLenVT); 9023 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 9024 DL, IndexVT, Index); 9025 } 9026 9027 if (IsIndexScaled) { 9028 // Manually scale the indices. 9029 // TODO: Sanitize the scale operand here? 9030 // TODO: For VP nodes, should we use VP_SHL here? 9031 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 9032 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 9033 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 9034 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 9035 ScaleOp = DAG.getTargetConstant(1, DL, ScaleOp.getValueType()); 9036 } 9037 9038 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_SCALED; 9039 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 9040 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 9041 {VPGN->getChain(), VPGN->getBasePtr(), Index, 9042 ScaleOp, VPGN->getMask(), 9043 VPGN->getVectorLength()}, 9044 VPGN->getMemOperand(), NewIndexTy); 9045 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 9046 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 9047 {VPSN->getChain(), VPSN->getValue(), 9048 VPSN->getBasePtr(), Index, ScaleOp, 9049 VPSN->getMask(), VPSN->getVectorLength()}, 9050 VPSN->getMemOperand(), NewIndexTy); 9051 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 9052 return DAG.getMaskedGather( 9053 N->getVTList(), MGN->getMemoryVT(), DL, 9054 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 9055 MGN->getBasePtr(), Index, ScaleOp}, 9056 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 9057 const auto *MSN = cast<MaskedScatterSDNode>(N); 9058 return DAG.getMaskedScatter( 9059 N->getVTList(), MSN->getMemoryVT(), DL, 9060 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 9061 Index, ScaleOp}, 9062 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 9063 } 9064 case RISCVISD::SRA_VL: 9065 case RISCVISD::SRL_VL: 9066 case RISCVISD::SHL_VL: { 9067 SDValue ShAmt = N->getOperand(1); 9068 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 9069 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 9070 SDLoc DL(N); 9071 SDValue VL = N->getOperand(3); 9072 EVT VT = N->getValueType(0); 9073 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 9074 ShAmt.getOperand(1), VL); 9075 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 9076 N->getOperand(2), N->getOperand(3)); 9077 } 9078 break; 9079 } 9080 case ISD::SRA: 9081 if (SDValue V = performSRACombine(N, DAG, Subtarget)) 9082 return V; 9083 LLVM_FALLTHROUGH; 9084 case ISD::SRL: 9085 case ISD::SHL: { 9086 SDValue ShAmt = N->getOperand(1); 9087 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 9088 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 9089 SDLoc DL(N); 9090 EVT VT = N->getValueType(0); 9091 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 9092 ShAmt.getOperand(1), 9093 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 9094 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 9095 } 9096 break; 9097 } 9098 case RISCVISD::ADD_VL: 9099 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 9100 return V; 9101 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 9102 case RISCVISD::SUB_VL: 9103 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 9104 case RISCVISD::VWADD_W_VL: 9105 case RISCVISD::VWADDU_W_VL: 9106 case RISCVISD::VWSUB_W_VL: 9107 case RISCVISD::VWSUBU_W_VL: 9108 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 9109 case RISCVISD::MUL_VL: 9110 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 9111 return V; 9112 // Mul is commutative. 9113 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 9114 case RISCVISD::VFMADD_VL: 9115 case RISCVISD::VFNMADD_VL: 9116 case RISCVISD::VFMSUB_VL: 9117 case RISCVISD::VFNMSUB_VL: { 9118 // Fold FNEG_VL into FMA opcodes. 9119 SDValue A = N->getOperand(0); 9120 SDValue B = N->getOperand(1); 9121 SDValue C = N->getOperand(2); 9122 SDValue Mask = N->getOperand(3); 9123 SDValue VL = N->getOperand(4); 9124 9125 auto invertIfNegative = [&Mask, &VL](SDValue &V) { 9126 if (V.getOpcode() == RISCVISD::FNEG_VL && V.getOperand(1) == Mask && 9127 V.getOperand(2) == VL) { 9128 // Return the negated input. 9129 V = V.getOperand(0); 9130 return true; 9131 } 9132 9133 return false; 9134 }; 9135 9136 bool NegA = invertIfNegative(A); 9137 bool NegB = invertIfNegative(B); 9138 bool NegC = invertIfNegative(C); 9139 9140 // If no operands are negated, we're done. 9141 if (!NegA && !NegB && !NegC) 9142 return SDValue(); 9143 9144 unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC); 9145 return DAG.getNode(NewOpcode, SDLoc(N), N->getValueType(0), A, B, C, Mask, 9146 VL); 9147 } 9148 case ISD::STORE: { 9149 auto *Store = cast<StoreSDNode>(N); 9150 SDValue Val = Store->getValue(); 9151 // Combine store of vmv.x.s to vse with VL of 1. 9152 // FIXME: Support FP. 9153 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 9154 SDValue Src = Val.getOperand(0); 9155 EVT VecVT = Src.getValueType(); 9156 EVT MemVT = Store->getMemoryVT(); 9157 // The memory VT and the element type must match. 9158 if (VecVT.getVectorElementType() == MemVT) { 9159 SDLoc DL(N); 9160 MVT MaskVT = getMaskTypeFor(VecVT); 9161 return DAG.getStoreVP( 9162 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 9163 DAG.getConstant(1, DL, MaskVT), 9164 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 9165 Store->getMemOperand(), Store->getAddressingMode(), 9166 Store->isTruncatingStore(), /*IsCompress*/ false); 9167 } 9168 } 9169 9170 break; 9171 } 9172 case ISD::SPLAT_VECTOR: { 9173 EVT VT = N->getValueType(0); 9174 // Only perform this combine on legal MVT types. 9175 if (!isTypeLegal(VT)) 9176 break; 9177 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 9178 DAG, Subtarget)) 9179 return Gather; 9180 break; 9181 } 9182 case RISCVISD::VMV_V_X_VL: { 9183 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 9184 // scalar input. 9185 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 9186 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 9187 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 9188 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 9189 return SDValue(N, 0); 9190 9191 break; 9192 } 9193 case ISD::INTRINSIC_WO_CHAIN: { 9194 unsigned IntNo = N->getConstantOperandVal(0); 9195 switch (IntNo) { 9196 // By default we do not combine any intrinsic. 9197 default: 9198 return SDValue(); 9199 case Intrinsic::riscv_vcpop: 9200 case Intrinsic::riscv_vcpop_mask: 9201 case Intrinsic::riscv_vfirst: 9202 case Intrinsic::riscv_vfirst_mask: { 9203 SDValue VL = N->getOperand(2); 9204 if (IntNo == Intrinsic::riscv_vcpop_mask || 9205 IntNo == Intrinsic::riscv_vfirst_mask) 9206 VL = N->getOperand(3); 9207 if (!isNullConstant(VL)) 9208 return SDValue(); 9209 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 9210 SDLoc DL(N); 9211 EVT VT = N->getValueType(0); 9212 if (IntNo == Intrinsic::riscv_vfirst || 9213 IntNo == Intrinsic::riscv_vfirst_mask) 9214 return DAG.getConstant(-1, DL, VT); 9215 return DAG.getConstant(0, DL, VT); 9216 } 9217 } 9218 } 9219 case ISD::BITCAST: { 9220 assert(Subtarget.useRVVForFixedLengthVectors()); 9221 SDValue N0 = N->getOperand(0); 9222 EVT VT = N->getValueType(0); 9223 EVT SrcVT = N0.getValueType(); 9224 // If this is a bitcast between a MVT::v4i1/v2i1/v1i1 and an illegal integer 9225 // type, widen both sides to avoid a trip through memory. 9226 if ((SrcVT == MVT::v1i1 || SrcVT == MVT::v2i1 || SrcVT == MVT::v4i1) && 9227 VT.isScalarInteger()) { 9228 unsigned NumConcats = 8 / SrcVT.getVectorNumElements(); 9229 SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT)); 9230 Ops[0] = N0; 9231 SDLoc DL(N); 9232 N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i1, Ops); 9233 N0 = DAG.getBitcast(MVT::i8, N0); 9234 return DAG.getNode(ISD::TRUNCATE, DL, VT, N0); 9235 } 9236 9237 return SDValue(); 9238 } 9239 } 9240 9241 return SDValue(); 9242 } 9243 9244 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 9245 const SDNode *N, CombineLevel Level) const { 9246 // The following folds are only desirable if `(OP _, c1 << c2)` can be 9247 // materialised in fewer instructions than `(OP _, c1)`: 9248 // 9249 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 9250 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 9251 SDValue N0 = N->getOperand(0); 9252 EVT Ty = N0.getValueType(); 9253 if (Ty.isScalarInteger() && 9254 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 9255 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 9256 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9257 if (C1 && C2) { 9258 const APInt &C1Int = C1->getAPIntValue(); 9259 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 9260 9261 // We can materialise `c1 << c2` into an add immediate, so it's "free", 9262 // and the combine should happen, to potentially allow further combines 9263 // later. 9264 if (ShiftedC1Int.getMinSignedBits() <= 64 && 9265 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 9266 return true; 9267 9268 // We can materialise `c1` in an add immediate, so it's "free", and the 9269 // combine should be prevented. 9270 if (C1Int.getMinSignedBits() <= 64 && 9271 isLegalAddImmediate(C1Int.getSExtValue())) 9272 return false; 9273 9274 // Neither constant will fit into an immediate, so find materialisation 9275 // costs. 9276 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 9277 Subtarget.getFeatureBits(), 9278 /*CompressionCost*/true); 9279 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 9280 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 9281 /*CompressionCost*/true); 9282 9283 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 9284 // combine should be prevented. 9285 if (C1Cost < ShiftedC1Cost) 9286 return false; 9287 } 9288 } 9289 return true; 9290 } 9291 9292 bool RISCVTargetLowering::targetShrinkDemandedConstant( 9293 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 9294 TargetLoweringOpt &TLO) const { 9295 // Delay this optimization as late as possible. 9296 if (!TLO.LegalOps) 9297 return false; 9298 9299 EVT VT = Op.getValueType(); 9300 if (VT.isVector()) 9301 return false; 9302 9303 // Only handle AND for now. 9304 if (Op.getOpcode() != ISD::AND) 9305 return false; 9306 9307 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 9308 if (!C) 9309 return false; 9310 9311 const APInt &Mask = C->getAPIntValue(); 9312 9313 // Clear all non-demanded bits initially. 9314 APInt ShrunkMask = Mask & DemandedBits; 9315 9316 // Try to make a smaller immediate by setting undemanded bits. 9317 9318 APInt ExpandedMask = Mask | ~DemandedBits; 9319 9320 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 9321 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 9322 }; 9323 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 9324 if (NewMask == Mask) 9325 return true; 9326 SDLoc DL(Op); 9327 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 9328 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 9329 return TLO.CombineTo(Op, NewOp); 9330 }; 9331 9332 // If the shrunk mask fits in sign extended 12 bits, let the target 9333 // independent code apply it. 9334 if (ShrunkMask.isSignedIntN(12)) 9335 return false; 9336 9337 // Preserve (and X, 0xffff) when zext.h is supported. 9338 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 9339 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 9340 if (IsLegalMask(NewMask)) 9341 return UseMask(NewMask); 9342 } 9343 9344 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 9345 if (VT == MVT::i64) { 9346 APInt NewMask = APInt(64, 0xffffffff); 9347 if (IsLegalMask(NewMask)) 9348 return UseMask(NewMask); 9349 } 9350 9351 // For the remaining optimizations, we need to be able to make a negative 9352 // number through a combination of mask and undemanded bits. 9353 if (!ExpandedMask.isNegative()) 9354 return false; 9355 9356 // What is the fewest number of bits we need to represent the negative number. 9357 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 9358 9359 // Try to make a 12 bit negative immediate. If that fails try to make a 32 9360 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 9361 APInt NewMask = ShrunkMask; 9362 if (MinSignedBits <= 12) 9363 NewMask.setBitsFrom(11); 9364 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 9365 NewMask.setBitsFrom(31); 9366 else 9367 return false; 9368 9369 // Check that our new mask is a subset of the demanded mask. 9370 assert(IsLegalMask(NewMask)); 9371 return UseMask(NewMask); 9372 } 9373 9374 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) { 9375 static const uint64_t GREVMasks[] = { 9376 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 9377 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 9378 9379 for (unsigned Stage = 0; Stage != 6; ++Stage) { 9380 unsigned Shift = 1 << Stage; 9381 if (ShAmt & Shift) { 9382 uint64_t Mask = GREVMasks[Stage]; 9383 uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask); 9384 if (IsGORC) 9385 Res |= x; 9386 x = Res; 9387 } 9388 } 9389 9390 return x; 9391 } 9392 9393 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 9394 KnownBits &Known, 9395 const APInt &DemandedElts, 9396 const SelectionDAG &DAG, 9397 unsigned Depth) const { 9398 unsigned BitWidth = Known.getBitWidth(); 9399 unsigned Opc = Op.getOpcode(); 9400 assert((Opc >= ISD::BUILTIN_OP_END || 9401 Opc == ISD::INTRINSIC_WO_CHAIN || 9402 Opc == ISD::INTRINSIC_W_CHAIN || 9403 Opc == ISD::INTRINSIC_VOID) && 9404 "Should use MaskedValueIsZero if you don't know whether Op" 9405 " is a target node!"); 9406 9407 Known.resetAll(); 9408 switch (Opc) { 9409 default: break; 9410 case RISCVISD::SELECT_CC: { 9411 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 9412 // If we don't know any bits, early out. 9413 if (Known.isUnknown()) 9414 break; 9415 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 9416 9417 // Only known if known in both the LHS and RHS. 9418 Known = KnownBits::commonBits(Known, Known2); 9419 break; 9420 } 9421 case RISCVISD::REMUW: { 9422 KnownBits Known2; 9423 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9424 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9425 // We only care about the lower 32 bits. 9426 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 9427 // Restore the original width by sign extending. 9428 Known = Known.sext(BitWidth); 9429 break; 9430 } 9431 case RISCVISD::DIVUW: { 9432 KnownBits Known2; 9433 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9434 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9435 // We only care about the lower 32 bits. 9436 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 9437 // Restore the original width by sign extending. 9438 Known = Known.sext(BitWidth); 9439 break; 9440 } 9441 case RISCVISD::CTZW: { 9442 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9443 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 9444 unsigned LowBits = Log2_32(PossibleTZ) + 1; 9445 Known.Zero.setBitsFrom(LowBits); 9446 break; 9447 } 9448 case RISCVISD::CLZW: { 9449 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9450 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 9451 unsigned LowBits = Log2_32(PossibleLZ) + 1; 9452 Known.Zero.setBitsFrom(LowBits); 9453 break; 9454 } 9455 case RISCVISD::GREV: 9456 case RISCVISD::GORC: { 9457 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 9458 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9459 unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1); 9460 bool IsGORC = Op.getOpcode() == RISCVISD::GORC; 9461 // To compute zeros, we need to invert the value and invert it back after. 9462 Known.Zero = 9463 ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC); 9464 Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC); 9465 } 9466 break; 9467 } 9468 case RISCVISD::READ_VLENB: { 9469 // We can use the minimum and maximum VLEN values to bound VLENB. We 9470 // know VLEN must be a power of two. 9471 const unsigned MinVLenB = Subtarget.getRealMinVLen() / 8; 9472 const unsigned MaxVLenB = Subtarget.getRealMaxVLen() / 8; 9473 assert(MinVLenB > 0 && "READ_VLENB without vector extension enabled?"); 9474 Known.Zero.setLowBits(Log2_32(MinVLenB)); 9475 Known.Zero.setBitsFrom(Log2_32(MaxVLenB)+1); 9476 if (MaxVLenB == MinVLenB) 9477 Known.One.setBit(Log2_32(MinVLenB)); 9478 break; 9479 } 9480 case ISD::INTRINSIC_W_CHAIN: 9481 case ISD::INTRINSIC_WO_CHAIN: { 9482 unsigned IntNo = 9483 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 9484 switch (IntNo) { 9485 default: 9486 // We can't do anything for most intrinsics. 9487 break; 9488 case Intrinsic::riscv_vsetvli: 9489 case Intrinsic::riscv_vsetvlimax: 9490 case Intrinsic::riscv_vsetvli_opt: 9491 case Intrinsic::riscv_vsetvlimax_opt: 9492 // Assume that VL output is positive and would fit in an int32_t. 9493 // TODO: VLEN might be capped at 16 bits in a future V spec update. 9494 if (BitWidth >= 32) 9495 Known.Zero.setBitsFrom(31); 9496 break; 9497 } 9498 break; 9499 } 9500 } 9501 } 9502 9503 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 9504 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 9505 unsigned Depth) const { 9506 switch (Op.getOpcode()) { 9507 default: 9508 break; 9509 case RISCVISD::SELECT_CC: { 9510 unsigned Tmp = 9511 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 9512 if (Tmp == 1) return 1; // Early out. 9513 unsigned Tmp2 = 9514 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 9515 return std::min(Tmp, Tmp2); 9516 } 9517 case RISCVISD::SLLW: 9518 case RISCVISD::SRAW: 9519 case RISCVISD::SRLW: 9520 case RISCVISD::DIVW: 9521 case RISCVISD::DIVUW: 9522 case RISCVISD::REMUW: 9523 case RISCVISD::ROLW: 9524 case RISCVISD::RORW: 9525 case RISCVISD::GREVW: 9526 case RISCVISD::GORCW: 9527 case RISCVISD::FSLW: 9528 case RISCVISD::FSRW: 9529 case RISCVISD::SHFLW: 9530 case RISCVISD::UNSHFLW: 9531 case RISCVISD::BCOMPRESSW: 9532 case RISCVISD::BDECOMPRESSW: 9533 case RISCVISD::BFPW: 9534 case RISCVISD::FCVT_W_RV64: 9535 case RISCVISD::FCVT_WU_RV64: 9536 case RISCVISD::STRICT_FCVT_W_RV64: 9537 case RISCVISD::STRICT_FCVT_WU_RV64: 9538 // TODO: As the result is sign-extended, this is conservatively correct. A 9539 // more precise answer could be calculated for SRAW depending on known 9540 // bits in the shift amount. 9541 return 33; 9542 case RISCVISD::SHFL: 9543 case RISCVISD::UNSHFL: { 9544 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 9545 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 9546 // will stay within the upper 32 bits. If there were more than 32 sign bits 9547 // before there will be at least 33 sign bits after. 9548 if (Op.getValueType() == MVT::i64 && 9549 isa<ConstantSDNode>(Op.getOperand(1)) && 9550 (Op.getConstantOperandVal(1) & 0x10) == 0) { 9551 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 9552 if (Tmp > 32) 9553 return 33; 9554 } 9555 break; 9556 } 9557 case RISCVISD::VMV_X_S: { 9558 // The number of sign bits of the scalar result is computed by obtaining the 9559 // element type of the input vector operand, subtracting its width from the 9560 // XLEN, and then adding one (sign bit within the element type). If the 9561 // element type is wider than XLen, the least-significant XLEN bits are 9562 // taken. 9563 unsigned XLen = Subtarget.getXLen(); 9564 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 9565 if (EltBits <= XLen) 9566 return XLen - EltBits + 1; 9567 break; 9568 } 9569 } 9570 9571 return 1; 9572 } 9573 9574 const Constant * 9575 RISCVTargetLowering::getTargetConstantFromLoad(LoadSDNode *Ld) const { 9576 assert(Ld && "Unexpected null LoadSDNode"); 9577 if (!ISD::isNormalLoad(Ld)) 9578 return nullptr; 9579 9580 SDValue Ptr = Ld->getBasePtr(); 9581 9582 // Only constant pools with no offset are supported. 9583 auto GetSupportedConstantPool = [](SDValue Ptr) -> ConstantPoolSDNode * { 9584 auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr); 9585 if (!CNode || CNode->isMachineConstantPoolEntry() || 9586 CNode->getOffset() != 0) 9587 return nullptr; 9588 9589 return CNode; 9590 }; 9591 9592 // Simple case, LLA. 9593 if (Ptr.getOpcode() == RISCVISD::LLA) { 9594 auto *CNode = GetSupportedConstantPool(Ptr); 9595 if (!CNode || CNode->getTargetFlags() != 0) 9596 return nullptr; 9597 9598 return CNode->getConstVal(); 9599 } 9600 9601 // Look for a HI and ADD_LO pair. 9602 if (Ptr.getOpcode() != RISCVISD::ADD_LO || 9603 Ptr.getOperand(0).getOpcode() != RISCVISD::HI) 9604 return nullptr; 9605 9606 auto *CNodeLo = GetSupportedConstantPool(Ptr.getOperand(1)); 9607 auto *CNodeHi = GetSupportedConstantPool(Ptr.getOperand(0).getOperand(0)); 9608 9609 if (!CNodeLo || CNodeLo->getTargetFlags() != RISCVII::MO_LO || 9610 !CNodeHi || CNodeHi->getTargetFlags() != RISCVII::MO_HI) 9611 return nullptr; 9612 9613 if (CNodeLo->getConstVal() != CNodeHi->getConstVal()) 9614 return nullptr; 9615 9616 return CNodeLo->getConstVal(); 9617 } 9618 9619 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 9620 MachineBasicBlock *BB) { 9621 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 9622 9623 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 9624 // Should the count have wrapped while it was being read, we need to try 9625 // again. 9626 // ... 9627 // read: 9628 // rdcycleh x3 # load high word of cycle 9629 // rdcycle x2 # load low word of cycle 9630 // rdcycleh x4 # load high word of cycle 9631 // bne x3, x4, read # check if high word reads match, otherwise try again 9632 // ... 9633 9634 MachineFunction &MF = *BB->getParent(); 9635 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9636 MachineFunction::iterator It = ++BB->getIterator(); 9637 9638 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9639 MF.insert(It, LoopMBB); 9640 9641 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9642 MF.insert(It, DoneMBB); 9643 9644 // Transfer the remainder of BB and its successor edges to DoneMBB. 9645 DoneMBB->splice(DoneMBB->begin(), BB, 9646 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9647 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 9648 9649 BB->addSuccessor(LoopMBB); 9650 9651 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9652 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9653 Register LoReg = MI.getOperand(0).getReg(); 9654 Register HiReg = MI.getOperand(1).getReg(); 9655 DebugLoc DL = MI.getDebugLoc(); 9656 9657 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 9658 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 9659 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9660 .addReg(RISCV::X0); 9661 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 9662 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 9663 .addReg(RISCV::X0); 9664 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 9665 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9666 .addReg(RISCV::X0); 9667 9668 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 9669 .addReg(HiReg) 9670 .addReg(ReadAgainReg) 9671 .addMBB(LoopMBB); 9672 9673 LoopMBB->addSuccessor(LoopMBB); 9674 LoopMBB->addSuccessor(DoneMBB); 9675 9676 MI.eraseFromParent(); 9677 9678 return DoneMBB; 9679 } 9680 9681 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9682 MachineBasicBlock *BB) { 9683 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9684 9685 MachineFunction &MF = *BB->getParent(); 9686 DebugLoc DL = MI.getDebugLoc(); 9687 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9688 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9689 Register LoReg = MI.getOperand(0).getReg(); 9690 Register HiReg = MI.getOperand(1).getReg(); 9691 Register SrcReg = MI.getOperand(2).getReg(); 9692 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9693 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9694 9695 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9696 RI); 9697 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9698 MachineMemOperand *MMOLo = 9699 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9700 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9701 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9702 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9703 .addFrameIndex(FI) 9704 .addImm(0) 9705 .addMemOperand(MMOLo); 9706 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9707 .addFrameIndex(FI) 9708 .addImm(4) 9709 .addMemOperand(MMOHi); 9710 MI.eraseFromParent(); // The pseudo instruction is gone now. 9711 return BB; 9712 } 9713 9714 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9715 MachineBasicBlock *BB) { 9716 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9717 "Unexpected instruction"); 9718 9719 MachineFunction &MF = *BB->getParent(); 9720 DebugLoc DL = MI.getDebugLoc(); 9721 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9722 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9723 Register DstReg = MI.getOperand(0).getReg(); 9724 Register LoReg = MI.getOperand(1).getReg(); 9725 Register HiReg = MI.getOperand(2).getReg(); 9726 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9727 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9728 9729 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9730 MachineMemOperand *MMOLo = 9731 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9732 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9733 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9734 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9735 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9736 .addFrameIndex(FI) 9737 .addImm(0) 9738 .addMemOperand(MMOLo); 9739 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9740 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9741 .addFrameIndex(FI) 9742 .addImm(4) 9743 .addMemOperand(MMOHi); 9744 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9745 MI.eraseFromParent(); // The pseudo instruction is gone now. 9746 return BB; 9747 } 9748 9749 static bool isSelectPseudo(MachineInstr &MI) { 9750 switch (MI.getOpcode()) { 9751 default: 9752 return false; 9753 case RISCV::Select_GPR_Using_CC_GPR: 9754 case RISCV::Select_FPR16_Using_CC_GPR: 9755 case RISCV::Select_FPR32_Using_CC_GPR: 9756 case RISCV::Select_FPR64_Using_CC_GPR: 9757 return true; 9758 } 9759 } 9760 9761 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9762 unsigned RelOpcode, unsigned EqOpcode, 9763 const RISCVSubtarget &Subtarget) { 9764 DebugLoc DL = MI.getDebugLoc(); 9765 Register DstReg = MI.getOperand(0).getReg(); 9766 Register Src1Reg = MI.getOperand(1).getReg(); 9767 Register Src2Reg = MI.getOperand(2).getReg(); 9768 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9769 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9770 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9771 9772 // Save the current FFLAGS. 9773 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9774 9775 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9776 .addReg(Src1Reg) 9777 .addReg(Src2Reg); 9778 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9779 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9780 9781 // Restore the FFLAGS. 9782 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9783 .addReg(SavedFFlags, RegState::Kill); 9784 9785 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9786 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9787 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9788 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9789 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9790 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9791 9792 // Erase the pseudoinstruction. 9793 MI.eraseFromParent(); 9794 return BB; 9795 } 9796 9797 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9798 MachineBasicBlock *BB, 9799 const RISCVSubtarget &Subtarget) { 9800 // To "insert" Select_* instructions, we actually have to insert the triangle 9801 // control-flow pattern. The incoming instructions know the destination vreg 9802 // to set, the condition code register to branch on, the true/false values to 9803 // select between, and the condcode to use to select the appropriate branch. 9804 // 9805 // We produce the following control flow: 9806 // HeadMBB 9807 // | \ 9808 // | IfFalseMBB 9809 // | / 9810 // TailMBB 9811 // 9812 // When we find a sequence of selects we attempt to optimize their emission 9813 // by sharing the control flow. Currently we only handle cases where we have 9814 // multiple selects with the exact same condition (same LHS, RHS and CC). 9815 // The selects may be interleaved with other instructions if the other 9816 // instructions meet some requirements we deem safe: 9817 // - They are debug instructions. Otherwise, 9818 // - They do not have side-effects, do not access memory and their inputs do 9819 // not depend on the results of the select pseudo-instructions. 9820 // The TrueV/FalseV operands of the selects cannot depend on the result of 9821 // previous selects in the sequence. 9822 // These conditions could be further relaxed. See the X86 target for a 9823 // related approach and more information. 9824 Register LHS = MI.getOperand(1).getReg(); 9825 Register RHS = MI.getOperand(2).getReg(); 9826 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9827 9828 SmallVector<MachineInstr *, 4> SelectDebugValues; 9829 SmallSet<Register, 4> SelectDests; 9830 SelectDests.insert(MI.getOperand(0).getReg()); 9831 9832 MachineInstr *LastSelectPseudo = &MI; 9833 9834 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9835 SequenceMBBI != E; ++SequenceMBBI) { 9836 if (SequenceMBBI->isDebugInstr()) 9837 continue; 9838 if (isSelectPseudo(*SequenceMBBI)) { 9839 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9840 SequenceMBBI->getOperand(2).getReg() != RHS || 9841 SequenceMBBI->getOperand(3).getImm() != CC || 9842 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9843 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9844 break; 9845 LastSelectPseudo = &*SequenceMBBI; 9846 SequenceMBBI->collectDebugValues(SelectDebugValues); 9847 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9848 } else { 9849 if (SequenceMBBI->hasUnmodeledSideEffects() || 9850 SequenceMBBI->mayLoadOrStore()) 9851 break; 9852 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9853 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9854 })) 9855 break; 9856 } 9857 } 9858 9859 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9860 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9861 DebugLoc DL = MI.getDebugLoc(); 9862 MachineFunction::iterator I = ++BB->getIterator(); 9863 9864 MachineBasicBlock *HeadMBB = BB; 9865 MachineFunction *F = BB->getParent(); 9866 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9867 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9868 9869 F->insert(I, IfFalseMBB); 9870 F->insert(I, TailMBB); 9871 9872 // Transfer debug instructions associated with the selects to TailMBB. 9873 for (MachineInstr *DebugInstr : SelectDebugValues) { 9874 TailMBB->push_back(DebugInstr->removeFromParent()); 9875 } 9876 9877 // Move all instructions after the sequence to TailMBB. 9878 TailMBB->splice(TailMBB->end(), HeadMBB, 9879 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9880 // Update machine-CFG edges by transferring all successors of the current 9881 // block to the new block which will contain the Phi nodes for the selects. 9882 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9883 // Set the successors for HeadMBB. 9884 HeadMBB->addSuccessor(IfFalseMBB); 9885 HeadMBB->addSuccessor(TailMBB); 9886 9887 // Insert appropriate branch. 9888 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9889 .addReg(LHS) 9890 .addReg(RHS) 9891 .addMBB(TailMBB); 9892 9893 // IfFalseMBB just falls through to TailMBB. 9894 IfFalseMBB->addSuccessor(TailMBB); 9895 9896 // Create PHIs for all of the select pseudo-instructions. 9897 auto SelectMBBI = MI.getIterator(); 9898 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9899 auto InsertionPoint = TailMBB->begin(); 9900 while (SelectMBBI != SelectEnd) { 9901 auto Next = std::next(SelectMBBI); 9902 if (isSelectPseudo(*SelectMBBI)) { 9903 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9904 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9905 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9906 .addReg(SelectMBBI->getOperand(4).getReg()) 9907 .addMBB(HeadMBB) 9908 .addReg(SelectMBBI->getOperand(5).getReg()) 9909 .addMBB(IfFalseMBB); 9910 SelectMBBI->eraseFromParent(); 9911 } 9912 SelectMBBI = Next; 9913 } 9914 9915 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9916 return TailMBB; 9917 } 9918 9919 MachineBasicBlock * 9920 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9921 MachineBasicBlock *BB) const { 9922 switch (MI.getOpcode()) { 9923 default: 9924 llvm_unreachable("Unexpected instr type to insert"); 9925 case RISCV::ReadCycleWide: 9926 assert(!Subtarget.is64Bit() && 9927 "ReadCycleWrite is only to be used on riscv32"); 9928 return emitReadCycleWidePseudo(MI, BB); 9929 case RISCV::Select_GPR_Using_CC_GPR: 9930 case RISCV::Select_FPR16_Using_CC_GPR: 9931 case RISCV::Select_FPR32_Using_CC_GPR: 9932 case RISCV::Select_FPR64_Using_CC_GPR: 9933 return emitSelectPseudo(MI, BB, Subtarget); 9934 case RISCV::BuildPairF64Pseudo: 9935 return emitBuildPairF64Pseudo(MI, BB); 9936 case RISCV::SplitF64Pseudo: 9937 return emitSplitF64Pseudo(MI, BB); 9938 case RISCV::PseudoQuietFLE_H: 9939 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9940 case RISCV::PseudoQuietFLT_H: 9941 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9942 case RISCV::PseudoQuietFLE_S: 9943 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9944 case RISCV::PseudoQuietFLT_S: 9945 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9946 case RISCV::PseudoQuietFLE_D: 9947 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9948 case RISCV::PseudoQuietFLT_D: 9949 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9950 } 9951 } 9952 9953 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9954 SDNode *Node) const { 9955 // Add FRM dependency to any instructions with dynamic rounding mode. 9956 unsigned Opc = MI.getOpcode(); 9957 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9958 if (Idx < 0) 9959 return; 9960 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9961 return; 9962 // If the instruction already reads FRM, don't add another read. 9963 if (MI.readsRegister(RISCV::FRM)) 9964 return; 9965 MI.addOperand( 9966 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9967 } 9968 9969 // Calling Convention Implementation. 9970 // The expectations for frontend ABI lowering vary from target to target. 9971 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 9972 // details, but this is a longer term goal. For now, we simply try to keep the 9973 // role of the frontend as simple and well-defined as possible. The rules can 9974 // be summarised as: 9975 // * Never split up large scalar arguments. We handle them here. 9976 // * If a hardfloat calling convention is being used, and the struct may be 9977 // passed in a pair of registers (fp+fp, int+fp), and both registers are 9978 // available, then pass as two separate arguments. If either the GPRs or FPRs 9979 // are exhausted, then pass according to the rule below. 9980 // * If a struct could never be passed in registers or directly in a stack 9981 // slot (as it is larger than 2*XLEN and the floating point rules don't 9982 // apply), then pass it using a pointer with the byval attribute. 9983 // * If a struct is less than 2*XLEN, then coerce to either a two-element 9984 // word-sized array or a 2*XLEN scalar (depending on alignment). 9985 // * The frontend can determine whether a struct is returned by reference or 9986 // not based on its size and fields. If it will be returned by reference, the 9987 // frontend must modify the prototype so a pointer with the sret annotation is 9988 // passed as the first argument. This is not necessary for large scalar 9989 // returns. 9990 // * Struct return values and varargs should be coerced to structs containing 9991 // register-size fields in the same situations they would be for fixed 9992 // arguments. 9993 9994 static const MCPhysReg ArgGPRs[] = { 9995 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 9996 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 9997 }; 9998 static const MCPhysReg ArgFPR16s[] = { 9999 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 10000 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 10001 }; 10002 static const MCPhysReg ArgFPR32s[] = { 10003 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 10004 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 10005 }; 10006 static const MCPhysReg ArgFPR64s[] = { 10007 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 10008 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 10009 }; 10010 // This is an interim calling convention and it may be changed in the future. 10011 static const MCPhysReg ArgVRs[] = { 10012 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 10013 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 10014 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 10015 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 10016 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 10017 RISCV::V20M2, RISCV::V22M2}; 10018 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 10019 RISCV::V20M4}; 10020 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 10021 10022 // Pass a 2*XLEN argument that has been split into two XLEN values through 10023 // registers or the stack as necessary. 10024 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 10025 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 10026 MVT ValVT2, MVT LocVT2, 10027 ISD::ArgFlagsTy ArgFlags2) { 10028 unsigned XLenInBytes = XLen / 8; 10029 if (Register Reg = State.AllocateReg(ArgGPRs)) { 10030 // At least one half can be passed via register. 10031 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 10032 VA1.getLocVT(), CCValAssign::Full)); 10033 } else { 10034 // Both halves must be passed on the stack, with proper alignment. 10035 Align StackAlign = 10036 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 10037 State.addLoc( 10038 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 10039 State.AllocateStack(XLenInBytes, StackAlign), 10040 VA1.getLocVT(), CCValAssign::Full)); 10041 State.addLoc(CCValAssign::getMem( 10042 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 10043 LocVT2, CCValAssign::Full)); 10044 return false; 10045 } 10046 10047 if (Register Reg = State.AllocateReg(ArgGPRs)) { 10048 // The second half can also be passed via register. 10049 State.addLoc( 10050 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 10051 } else { 10052 // The second half is passed via the stack, without additional alignment. 10053 State.addLoc(CCValAssign::getMem( 10054 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 10055 LocVT2, CCValAssign::Full)); 10056 } 10057 10058 return false; 10059 } 10060 10061 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 10062 Optional<unsigned> FirstMaskArgument, 10063 CCState &State, const RISCVTargetLowering &TLI) { 10064 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 10065 if (RC == &RISCV::VRRegClass) { 10066 // Assign the first mask argument to V0. 10067 // This is an interim calling convention and it may be changed in the 10068 // future. 10069 if (FirstMaskArgument && ValNo == *FirstMaskArgument) 10070 return State.AllocateReg(RISCV::V0); 10071 return State.AllocateReg(ArgVRs); 10072 } 10073 if (RC == &RISCV::VRM2RegClass) 10074 return State.AllocateReg(ArgVRM2s); 10075 if (RC == &RISCV::VRM4RegClass) 10076 return State.AllocateReg(ArgVRM4s); 10077 if (RC == &RISCV::VRM8RegClass) 10078 return State.AllocateReg(ArgVRM8s); 10079 llvm_unreachable("Unhandled register class for ValueType"); 10080 } 10081 10082 // Implements the RISC-V calling convention. Returns true upon failure. 10083 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 10084 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 10085 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 10086 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 10087 Optional<unsigned> FirstMaskArgument) { 10088 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 10089 assert(XLen == 32 || XLen == 64); 10090 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 10091 10092 // Any return value split in to more than two values can't be returned 10093 // directly. Vectors are returned via the available vector registers. 10094 if (!LocVT.isVector() && IsRet && ValNo > 1) 10095 return true; 10096 10097 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 10098 // variadic argument, or if no F16/F32 argument registers are available. 10099 bool UseGPRForF16_F32 = true; 10100 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 10101 // variadic argument, or if no F64 argument registers are available. 10102 bool UseGPRForF64 = true; 10103 10104 switch (ABI) { 10105 default: 10106 llvm_unreachable("Unexpected ABI"); 10107 case RISCVABI::ABI_ILP32: 10108 case RISCVABI::ABI_LP64: 10109 break; 10110 case RISCVABI::ABI_ILP32F: 10111 case RISCVABI::ABI_LP64F: 10112 UseGPRForF16_F32 = !IsFixed; 10113 break; 10114 case RISCVABI::ABI_ILP32D: 10115 case RISCVABI::ABI_LP64D: 10116 UseGPRForF16_F32 = !IsFixed; 10117 UseGPRForF64 = !IsFixed; 10118 break; 10119 } 10120 10121 // FPR16, FPR32, and FPR64 alias each other. 10122 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 10123 UseGPRForF16_F32 = true; 10124 UseGPRForF64 = true; 10125 } 10126 10127 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 10128 // similar local variables rather than directly checking against the target 10129 // ABI. 10130 10131 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 10132 LocVT = XLenVT; 10133 LocInfo = CCValAssign::BCvt; 10134 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 10135 LocVT = MVT::i64; 10136 LocInfo = CCValAssign::BCvt; 10137 } 10138 10139 // If this is a variadic argument, the RISC-V calling convention requires 10140 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 10141 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 10142 // be used regardless of whether the original argument was split during 10143 // legalisation or not. The argument will not be passed by registers if the 10144 // original type is larger than 2*XLEN, so the register alignment rule does 10145 // not apply. 10146 unsigned TwoXLenInBytes = (2 * XLen) / 8; 10147 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 10148 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 10149 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 10150 // Skip 'odd' register if necessary. 10151 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 10152 State.AllocateReg(ArgGPRs); 10153 } 10154 10155 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 10156 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 10157 State.getPendingArgFlags(); 10158 10159 assert(PendingLocs.size() == PendingArgFlags.size() && 10160 "PendingLocs and PendingArgFlags out of sync"); 10161 10162 // Handle passing f64 on RV32D with a soft float ABI or when floating point 10163 // registers are exhausted. 10164 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 10165 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 10166 "Can't lower f64 if it is split"); 10167 // Depending on available argument GPRS, f64 may be passed in a pair of 10168 // GPRs, split between a GPR and the stack, or passed completely on the 10169 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 10170 // cases. 10171 Register Reg = State.AllocateReg(ArgGPRs); 10172 LocVT = MVT::i32; 10173 if (!Reg) { 10174 unsigned StackOffset = State.AllocateStack(8, Align(8)); 10175 State.addLoc( 10176 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10177 return false; 10178 } 10179 if (!State.AllocateReg(ArgGPRs)) 10180 State.AllocateStack(4, Align(4)); 10181 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10182 return false; 10183 } 10184 10185 // Fixed-length vectors are located in the corresponding scalable-vector 10186 // container types. 10187 if (ValVT.isFixedLengthVector()) 10188 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10189 10190 // Split arguments might be passed indirectly, so keep track of the pending 10191 // values. Split vectors are passed via a mix of registers and indirectly, so 10192 // treat them as we would any other argument. 10193 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 10194 LocVT = XLenVT; 10195 LocInfo = CCValAssign::Indirect; 10196 PendingLocs.push_back( 10197 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 10198 PendingArgFlags.push_back(ArgFlags); 10199 if (!ArgFlags.isSplitEnd()) { 10200 return false; 10201 } 10202 } 10203 10204 // If the split argument only had two elements, it should be passed directly 10205 // in registers or on the stack. 10206 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 10207 PendingLocs.size() <= 2) { 10208 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 10209 // Apply the normal calling convention rules to the first half of the 10210 // split argument. 10211 CCValAssign VA = PendingLocs[0]; 10212 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 10213 PendingLocs.clear(); 10214 PendingArgFlags.clear(); 10215 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 10216 ArgFlags); 10217 } 10218 10219 // Allocate to a register if possible, or else a stack slot. 10220 Register Reg; 10221 unsigned StoreSizeBytes = XLen / 8; 10222 Align StackAlign = Align(XLen / 8); 10223 10224 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 10225 Reg = State.AllocateReg(ArgFPR16s); 10226 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 10227 Reg = State.AllocateReg(ArgFPR32s); 10228 else if (ValVT == MVT::f64 && !UseGPRForF64) 10229 Reg = State.AllocateReg(ArgFPR64s); 10230 else if (ValVT.isVector()) { 10231 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 10232 if (!Reg) { 10233 // For return values, the vector must be passed fully via registers or 10234 // via the stack. 10235 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 10236 // but we're using all of them. 10237 if (IsRet) 10238 return true; 10239 // Try using a GPR to pass the address 10240 if ((Reg = State.AllocateReg(ArgGPRs))) { 10241 LocVT = XLenVT; 10242 LocInfo = CCValAssign::Indirect; 10243 } else if (ValVT.isScalableVector()) { 10244 LocVT = XLenVT; 10245 LocInfo = CCValAssign::Indirect; 10246 } else { 10247 // Pass fixed-length vectors on the stack. 10248 LocVT = ValVT; 10249 StoreSizeBytes = ValVT.getStoreSize(); 10250 // Align vectors to their element sizes, being careful for vXi1 10251 // vectors. 10252 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10253 } 10254 } 10255 } else { 10256 Reg = State.AllocateReg(ArgGPRs); 10257 } 10258 10259 unsigned StackOffset = 10260 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 10261 10262 // If we reach this point and PendingLocs is non-empty, we must be at the 10263 // end of a split argument that must be passed indirectly. 10264 if (!PendingLocs.empty()) { 10265 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 10266 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 10267 10268 for (auto &It : PendingLocs) { 10269 if (Reg) 10270 It.convertToReg(Reg); 10271 else 10272 It.convertToMem(StackOffset); 10273 State.addLoc(It); 10274 } 10275 PendingLocs.clear(); 10276 PendingArgFlags.clear(); 10277 return false; 10278 } 10279 10280 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 10281 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 10282 "Expected an XLenVT or vector types at this stage"); 10283 10284 if (Reg) { 10285 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10286 return false; 10287 } 10288 10289 // When a floating-point value is passed on the stack, no bit-conversion is 10290 // needed. 10291 if (ValVT.isFloatingPoint()) { 10292 LocVT = ValVT; 10293 LocInfo = CCValAssign::Full; 10294 } 10295 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10296 return false; 10297 } 10298 10299 template <typename ArgTy> 10300 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 10301 for (const auto &ArgIdx : enumerate(Args)) { 10302 MVT ArgVT = ArgIdx.value().VT; 10303 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 10304 return ArgIdx.index(); 10305 } 10306 return None; 10307 } 10308 10309 void RISCVTargetLowering::analyzeInputArgs( 10310 MachineFunction &MF, CCState &CCInfo, 10311 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 10312 RISCVCCAssignFn Fn) const { 10313 unsigned NumArgs = Ins.size(); 10314 FunctionType *FType = MF.getFunction().getFunctionType(); 10315 10316 Optional<unsigned> FirstMaskArgument; 10317 if (Subtarget.hasVInstructions()) 10318 FirstMaskArgument = preAssignMask(Ins); 10319 10320 for (unsigned i = 0; i != NumArgs; ++i) { 10321 MVT ArgVT = Ins[i].VT; 10322 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 10323 10324 Type *ArgTy = nullptr; 10325 if (IsRet) 10326 ArgTy = FType->getReturnType(); 10327 else if (Ins[i].isOrigArg()) 10328 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 10329 10330 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10331 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10332 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 10333 FirstMaskArgument)) { 10334 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 10335 << EVT(ArgVT).getEVTString() << '\n'); 10336 llvm_unreachable(nullptr); 10337 } 10338 } 10339 } 10340 10341 void RISCVTargetLowering::analyzeOutputArgs( 10342 MachineFunction &MF, CCState &CCInfo, 10343 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 10344 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 10345 unsigned NumArgs = Outs.size(); 10346 10347 Optional<unsigned> FirstMaskArgument; 10348 if (Subtarget.hasVInstructions()) 10349 FirstMaskArgument = preAssignMask(Outs); 10350 10351 for (unsigned i = 0; i != NumArgs; i++) { 10352 MVT ArgVT = Outs[i].VT; 10353 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10354 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 10355 10356 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10357 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10358 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 10359 FirstMaskArgument)) { 10360 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 10361 << EVT(ArgVT).getEVTString() << "\n"); 10362 llvm_unreachable(nullptr); 10363 } 10364 } 10365 } 10366 10367 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 10368 // values. 10369 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 10370 const CCValAssign &VA, const SDLoc &DL, 10371 const RISCVSubtarget &Subtarget) { 10372 switch (VA.getLocInfo()) { 10373 default: 10374 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10375 case CCValAssign::Full: 10376 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 10377 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 10378 break; 10379 case CCValAssign::BCvt: 10380 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10381 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 10382 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10383 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 10384 else 10385 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 10386 break; 10387 } 10388 return Val; 10389 } 10390 10391 // The caller is responsible for loading the full value if the argument is 10392 // passed with CCValAssign::Indirect. 10393 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 10394 const CCValAssign &VA, const SDLoc &DL, 10395 const RISCVTargetLowering &TLI) { 10396 MachineFunction &MF = DAG.getMachineFunction(); 10397 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10398 EVT LocVT = VA.getLocVT(); 10399 SDValue Val; 10400 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 10401 Register VReg = RegInfo.createVirtualRegister(RC); 10402 RegInfo.addLiveIn(VA.getLocReg(), VReg); 10403 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 10404 10405 if (VA.getLocInfo() == CCValAssign::Indirect) 10406 return Val; 10407 10408 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 10409 } 10410 10411 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 10412 const CCValAssign &VA, const SDLoc &DL, 10413 const RISCVSubtarget &Subtarget) { 10414 EVT LocVT = VA.getLocVT(); 10415 10416 switch (VA.getLocInfo()) { 10417 default: 10418 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10419 case CCValAssign::Full: 10420 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 10421 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 10422 break; 10423 case CCValAssign::BCvt: 10424 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10425 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 10426 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10427 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 10428 else 10429 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 10430 break; 10431 } 10432 return Val; 10433 } 10434 10435 // The caller is responsible for loading the full value if the argument is 10436 // passed with CCValAssign::Indirect. 10437 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 10438 const CCValAssign &VA, const SDLoc &DL) { 10439 MachineFunction &MF = DAG.getMachineFunction(); 10440 MachineFrameInfo &MFI = MF.getFrameInfo(); 10441 EVT LocVT = VA.getLocVT(); 10442 EVT ValVT = VA.getValVT(); 10443 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 10444 if (ValVT.isScalableVector()) { 10445 // When the value is a scalable vector, we save the pointer which points to 10446 // the scalable vector value in the stack. The ValVT will be the pointer 10447 // type, instead of the scalable vector type. 10448 ValVT = LocVT; 10449 } 10450 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 10451 /*IsImmutable=*/true); 10452 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 10453 SDValue Val; 10454 10455 ISD::LoadExtType ExtType; 10456 switch (VA.getLocInfo()) { 10457 default: 10458 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10459 case CCValAssign::Full: 10460 case CCValAssign::Indirect: 10461 case CCValAssign::BCvt: 10462 ExtType = ISD::NON_EXTLOAD; 10463 break; 10464 } 10465 Val = DAG.getExtLoad( 10466 ExtType, DL, LocVT, Chain, FIN, 10467 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 10468 return Val; 10469 } 10470 10471 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 10472 const CCValAssign &VA, const SDLoc &DL) { 10473 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 10474 "Unexpected VA"); 10475 MachineFunction &MF = DAG.getMachineFunction(); 10476 MachineFrameInfo &MFI = MF.getFrameInfo(); 10477 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10478 10479 if (VA.isMemLoc()) { 10480 // f64 is passed on the stack. 10481 int FI = 10482 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 10483 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10484 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 10485 MachinePointerInfo::getFixedStack(MF, FI)); 10486 } 10487 10488 assert(VA.isRegLoc() && "Expected register VA assignment"); 10489 10490 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10491 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 10492 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 10493 SDValue Hi; 10494 if (VA.getLocReg() == RISCV::X17) { 10495 // Second half of f64 is passed on the stack. 10496 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 10497 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10498 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 10499 MachinePointerInfo::getFixedStack(MF, FI)); 10500 } else { 10501 // Second half of f64 is passed in another GPR. 10502 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10503 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 10504 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 10505 } 10506 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 10507 } 10508 10509 // FastCC has less than 1% performance improvement for some particular 10510 // benchmark. But theoretically, it may has benenfit for some cases. 10511 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 10512 unsigned ValNo, MVT ValVT, MVT LocVT, 10513 CCValAssign::LocInfo LocInfo, 10514 ISD::ArgFlagsTy ArgFlags, CCState &State, 10515 bool IsFixed, bool IsRet, Type *OrigTy, 10516 const RISCVTargetLowering &TLI, 10517 Optional<unsigned> FirstMaskArgument) { 10518 10519 // X5 and X6 might be used for save-restore libcall. 10520 static const MCPhysReg GPRList[] = { 10521 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 10522 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 10523 RISCV::X29, RISCV::X30, RISCV::X31}; 10524 10525 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10526 if (unsigned Reg = State.AllocateReg(GPRList)) { 10527 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10528 return false; 10529 } 10530 } 10531 10532 if (LocVT == MVT::f16) { 10533 static const MCPhysReg FPR16List[] = { 10534 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 10535 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 10536 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 10537 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 10538 if (unsigned Reg = State.AllocateReg(FPR16List)) { 10539 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10540 return false; 10541 } 10542 } 10543 10544 if (LocVT == MVT::f32) { 10545 static const MCPhysReg FPR32List[] = { 10546 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 10547 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 10548 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 10549 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 10550 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10551 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10552 return false; 10553 } 10554 } 10555 10556 if (LocVT == MVT::f64) { 10557 static const MCPhysReg FPR64List[] = { 10558 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 10559 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 10560 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 10561 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 10562 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10563 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10564 return false; 10565 } 10566 } 10567 10568 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 10569 unsigned Offset4 = State.AllocateStack(4, Align(4)); 10570 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 10571 return false; 10572 } 10573 10574 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 10575 unsigned Offset5 = State.AllocateStack(8, Align(8)); 10576 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 10577 return false; 10578 } 10579 10580 if (LocVT.isVector()) { 10581 if (unsigned Reg = 10582 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 10583 // Fixed-length vectors are located in the corresponding scalable-vector 10584 // container types. 10585 if (ValVT.isFixedLengthVector()) 10586 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10587 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10588 } else { 10589 // Try and pass the address via a "fast" GPR. 10590 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 10591 LocInfo = CCValAssign::Indirect; 10592 LocVT = TLI.getSubtarget().getXLenVT(); 10593 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 10594 } else if (ValVT.isFixedLengthVector()) { 10595 auto StackAlign = 10596 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10597 unsigned StackOffset = 10598 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 10599 State.addLoc( 10600 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10601 } else { 10602 // Can't pass scalable vectors on the stack. 10603 return true; 10604 } 10605 } 10606 10607 return false; 10608 } 10609 10610 return true; // CC didn't match. 10611 } 10612 10613 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 10614 CCValAssign::LocInfo LocInfo, 10615 ISD::ArgFlagsTy ArgFlags, CCState &State) { 10616 10617 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10618 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 10619 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 10620 static const MCPhysReg GPRList[] = { 10621 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 10622 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 10623 if (unsigned Reg = State.AllocateReg(GPRList)) { 10624 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10625 return false; 10626 } 10627 } 10628 10629 if (LocVT == MVT::f32) { 10630 // Pass in STG registers: F1, ..., F6 10631 // fs0 ... fs5 10632 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 10633 RISCV::F18_F, RISCV::F19_F, 10634 RISCV::F20_F, RISCV::F21_F}; 10635 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10636 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10637 return false; 10638 } 10639 } 10640 10641 if (LocVT == MVT::f64) { 10642 // Pass in STG registers: D1, ..., D6 10643 // fs6 ... fs11 10644 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 10645 RISCV::F24_D, RISCV::F25_D, 10646 RISCV::F26_D, RISCV::F27_D}; 10647 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10648 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10649 return false; 10650 } 10651 } 10652 10653 report_fatal_error("No registers left in GHC calling convention"); 10654 return true; 10655 } 10656 10657 // Transform physical registers into virtual registers. 10658 SDValue RISCVTargetLowering::LowerFormalArguments( 10659 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 10660 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 10661 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 10662 10663 MachineFunction &MF = DAG.getMachineFunction(); 10664 10665 switch (CallConv) { 10666 default: 10667 report_fatal_error("Unsupported calling convention"); 10668 case CallingConv::C: 10669 case CallingConv::Fast: 10670 break; 10671 case CallingConv::GHC: 10672 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10673 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10674 report_fatal_error( 10675 "GHC calling convention requires the F and D instruction set extensions"); 10676 } 10677 10678 const Function &Func = MF.getFunction(); 10679 if (Func.hasFnAttribute("interrupt")) { 10680 if (!Func.arg_empty()) 10681 report_fatal_error( 10682 "Functions with the interrupt attribute cannot have arguments!"); 10683 10684 StringRef Kind = 10685 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10686 10687 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10688 report_fatal_error( 10689 "Function interrupt attribute argument not supported!"); 10690 } 10691 10692 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10693 MVT XLenVT = Subtarget.getXLenVT(); 10694 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10695 // Used with vargs to acumulate store chains. 10696 std::vector<SDValue> OutChains; 10697 10698 // Assign locations to all of the incoming arguments. 10699 SmallVector<CCValAssign, 16> ArgLocs; 10700 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10701 10702 if (CallConv == CallingConv::GHC) 10703 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10704 else 10705 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10706 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10707 : CC_RISCV); 10708 10709 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10710 CCValAssign &VA = ArgLocs[i]; 10711 SDValue ArgValue; 10712 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10713 // case. 10714 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10715 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10716 else if (VA.isRegLoc()) 10717 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10718 else 10719 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10720 10721 if (VA.getLocInfo() == CCValAssign::Indirect) { 10722 // If the original argument was split and passed by reference (e.g. i128 10723 // on RV32), we need to load all parts of it here (using the same 10724 // address). Vectors may be partly split to registers and partly to the 10725 // stack, in which case the base address is partly offset and subsequent 10726 // stores are relative to that. 10727 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10728 MachinePointerInfo())); 10729 unsigned ArgIndex = Ins[i].OrigArgIndex; 10730 unsigned ArgPartOffset = Ins[i].PartOffset; 10731 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10732 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10733 CCValAssign &PartVA = ArgLocs[i + 1]; 10734 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10735 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10736 if (PartVA.getValVT().isScalableVector()) 10737 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10738 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10739 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10740 MachinePointerInfo())); 10741 ++i; 10742 } 10743 continue; 10744 } 10745 InVals.push_back(ArgValue); 10746 } 10747 10748 if (IsVarArg) { 10749 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10750 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10751 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10752 MachineFrameInfo &MFI = MF.getFrameInfo(); 10753 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10754 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10755 10756 // Offset of the first variable argument from stack pointer, and size of 10757 // the vararg save area. For now, the varargs save area is either zero or 10758 // large enough to hold a0-a7. 10759 int VaArgOffset, VarArgsSaveSize; 10760 10761 // If all registers are allocated, then all varargs must be passed on the 10762 // stack and we don't need to save any argregs. 10763 if (ArgRegs.size() == Idx) { 10764 VaArgOffset = CCInfo.getNextStackOffset(); 10765 VarArgsSaveSize = 0; 10766 } else { 10767 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10768 VaArgOffset = -VarArgsSaveSize; 10769 } 10770 10771 // Record the frame index of the first variable argument 10772 // which is a value necessary to VASTART. 10773 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10774 RVFI->setVarArgsFrameIndex(FI); 10775 10776 // If saving an odd number of registers then create an extra stack slot to 10777 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10778 // offsets to even-numbered registered remain 2*XLEN-aligned. 10779 if (Idx % 2) { 10780 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10781 VarArgsSaveSize += XLenInBytes; 10782 } 10783 10784 // Copy the integer registers that may have been used for passing varargs 10785 // to the vararg save area. 10786 for (unsigned I = Idx; I < ArgRegs.size(); 10787 ++I, VaArgOffset += XLenInBytes) { 10788 const Register Reg = RegInfo.createVirtualRegister(RC); 10789 RegInfo.addLiveIn(ArgRegs[I], Reg); 10790 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10791 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10792 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10793 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10794 MachinePointerInfo::getFixedStack(MF, FI)); 10795 cast<StoreSDNode>(Store.getNode()) 10796 ->getMemOperand() 10797 ->setValue((Value *)nullptr); 10798 OutChains.push_back(Store); 10799 } 10800 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10801 } 10802 10803 // All stores are grouped in one node to allow the matching between 10804 // the size of Ins and InVals. This only happens for vararg functions. 10805 if (!OutChains.empty()) { 10806 OutChains.push_back(Chain); 10807 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10808 } 10809 10810 return Chain; 10811 } 10812 10813 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10814 /// for tail call optimization. 10815 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10816 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10817 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10818 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10819 10820 auto &Callee = CLI.Callee; 10821 auto CalleeCC = CLI.CallConv; 10822 auto &Outs = CLI.Outs; 10823 auto &Caller = MF.getFunction(); 10824 auto CallerCC = Caller.getCallingConv(); 10825 10826 // Exception-handling functions need a special set of instructions to 10827 // indicate a return to the hardware. Tail-calling another function would 10828 // probably break this. 10829 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10830 // should be expanded as new function attributes are introduced. 10831 if (Caller.hasFnAttribute("interrupt")) 10832 return false; 10833 10834 // Do not tail call opt if the stack is used to pass parameters. 10835 if (CCInfo.getNextStackOffset() != 0) 10836 return false; 10837 10838 // Do not tail call opt if any parameters need to be passed indirectly. 10839 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10840 // passed indirectly. So the address of the value will be passed in a 10841 // register, or if not available, then the address is put on the stack. In 10842 // order to pass indirectly, space on the stack often needs to be allocated 10843 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10844 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10845 // are passed CCValAssign::Indirect. 10846 for (auto &VA : ArgLocs) 10847 if (VA.getLocInfo() == CCValAssign::Indirect) 10848 return false; 10849 10850 // Do not tail call opt if either caller or callee uses struct return 10851 // semantics. 10852 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10853 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10854 if (IsCallerStructRet || IsCalleeStructRet) 10855 return false; 10856 10857 // Externally-defined functions with weak linkage should not be 10858 // tail-called. The behaviour of branch instructions in this situation (as 10859 // used for tail calls) is implementation-defined, so we cannot rely on the 10860 // linker replacing the tail call with a return. 10861 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10862 const GlobalValue *GV = G->getGlobal(); 10863 if (GV->hasExternalWeakLinkage()) 10864 return false; 10865 } 10866 10867 // The callee has to preserve all registers the caller needs to preserve. 10868 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10869 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10870 if (CalleeCC != CallerCC) { 10871 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10872 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10873 return false; 10874 } 10875 10876 // Byval parameters hand the function a pointer directly into the stack area 10877 // we want to reuse during a tail call. Working around this *is* possible 10878 // but less efficient and uglier in LowerCall. 10879 for (auto &Arg : Outs) 10880 if (Arg.Flags.isByVal()) 10881 return false; 10882 10883 return true; 10884 } 10885 10886 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10887 return DAG.getDataLayout().getPrefTypeAlign( 10888 VT.getTypeForEVT(*DAG.getContext())); 10889 } 10890 10891 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10892 // and output parameter nodes. 10893 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10894 SmallVectorImpl<SDValue> &InVals) const { 10895 SelectionDAG &DAG = CLI.DAG; 10896 SDLoc &DL = CLI.DL; 10897 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10898 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10899 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10900 SDValue Chain = CLI.Chain; 10901 SDValue Callee = CLI.Callee; 10902 bool &IsTailCall = CLI.IsTailCall; 10903 CallingConv::ID CallConv = CLI.CallConv; 10904 bool IsVarArg = CLI.IsVarArg; 10905 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10906 MVT XLenVT = Subtarget.getXLenVT(); 10907 10908 MachineFunction &MF = DAG.getMachineFunction(); 10909 10910 // Analyze the operands of the call, assigning locations to each operand. 10911 SmallVector<CCValAssign, 16> ArgLocs; 10912 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10913 10914 if (CallConv == CallingConv::GHC) 10915 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10916 else 10917 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10918 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10919 : CC_RISCV); 10920 10921 // Check if it's really possible to do a tail call. 10922 if (IsTailCall) 10923 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10924 10925 if (IsTailCall) 10926 ++NumTailCalls; 10927 else if (CLI.CB && CLI.CB->isMustTailCall()) 10928 report_fatal_error("failed to perform tail call elimination on a call " 10929 "site marked musttail"); 10930 10931 // Get a count of how many bytes are to be pushed on the stack. 10932 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10933 10934 // Create local copies for byval args 10935 SmallVector<SDValue, 8> ByValArgs; 10936 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10937 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10938 if (!Flags.isByVal()) 10939 continue; 10940 10941 SDValue Arg = OutVals[i]; 10942 unsigned Size = Flags.getByValSize(); 10943 Align Alignment = Flags.getNonZeroByValAlign(); 10944 10945 int FI = 10946 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10947 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10948 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10949 10950 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10951 /*IsVolatile=*/false, 10952 /*AlwaysInline=*/false, IsTailCall, 10953 MachinePointerInfo(), MachinePointerInfo()); 10954 ByValArgs.push_back(FIPtr); 10955 } 10956 10957 if (!IsTailCall) 10958 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10959 10960 // Copy argument values to their designated locations. 10961 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10962 SmallVector<SDValue, 8> MemOpChains; 10963 SDValue StackPtr; 10964 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10965 CCValAssign &VA = ArgLocs[i]; 10966 SDValue ArgValue = OutVals[i]; 10967 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10968 10969 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10970 bool IsF64OnRV32DSoftABI = 10971 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 10972 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 10973 SDValue SplitF64 = DAG.getNode( 10974 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 10975 SDValue Lo = SplitF64.getValue(0); 10976 SDValue Hi = SplitF64.getValue(1); 10977 10978 Register RegLo = VA.getLocReg(); 10979 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 10980 10981 if (RegLo == RISCV::X17) { 10982 // Second half of f64 is passed on the stack. 10983 // Work out the address of the stack slot. 10984 if (!StackPtr.getNode()) 10985 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10986 // Emit the store. 10987 MemOpChains.push_back( 10988 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 10989 } else { 10990 // Second half of f64 is passed in another GPR. 10991 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10992 Register RegHigh = RegLo + 1; 10993 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 10994 } 10995 continue; 10996 } 10997 10998 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 10999 // as any other MemLoc. 11000 11001 // Promote the value if needed. 11002 // For now, only handle fully promoted and indirect arguments. 11003 if (VA.getLocInfo() == CCValAssign::Indirect) { 11004 // Store the argument in a stack slot and pass its address. 11005 Align StackAlign = 11006 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 11007 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 11008 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 11009 // If the original argument was split (e.g. i128), we need 11010 // to store the required parts of it here (and pass just one address). 11011 // Vectors may be partly split to registers and partly to the stack, in 11012 // which case the base address is partly offset and subsequent stores are 11013 // relative to that. 11014 unsigned ArgIndex = Outs[i].OrigArgIndex; 11015 unsigned ArgPartOffset = Outs[i].PartOffset; 11016 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 11017 // Calculate the total size to store. We don't have access to what we're 11018 // actually storing other than performing the loop and collecting the 11019 // info. 11020 SmallVector<std::pair<SDValue, SDValue>> Parts; 11021 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 11022 SDValue PartValue = OutVals[i + 1]; 11023 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 11024 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 11025 EVT PartVT = PartValue.getValueType(); 11026 if (PartVT.isScalableVector()) 11027 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 11028 StoredSize += PartVT.getStoreSize(); 11029 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 11030 Parts.push_back(std::make_pair(PartValue, Offset)); 11031 ++i; 11032 } 11033 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 11034 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 11035 MemOpChains.push_back( 11036 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 11037 MachinePointerInfo::getFixedStack(MF, FI))); 11038 for (const auto &Part : Parts) { 11039 SDValue PartValue = Part.first; 11040 SDValue PartOffset = Part.second; 11041 SDValue Address = 11042 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 11043 MemOpChains.push_back( 11044 DAG.getStore(Chain, DL, PartValue, Address, 11045 MachinePointerInfo::getFixedStack(MF, FI))); 11046 } 11047 ArgValue = SpillSlot; 11048 } else { 11049 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 11050 } 11051 11052 // Use local copy if it is a byval arg. 11053 if (Flags.isByVal()) 11054 ArgValue = ByValArgs[j++]; 11055 11056 if (VA.isRegLoc()) { 11057 // Queue up the argument copies and emit them at the end. 11058 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 11059 } else { 11060 assert(VA.isMemLoc() && "Argument not register or memory"); 11061 assert(!IsTailCall && "Tail call not allowed if stack is used " 11062 "for passing parameters"); 11063 11064 // Work out the address of the stack slot. 11065 if (!StackPtr.getNode()) 11066 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 11067 SDValue Address = 11068 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 11069 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 11070 11071 // Emit the store. 11072 MemOpChains.push_back( 11073 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 11074 } 11075 } 11076 11077 // Join the stores, which are independent of one another. 11078 if (!MemOpChains.empty()) 11079 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 11080 11081 SDValue Glue; 11082 11083 // Build a sequence of copy-to-reg nodes, chained and glued together. 11084 for (auto &Reg : RegsToPass) { 11085 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 11086 Glue = Chain.getValue(1); 11087 } 11088 11089 // Validate that none of the argument registers have been marked as 11090 // reserved, if so report an error. Do the same for the return address if this 11091 // is not a tailcall. 11092 validateCCReservedRegs(RegsToPass, MF); 11093 if (!IsTailCall && 11094 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 11095 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11096 MF.getFunction(), 11097 "Return address register required, but has been reserved."}); 11098 11099 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 11100 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 11101 // split it and then direct call can be matched by PseudoCALL. 11102 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 11103 const GlobalValue *GV = S->getGlobal(); 11104 11105 unsigned OpFlags = RISCVII::MO_CALL; 11106 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 11107 OpFlags = RISCVII::MO_PLT; 11108 11109 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 11110 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 11111 unsigned OpFlags = RISCVII::MO_CALL; 11112 11113 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 11114 nullptr)) 11115 OpFlags = RISCVII::MO_PLT; 11116 11117 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 11118 } 11119 11120 // The first call operand is the chain and the second is the target address. 11121 SmallVector<SDValue, 8> Ops; 11122 Ops.push_back(Chain); 11123 Ops.push_back(Callee); 11124 11125 // Add argument registers to the end of the list so that they are 11126 // known live into the call. 11127 for (auto &Reg : RegsToPass) 11128 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 11129 11130 if (!IsTailCall) { 11131 // Add a register mask operand representing the call-preserved registers. 11132 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11133 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 11134 assert(Mask && "Missing call preserved mask for calling convention"); 11135 Ops.push_back(DAG.getRegisterMask(Mask)); 11136 } 11137 11138 // Glue the call to the argument copies, if any. 11139 if (Glue.getNode()) 11140 Ops.push_back(Glue); 11141 11142 // Emit the call. 11143 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 11144 11145 if (IsTailCall) { 11146 MF.getFrameInfo().setHasTailCall(); 11147 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 11148 } 11149 11150 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 11151 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 11152 Glue = Chain.getValue(1); 11153 11154 // Mark the end of the call, which is glued to the call itself. 11155 Chain = DAG.getCALLSEQ_END(Chain, 11156 DAG.getConstant(NumBytes, DL, PtrVT, true), 11157 DAG.getConstant(0, DL, PtrVT, true), 11158 Glue, DL); 11159 Glue = Chain.getValue(1); 11160 11161 // Assign locations to each value returned by this call. 11162 SmallVector<CCValAssign, 16> RVLocs; 11163 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 11164 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 11165 11166 // Copy all of the result registers out of their specified physreg. 11167 for (auto &VA : RVLocs) { 11168 // Copy the value out 11169 SDValue RetValue = 11170 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 11171 // Glue the RetValue to the end of the call sequence 11172 Chain = RetValue.getValue(1); 11173 Glue = RetValue.getValue(2); 11174 11175 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 11176 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 11177 SDValue RetValue2 = 11178 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 11179 Chain = RetValue2.getValue(1); 11180 Glue = RetValue2.getValue(2); 11181 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 11182 RetValue2); 11183 } 11184 11185 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 11186 11187 InVals.push_back(RetValue); 11188 } 11189 11190 return Chain; 11191 } 11192 11193 bool RISCVTargetLowering::CanLowerReturn( 11194 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 11195 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 11196 SmallVector<CCValAssign, 16> RVLocs; 11197 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 11198 11199 Optional<unsigned> FirstMaskArgument; 11200 if (Subtarget.hasVInstructions()) 11201 FirstMaskArgument = preAssignMask(Outs); 11202 11203 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 11204 MVT VT = Outs[i].VT; 11205 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 11206 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 11207 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 11208 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 11209 *this, FirstMaskArgument)) 11210 return false; 11211 } 11212 return true; 11213 } 11214 11215 SDValue 11216 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 11217 bool IsVarArg, 11218 const SmallVectorImpl<ISD::OutputArg> &Outs, 11219 const SmallVectorImpl<SDValue> &OutVals, 11220 const SDLoc &DL, SelectionDAG &DAG) const { 11221 const MachineFunction &MF = DAG.getMachineFunction(); 11222 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 11223 11224 // Stores the assignment of the return value to a location. 11225 SmallVector<CCValAssign, 16> RVLocs; 11226 11227 // Info about the registers and stack slot. 11228 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 11229 *DAG.getContext()); 11230 11231 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 11232 nullptr, CC_RISCV); 11233 11234 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 11235 report_fatal_error("GHC functions return void only"); 11236 11237 SDValue Glue; 11238 SmallVector<SDValue, 4> RetOps(1, Chain); 11239 11240 // Copy the result values into the output registers. 11241 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 11242 SDValue Val = OutVals[i]; 11243 CCValAssign &VA = RVLocs[i]; 11244 assert(VA.isRegLoc() && "Can only return in registers!"); 11245 11246 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 11247 // Handle returning f64 on RV32D with a soft float ABI. 11248 assert(VA.isRegLoc() && "Expected return via registers"); 11249 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 11250 DAG.getVTList(MVT::i32, MVT::i32), Val); 11251 SDValue Lo = SplitF64.getValue(0); 11252 SDValue Hi = SplitF64.getValue(1); 11253 Register RegLo = VA.getLocReg(); 11254 assert(RegLo < RISCV::X31 && "Invalid register pair"); 11255 Register RegHi = RegLo + 1; 11256 11257 if (STI.isRegisterReservedByUser(RegLo) || 11258 STI.isRegisterReservedByUser(RegHi)) 11259 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11260 MF.getFunction(), 11261 "Return value register required, but has been reserved."}); 11262 11263 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 11264 Glue = Chain.getValue(1); 11265 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 11266 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 11267 Glue = Chain.getValue(1); 11268 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 11269 } else { 11270 // Handle a 'normal' return. 11271 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 11272 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 11273 11274 if (STI.isRegisterReservedByUser(VA.getLocReg())) 11275 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11276 MF.getFunction(), 11277 "Return value register required, but has been reserved."}); 11278 11279 // Guarantee that all emitted copies are stuck together. 11280 Glue = Chain.getValue(1); 11281 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 11282 } 11283 } 11284 11285 RetOps[0] = Chain; // Update chain. 11286 11287 // Add the glue node if we have it. 11288 if (Glue.getNode()) { 11289 RetOps.push_back(Glue); 11290 } 11291 11292 unsigned RetOpc = RISCVISD::RET_FLAG; 11293 // Interrupt service routines use different return instructions. 11294 const Function &Func = DAG.getMachineFunction().getFunction(); 11295 if (Func.hasFnAttribute("interrupt")) { 11296 if (!Func.getReturnType()->isVoidTy()) 11297 report_fatal_error( 11298 "Functions with the interrupt attribute must have void return type!"); 11299 11300 MachineFunction &MF = DAG.getMachineFunction(); 11301 StringRef Kind = 11302 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 11303 11304 if (Kind == "user") 11305 RetOpc = RISCVISD::URET_FLAG; 11306 else if (Kind == "supervisor") 11307 RetOpc = RISCVISD::SRET_FLAG; 11308 else 11309 RetOpc = RISCVISD::MRET_FLAG; 11310 } 11311 11312 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 11313 } 11314 11315 void RISCVTargetLowering::validateCCReservedRegs( 11316 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 11317 MachineFunction &MF) const { 11318 const Function &F = MF.getFunction(); 11319 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 11320 11321 if (llvm::any_of(Regs, [&STI](auto Reg) { 11322 return STI.isRegisterReservedByUser(Reg.first); 11323 })) 11324 F.getContext().diagnose(DiagnosticInfoUnsupported{ 11325 F, "Argument register required, but has been reserved."}); 11326 } 11327 11328 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 11329 return CI->isTailCall(); 11330 } 11331 11332 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 11333 #define NODE_NAME_CASE(NODE) \ 11334 case RISCVISD::NODE: \ 11335 return "RISCVISD::" #NODE; 11336 // clang-format off 11337 switch ((RISCVISD::NodeType)Opcode) { 11338 case RISCVISD::FIRST_NUMBER: 11339 break; 11340 NODE_NAME_CASE(RET_FLAG) 11341 NODE_NAME_CASE(URET_FLAG) 11342 NODE_NAME_CASE(SRET_FLAG) 11343 NODE_NAME_CASE(MRET_FLAG) 11344 NODE_NAME_CASE(CALL) 11345 NODE_NAME_CASE(SELECT_CC) 11346 NODE_NAME_CASE(BR_CC) 11347 NODE_NAME_CASE(BuildPairF64) 11348 NODE_NAME_CASE(SplitF64) 11349 NODE_NAME_CASE(TAIL) 11350 NODE_NAME_CASE(ADD_LO) 11351 NODE_NAME_CASE(HI) 11352 NODE_NAME_CASE(LLA) 11353 NODE_NAME_CASE(ADD_TPREL) 11354 NODE_NAME_CASE(LA) 11355 NODE_NAME_CASE(LA_TLS_IE) 11356 NODE_NAME_CASE(LA_TLS_GD) 11357 NODE_NAME_CASE(MULHSU) 11358 NODE_NAME_CASE(SLLW) 11359 NODE_NAME_CASE(SRAW) 11360 NODE_NAME_CASE(SRLW) 11361 NODE_NAME_CASE(DIVW) 11362 NODE_NAME_CASE(DIVUW) 11363 NODE_NAME_CASE(REMUW) 11364 NODE_NAME_CASE(ROLW) 11365 NODE_NAME_CASE(RORW) 11366 NODE_NAME_CASE(CLZW) 11367 NODE_NAME_CASE(CTZW) 11368 NODE_NAME_CASE(FSLW) 11369 NODE_NAME_CASE(FSRW) 11370 NODE_NAME_CASE(FSL) 11371 NODE_NAME_CASE(FSR) 11372 NODE_NAME_CASE(FMV_H_X) 11373 NODE_NAME_CASE(FMV_X_ANYEXTH) 11374 NODE_NAME_CASE(FMV_X_SIGNEXTH) 11375 NODE_NAME_CASE(FMV_W_X_RV64) 11376 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 11377 NODE_NAME_CASE(FCVT_X) 11378 NODE_NAME_CASE(FCVT_XU) 11379 NODE_NAME_CASE(FCVT_W_RV64) 11380 NODE_NAME_CASE(FCVT_WU_RV64) 11381 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 11382 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 11383 NODE_NAME_CASE(READ_CYCLE_WIDE) 11384 NODE_NAME_CASE(GREV) 11385 NODE_NAME_CASE(GREVW) 11386 NODE_NAME_CASE(GORC) 11387 NODE_NAME_CASE(GORCW) 11388 NODE_NAME_CASE(SHFL) 11389 NODE_NAME_CASE(SHFLW) 11390 NODE_NAME_CASE(UNSHFL) 11391 NODE_NAME_CASE(UNSHFLW) 11392 NODE_NAME_CASE(BFP) 11393 NODE_NAME_CASE(BFPW) 11394 NODE_NAME_CASE(BCOMPRESS) 11395 NODE_NAME_CASE(BCOMPRESSW) 11396 NODE_NAME_CASE(BDECOMPRESS) 11397 NODE_NAME_CASE(BDECOMPRESSW) 11398 NODE_NAME_CASE(VMV_V_X_VL) 11399 NODE_NAME_CASE(VFMV_V_F_VL) 11400 NODE_NAME_CASE(VMV_X_S) 11401 NODE_NAME_CASE(VMV_S_X_VL) 11402 NODE_NAME_CASE(VFMV_S_F_VL) 11403 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 11404 NODE_NAME_CASE(READ_VLENB) 11405 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 11406 NODE_NAME_CASE(VSLIDEUP_VL) 11407 NODE_NAME_CASE(VSLIDE1UP_VL) 11408 NODE_NAME_CASE(VSLIDEDOWN_VL) 11409 NODE_NAME_CASE(VSLIDE1DOWN_VL) 11410 NODE_NAME_CASE(VID_VL) 11411 NODE_NAME_CASE(VFNCVT_ROD_VL) 11412 NODE_NAME_CASE(VECREDUCE_ADD_VL) 11413 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 11414 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 11415 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 11416 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 11417 NODE_NAME_CASE(VECREDUCE_AND_VL) 11418 NODE_NAME_CASE(VECREDUCE_OR_VL) 11419 NODE_NAME_CASE(VECREDUCE_XOR_VL) 11420 NODE_NAME_CASE(VECREDUCE_FADD_VL) 11421 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 11422 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 11423 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 11424 NODE_NAME_CASE(ADD_VL) 11425 NODE_NAME_CASE(AND_VL) 11426 NODE_NAME_CASE(MUL_VL) 11427 NODE_NAME_CASE(OR_VL) 11428 NODE_NAME_CASE(SDIV_VL) 11429 NODE_NAME_CASE(SHL_VL) 11430 NODE_NAME_CASE(SREM_VL) 11431 NODE_NAME_CASE(SRA_VL) 11432 NODE_NAME_CASE(SRL_VL) 11433 NODE_NAME_CASE(SUB_VL) 11434 NODE_NAME_CASE(UDIV_VL) 11435 NODE_NAME_CASE(UREM_VL) 11436 NODE_NAME_CASE(XOR_VL) 11437 NODE_NAME_CASE(SADDSAT_VL) 11438 NODE_NAME_CASE(UADDSAT_VL) 11439 NODE_NAME_CASE(SSUBSAT_VL) 11440 NODE_NAME_CASE(USUBSAT_VL) 11441 NODE_NAME_CASE(FADD_VL) 11442 NODE_NAME_CASE(FSUB_VL) 11443 NODE_NAME_CASE(FMUL_VL) 11444 NODE_NAME_CASE(FDIV_VL) 11445 NODE_NAME_CASE(FNEG_VL) 11446 NODE_NAME_CASE(FABS_VL) 11447 NODE_NAME_CASE(FSQRT_VL) 11448 NODE_NAME_CASE(VFMADD_VL) 11449 NODE_NAME_CASE(VFNMADD_VL) 11450 NODE_NAME_CASE(VFMSUB_VL) 11451 NODE_NAME_CASE(VFNMSUB_VL) 11452 NODE_NAME_CASE(FCOPYSIGN_VL) 11453 NODE_NAME_CASE(SMIN_VL) 11454 NODE_NAME_CASE(SMAX_VL) 11455 NODE_NAME_CASE(UMIN_VL) 11456 NODE_NAME_CASE(UMAX_VL) 11457 NODE_NAME_CASE(FMINNUM_VL) 11458 NODE_NAME_CASE(FMAXNUM_VL) 11459 NODE_NAME_CASE(MULHS_VL) 11460 NODE_NAME_CASE(MULHU_VL) 11461 NODE_NAME_CASE(FP_TO_SINT_VL) 11462 NODE_NAME_CASE(FP_TO_UINT_VL) 11463 NODE_NAME_CASE(SINT_TO_FP_VL) 11464 NODE_NAME_CASE(UINT_TO_FP_VL) 11465 NODE_NAME_CASE(FP_EXTEND_VL) 11466 NODE_NAME_CASE(FP_ROUND_VL) 11467 NODE_NAME_CASE(VWMUL_VL) 11468 NODE_NAME_CASE(VWMULU_VL) 11469 NODE_NAME_CASE(VWMULSU_VL) 11470 NODE_NAME_CASE(VWADD_VL) 11471 NODE_NAME_CASE(VWADDU_VL) 11472 NODE_NAME_CASE(VWSUB_VL) 11473 NODE_NAME_CASE(VWSUBU_VL) 11474 NODE_NAME_CASE(VWADD_W_VL) 11475 NODE_NAME_CASE(VWADDU_W_VL) 11476 NODE_NAME_CASE(VWSUB_W_VL) 11477 NODE_NAME_CASE(VWSUBU_W_VL) 11478 NODE_NAME_CASE(SETCC_VL) 11479 NODE_NAME_CASE(VSELECT_VL) 11480 NODE_NAME_CASE(VP_MERGE_VL) 11481 NODE_NAME_CASE(VMAND_VL) 11482 NODE_NAME_CASE(VMOR_VL) 11483 NODE_NAME_CASE(VMXOR_VL) 11484 NODE_NAME_CASE(VMCLR_VL) 11485 NODE_NAME_CASE(VMSET_VL) 11486 NODE_NAME_CASE(VRGATHER_VX_VL) 11487 NODE_NAME_CASE(VRGATHER_VV_VL) 11488 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 11489 NODE_NAME_CASE(VSEXT_VL) 11490 NODE_NAME_CASE(VZEXT_VL) 11491 NODE_NAME_CASE(VCPOP_VL) 11492 NODE_NAME_CASE(READ_CSR) 11493 NODE_NAME_CASE(WRITE_CSR) 11494 NODE_NAME_CASE(SWAP_CSR) 11495 } 11496 // clang-format on 11497 return nullptr; 11498 #undef NODE_NAME_CASE 11499 } 11500 11501 /// getConstraintType - Given a constraint letter, return the type of 11502 /// constraint it is for this target. 11503 RISCVTargetLowering::ConstraintType 11504 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 11505 if (Constraint.size() == 1) { 11506 switch (Constraint[0]) { 11507 default: 11508 break; 11509 case 'f': 11510 return C_RegisterClass; 11511 case 'I': 11512 case 'J': 11513 case 'K': 11514 return C_Immediate; 11515 case 'A': 11516 return C_Memory; 11517 case 'S': // A symbolic address 11518 return C_Other; 11519 } 11520 } else { 11521 if (Constraint == "vr" || Constraint == "vm") 11522 return C_RegisterClass; 11523 } 11524 return TargetLowering::getConstraintType(Constraint); 11525 } 11526 11527 std::pair<unsigned, const TargetRegisterClass *> 11528 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11529 StringRef Constraint, 11530 MVT VT) const { 11531 // First, see if this is a constraint that directly corresponds to a 11532 // RISCV register class. 11533 if (Constraint.size() == 1) { 11534 switch (Constraint[0]) { 11535 case 'r': 11536 // TODO: Support fixed vectors up to XLen for P extension? 11537 if (VT.isVector()) 11538 break; 11539 return std::make_pair(0U, &RISCV::GPRRegClass); 11540 case 'f': 11541 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 11542 return std::make_pair(0U, &RISCV::FPR16RegClass); 11543 if (Subtarget.hasStdExtF() && VT == MVT::f32) 11544 return std::make_pair(0U, &RISCV::FPR32RegClass); 11545 if (Subtarget.hasStdExtD() && VT == MVT::f64) 11546 return std::make_pair(0U, &RISCV::FPR64RegClass); 11547 break; 11548 default: 11549 break; 11550 } 11551 } else if (Constraint == "vr") { 11552 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 11553 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11554 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 11555 return std::make_pair(0U, RC); 11556 } 11557 } else if (Constraint == "vm") { 11558 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 11559 return std::make_pair(0U, &RISCV::VMV0RegClass); 11560 } 11561 11562 // Clang will correctly decode the usage of register name aliases into their 11563 // official names. However, other frontends like `rustc` do not. This allows 11564 // users of these frontends to use the ABI names for registers in LLVM-style 11565 // register constraints. 11566 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 11567 .Case("{zero}", RISCV::X0) 11568 .Case("{ra}", RISCV::X1) 11569 .Case("{sp}", RISCV::X2) 11570 .Case("{gp}", RISCV::X3) 11571 .Case("{tp}", RISCV::X4) 11572 .Case("{t0}", RISCV::X5) 11573 .Case("{t1}", RISCV::X6) 11574 .Case("{t2}", RISCV::X7) 11575 .Cases("{s0}", "{fp}", RISCV::X8) 11576 .Case("{s1}", RISCV::X9) 11577 .Case("{a0}", RISCV::X10) 11578 .Case("{a1}", RISCV::X11) 11579 .Case("{a2}", RISCV::X12) 11580 .Case("{a3}", RISCV::X13) 11581 .Case("{a4}", RISCV::X14) 11582 .Case("{a5}", RISCV::X15) 11583 .Case("{a6}", RISCV::X16) 11584 .Case("{a7}", RISCV::X17) 11585 .Case("{s2}", RISCV::X18) 11586 .Case("{s3}", RISCV::X19) 11587 .Case("{s4}", RISCV::X20) 11588 .Case("{s5}", RISCV::X21) 11589 .Case("{s6}", RISCV::X22) 11590 .Case("{s7}", RISCV::X23) 11591 .Case("{s8}", RISCV::X24) 11592 .Case("{s9}", RISCV::X25) 11593 .Case("{s10}", RISCV::X26) 11594 .Case("{s11}", RISCV::X27) 11595 .Case("{t3}", RISCV::X28) 11596 .Case("{t4}", RISCV::X29) 11597 .Case("{t5}", RISCV::X30) 11598 .Case("{t6}", RISCV::X31) 11599 .Default(RISCV::NoRegister); 11600 if (XRegFromAlias != RISCV::NoRegister) 11601 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 11602 11603 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 11604 // TableGen record rather than the AsmName to choose registers for InlineAsm 11605 // constraints, plus we want to match those names to the widest floating point 11606 // register type available, manually select floating point registers here. 11607 // 11608 // The second case is the ABI name of the register, so that frontends can also 11609 // use the ABI names in register constraint lists. 11610 if (Subtarget.hasStdExtF()) { 11611 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 11612 .Cases("{f0}", "{ft0}", RISCV::F0_F) 11613 .Cases("{f1}", "{ft1}", RISCV::F1_F) 11614 .Cases("{f2}", "{ft2}", RISCV::F2_F) 11615 .Cases("{f3}", "{ft3}", RISCV::F3_F) 11616 .Cases("{f4}", "{ft4}", RISCV::F4_F) 11617 .Cases("{f5}", "{ft5}", RISCV::F5_F) 11618 .Cases("{f6}", "{ft6}", RISCV::F6_F) 11619 .Cases("{f7}", "{ft7}", RISCV::F7_F) 11620 .Cases("{f8}", "{fs0}", RISCV::F8_F) 11621 .Cases("{f9}", "{fs1}", RISCV::F9_F) 11622 .Cases("{f10}", "{fa0}", RISCV::F10_F) 11623 .Cases("{f11}", "{fa1}", RISCV::F11_F) 11624 .Cases("{f12}", "{fa2}", RISCV::F12_F) 11625 .Cases("{f13}", "{fa3}", RISCV::F13_F) 11626 .Cases("{f14}", "{fa4}", RISCV::F14_F) 11627 .Cases("{f15}", "{fa5}", RISCV::F15_F) 11628 .Cases("{f16}", "{fa6}", RISCV::F16_F) 11629 .Cases("{f17}", "{fa7}", RISCV::F17_F) 11630 .Cases("{f18}", "{fs2}", RISCV::F18_F) 11631 .Cases("{f19}", "{fs3}", RISCV::F19_F) 11632 .Cases("{f20}", "{fs4}", RISCV::F20_F) 11633 .Cases("{f21}", "{fs5}", RISCV::F21_F) 11634 .Cases("{f22}", "{fs6}", RISCV::F22_F) 11635 .Cases("{f23}", "{fs7}", RISCV::F23_F) 11636 .Cases("{f24}", "{fs8}", RISCV::F24_F) 11637 .Cases("{f25}", "{fs9}", RISCV::F25_F) 11638 .Cases("{f26}", "{fs10}", RISCV::F26_F) 11639 .Cases("{f27}", "{fs11}", RISCV::F27_F) 11640 .Cases("{f28}", "{ft8}", RISCV::F28_F) 11641 .Cases("{f29}", "{ft9}", RISCV::F29_F) 11642 .Cases("{f30}", "{ft10}", RISCV::F30_F) 11643 .Cases("{f31}", "{ft11}", RISCV::F31_F) 11644 .Default(RISCV::NoRegister); 11645 if (FReg != RISCV::NoRegister) { 11646 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 11647 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 11648 unsigned RegNo = FReg - RISCV::F0_F; 11649 unsigned DReg = RISCV::F0_D + RegNo; 11650 return std::make_pair(DReg, &RISCV::FPR64RegClass); 11651 } 11652 if (VT == MVT::f32 || VT == MVT::Other) 11653 return std::make_pair(FReg, &RISCV::FPR32RegClass); 11654 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 11655 unsigned RegNo = FReg - RISCV::F0_F; 11656 unsigned HReg = RISCV::F0_H + RegNo; 11657 return std::make_pair(HReg, &RISCV::FPR16RegClass); 11658 } 11659 } 11660 } 11661 11662 if (Subtarget.hasVInstructions()) { 11663 Register VReg = StringSwitch<Register>(Constraint.lower()) 11664 .Case("{v0}", RISCV::V0) 11665 .Case("{v1}", RISCV::V1) 11666 .Case("{v2}", RISCV::V2) 11667 .Case("{v3}", RISCV::V3) 11668 .Case("{v4}", RISCV::V4) 11669 .Case("{v5}", RISCV::V5) 11670 .Case("{v6}", RISCV::V6) 11671 .Case("{v7}", RISCV::V7) 11672 .Case("{v8}", RISCV::V8) 11673 .Case("{v9}", RISCV::V9) 11674 .Case("{v10}", RISCV::V10) 11675 .Case("{v11}", RISCV::V11) 11676 .Case("{v12}", RISCV::V12) 11677 .Case("{v13}", RISCV::V13) 11678 .Case("{v14}", RISCV::V14) 11679 .Case("{v15}", RISCV::V15) 11680 .Case("{v16}", RISCV::V16) 11681 .Case("{v17}", RISCV::V17) 11682 .Case("{v18}", RISCV::V18) 11683 .Case("{v19}", RISCV::V19) 11684 .Case("{v20}", RISCV::V20) 11685 .Case("{v21}", RISCV::V21) 11686 .Case("{v22}", RISCV::V22) 11687 .Case("{v23}", RISCV::V23) 11688 .Case("{v24}", RISCV::V24) 11689 .Case("{v25}", RISCV::V25) 11690 .Case("{v26}", RISCV::V26) 11691 .Case("{v27}", RISCV::V27) 11692 .Case("{v28}", RISCV::V28) 11693 .Case("{v29}", RISCV::V29) 11694 .Case("{v30}", RISCV::V30) 11695 .Case("{v31}", RISCV::V31) 11696 .Default(RISCV::NoRegister); 11697 if (VReg != RISCV::NoRegister) { 11698 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11699 return std::make_pair(VReg, &RISCV::VMRegClass); 11700 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11701 return std::make_pair(VReg, &RISCV::VRRegClass); 11702 for (const auto *RC : 11703 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11704 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11705 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11706 return std::make_pair(VReg, RC); 11707 } 11708 } 11709 } 11710 } 11711 11712 std::pair<Register, const TargetRegisterClass *> Res = 11713 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11714 11715 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11716 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11717 // Subtarget into account. 11718 if (Res.second == &RISCV::GPRF16RegClass || 11719 Res.second == &RISCV::GPRF32RegClass || 11720 Res.second == &RISCV::GPRF64RegClass) 11721 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11722 11723 return Res; 11724 } 11725 11726 unsigned 11727 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11728 // Currently only support length 1 constraints. 11729 if (ConstraintCode.size() == 1) { 11730 switch (ConstraintCode[0]) { 11731 case 'A': 11732 return InlineAsm::Constraint_A; 11733 default: 11734 break; 11735 } 11736 } 11737 11738 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11739 } 11740 11741 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11742 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11743 SelectionDAG &DAG) const { 11744 // Currently only support length 1 constraints. 11745 if (Constraint.length() == 1) { 11746 switch (Constraint[0]) { 11747 case 'I': 11748 // Validate & create a 12-bit signed immediate operand. 11749 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11750 uint64_t CVal = C->getSExtValue(); 11751 if (isInt<12>(CVal)) 11752 Ops.push_back( 11753 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11754 } 11755 return; 11756 case 'J': 11757 // Validate & create an integer zero operand. 11758 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11759 if (C->getZExtValue() == 0) 11760 Ops.push_back( 11761 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11762 return; 11763 case 'K': 11764 // Validate & create a 5-bit unsigned immediate operand. 11765 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11766 uint64_t CVal = C->getZExtValue(); 11767 if (isUInt<5>(CVal)) 11768 Ops.push_back( 11769 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11770 } 11771 return; 11772 case 'S': 11773 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11774 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11775 GA->getValueType(0))); 11776 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11777 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11778 BA->getValueType(0))); 11779 } 11780 return; 11781 default: 11782 break; 11783 } 11784 } 11785 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11786 } 11787 11788 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11789 Instruction *Inst, 11790 AtomicOrdering Ord) const { 11791 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 11792 return Builder.CreateFence(Ord); 11793 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 11794 return Builder.CreateFence(AtomicOrdering::Release); 11795 return nullptr; 11796 } 11797 11798 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11799 Instruction *Inst, 11800 AtomicOrdering Ord) const { 11801 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11802 return Builder.CreateFence(AtomicOrdering::Acquire); 11803 return nullptr; 11804 } 11805 11806 TargetLowering::AtomicExpansionKind 11807 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11808 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11809 // point operations can't be used in an lr/sc sequence without breaking the 11810 // forward-progress guarantee. 11811 if (AI->isFloatingPointOperation()) 11812 return AtomicExpansionKind::CmpXChg; 11813 11814 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11815 if (Size == 8 || Size == 16) 11816 return AtomicExpansionKind::MaskedIntrinsic; 11817 return AtomicExpansionKind::None; 11818 } 11819 11820 static Intrinsic::ID 11821 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11822 if (XLen == 32) { 11823 switch (BinOp) { 11824 default: 11825 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11826 case AtomicRMWInst::Xchg: 11827 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11828 case AtomicRMWInst::Add: 11829 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11830 case AtomicRMWInst::Sub: 11831 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11832 case AtomicRMWInst::Nand: 11833 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11834 case AtomicRMWInst::Max: 11835 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11836 case AtomicRMWInst::Min: 11837 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11838 case AtomicRMWInst::UMax: 11839 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11840 case AtomicRMWInst::UMin: 11841 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11842 } 11843 } 11844 11845 if (XLen == 64) { 11846 switch (BinOp) { 11847 default: 11848 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11849 case AtomicRMWInst::Xchg: 11850 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11851 case AtomicRMWInst::Add: 11852 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11853 case AtomicRMWInst::Sub: 11854 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11855 case AtomicRMWInst::Nand: 11856 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11857 case AtomicRMWInst::Max: 11858 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11859 case AtomicRMWInst::Min: 11860 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11861 case AtomicRMWInst::UMax: 11862 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11863 case AtomicRMWInst::UMin: 11864 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11865 } 11866 } 11867 11868 llvm_unreachable("Unexpected XLen\n"); 11869 } 11870 11871 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11872 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11873 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11874 unsigned XLen = Subtarget.getXLen(); 11875 Value *Ordering = 11876 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11877 Type *Tys[] = {AlignedAddr->getType()}; 11878 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11879 AI->getModule(), 11880 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11881 11882 if (XLen == 64) { 11883 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11884 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11885 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11886 } 11887 11888 Value *Result; 11889 11890 // Must pass the shift amount needed to sign extend the loaded value prior 11891 // to performing a signed comparison for min/max. ShiftAmt is the number of 11892 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11893 // is the number of bits to left+right shift the value in order to 11894 // sign-extend. 11895 if (AI->getOperation() == AtomicRMWInst::Min || 11896 AI->getOperation() == AtomicRMWInst::Max) { 11897 const DataLayout &DL = AI->getModule()->getDataLayout(); 11898 unsigned ValWidth = 11899 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11900 Value *SextShamt = 11901 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11902 Result = Builder.CreateCall(LrwOpScwLoop, 11903 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11904 } else { 11905 Result = 11906 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11907 } 11908 11909 if (XLen == 64) 11910 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11911 return Result; 11912 } 11913 11914 TargetLowering::AtomicExpansionKind 11915 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11916 AtomicCmpXchgInst *CI) const { 11917 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11918 if (Size == 8 || Size == 16) 11919 return AtomicExpansionKind::MaskedIntrinsic; 11920 return AtomicExpansionKind::None; 11921 } 11922 11923 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11924 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11925 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11926 unsigned XLen = Subtarget.getXLen(); 11927 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11928 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11929 if (XLen == 64) { 11930 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11931 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11932 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11933 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11934 } 11935 Type *Tys[] = {AlignedAddr->getType()}; 11936 Function *MaskedCmpXchg = 11937 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11938 Value *Result = Builder.CreateCall( 11939 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11940 if (XLen == 64) 11941 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11942 return Result; 11943 } 11944 11945 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT, 11946 EVT DataVT) const { 11947 return false; 11948 } 11949 11950 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11951 EVT VT) const { 11952 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11953 return false; 11954 11955 switch (FPVT.getSimpleVT().SimpleTy) { 11956 case MVT::f16: 11957 return Subtarget.hasStdExtZfh(); 11958 case MVT::f32: 11959 return Subtarget.hasStdExtF(); 11960 case MVT::f64: 11961 return Subtarget.hasStdExtD(); 11962 default: 11963 return false; 11964 } 11965 } 11966 11967 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11968 // If we are using the small code model, we can reduce size of jump table 11969 // entry to 4 bytes. 11970 if (Subtarget.is64Bit() && !isPositionIndependent() && 11971 getTargetMachine().getCodeModel() == CodeModel::Small) { 11972 return MachineJumpTableInfo::EK_Custom32; 11973 } 11974 return TargetLowering::getJumpTableEncoding(); 11975 } 11976 11977 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 11978 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 11979 unsigned uid, MCContext &Ctx) const { 11980 assert(Subtarget.is64Bit() && !isPositionIndependent() && 11981 getTargetMachine().getCodeModel() == CodeModel::Small); 11982 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 11983 } 11984 11985 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 11986 EVT VT) const { 11987 VT = VT.getScalarType(); 11988 11989 if (!VT.isSimple()) 11990 return false; 11991 11992 switch (VT.getSimpleVT().SimpleTy) { 11993 case MVT::f16: 11994 return Subtarget.hasStdExtZfh(); 11995 case MVT::f32: 11996 return Subtarget.hasStdExtF(); 11997 case MVT::f64: 11998 return Subtarget.hasStdExtD(); 11999 default: 12000 break; 12001 } 12002 12003 return false; 12004 } 12005 12006 Register RISCVTargetLowering::getExceptionPointerRegister( 12007 const Constant *PersonalityFn) const { 12008 return RISCV::X10; 12009 } 12010 12011 Register RISCVTargetLowering::getExceptionSelectorRegister( 12012 const Constant *PersonalityFn) const { 12013 return RISCV::X11; 12014 } 12015 12016 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 12017 // Return false to suppress the unnecessary extensions if the LibCall 12018 // arguments or return value is f32 type for LP64 ABI. 12019 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 12020 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 12021 return false; 12022 12023 return true; 12024 } 12025 12026 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 12027 if (Subtarget.is64Bit() && Type == MVT::i32) 12028 return true; 12029 12030 return IsSigned; 12031 } 12032 12033 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 12034 SDValue C) const { 12035 // Check integral scalar types. 12036 if (VT.isScalarInteger()) { 12037 // Omit the optimization if the sub target has the M extension and the data 12038 // size exceeds XLen. 12039 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 12040 return false; 12041 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 12042 // Break the MUL to a SLLI and an ADD/SUB. 12043 const APInt &Imm = ConstNode->getAPIntValue(); 12044 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 12045 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 12046 return true; 12047 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 12048 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 12049 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 12050 (Imm - 8).isPowerOf2())) 12051 return true; 12052 // Omit the following optimization if the sub target has the M extension 12053 // and the data size >= XLen. 12054 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 12055 return false; 12056 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 12057 // a pair of LUI/ADDI. 12058 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 12059 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 12060 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 12061 (1 - ImmS).isPowerOf2()) 12062 return true; 12063 } 12064 } 12065 } 12066 12067 return false; 12068 } 12069 12070 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 12071 SDValue ConstNode) const { 12072 // Let the DAGCombiner decide for vectors. 12073 EVT VT = AddNode.getValueType(); 12074 if (VT.isVector()) 12075 return true; 12076 12077 // Let the DAGCombiner decide for larger types. 12078 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 12079 return true; 12080 12081 // It is worse if c1 is simm12 while c1*c2 is not. 12082 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 12083 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 12084 const APInt &C1 = C1Node->getAPIntValue(); 12085 const APInt &C2 = C2Node->getAPIntValue(); 12086 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 12087 return false; 12088 12089 // Default to true and let the DAGCombiner decide. 12090 return true; 12091 } 12092 12093 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 12094 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 12095 bool *Fast) const { 12096 if (!VT.isVector()) { 12097 if (Fast) 12098 *Fast = false; 12099 return Subtarget.enableUnalignedScalarMem(); 12100 } 12101 12102 // All vector implementations must support element alignment 12103 EVT ElemVT = VT.getVectorElementType(); 12104 if (Alignment >= ElemVT.getStoreSize()) { 12105 if (Fast) 12106 *Fast = true; 12107 return true; 12108 } 12109 12110 return false; 12111 } 12112 12113 bool RISCVTargetLowering::splitValueIntoRegisterParts( 12114 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 12115 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 12116 bool IsABIRegCopy = CC.has_value(); 12117 EVT ValueVT = Val.getValueType(); 12118 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 12119 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 12120 // and cast to f32. 12121 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 12122 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 12123 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 12124 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 12125 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 12126 Parts[0] = Val; 12127 return true; 12128 } 12129 12130 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 12131 LLVMContext &Context = *DAG.getContext(); 12132 EVT ValueEltVT = ValueVT.getVectorElementType(); 12133 EVT PartEltVT = PartVT.getVectorElementType(); 12134 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 12135 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 12136 if (PartVTBitSize % ValueVTBitSize == 0) { 12137 assert(PartVTBitSize >= ValueVTBitSize); 12138 // If the element types are different, bitcast to the same element type of 12139 // PartVT first. 12140 // Give an example here, we want copy a <vscale x 1 x i8> value to 12141 // <vscale x 4 x i16>. 12142 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 12143 // subvector, then we can bitcast to <vscale x 4 x i16>. 12144 if (ValueEltVT != PartEltVT) { 12145 if (PartVTBitSize > ValueVTBitSize) { 12146 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 12147 assert(Count != 0 && "The number of element should not be zero."); 12148 EVT SameEltTypeVT = 12149 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 12150 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 12151 DAG.getUNDEF(SameEltTypeVT), Val, 12152 DAG.getVectorIdxConstant(0, DL)); 12153 } 12154 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 12155 } else { 12156 Val = 12157 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 12158 Val, DAG.getVectorIdxConstant(0, DL)); 12159 } 12160 Parts[0] = Val; 12161 return true; 12162 } 12163 } 12164 return false; 12165 } 12166 12167 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 12168 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 12169 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 12170 bool IsABIRegCopy = CC.has_value(); 12171 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 12172 SDValue Val = Parts[0]; 12173 12174 // Cast the f32 to i32, truncate to i16, and cast back to f16. 12175 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 12176 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 12177 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 12178 return Val; 12179 } 12180 12181 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 12182 LLVMContext &Context = *DAG.getContext(); 12183 SDValue Val = Parts[0]; 12184 EVT ValueEltVT = ValueVT.getVectorElementType(); 12185 EVT PartEltVT = PartVT.getVectorElementType(); 12186 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 12187 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 12188 if (PartVTBitSize % ValueVTBitSize == 0) { 12189 assert(PartVTBitSize >= ValueVTBitSize); 12190 EVT SameEltTypeVT = ValueVT; 12191 // If the element types are different, convert it to the same element type 12192 // of PartVT. 12193 // Give an example here, we want copy a <vscale x 1 x i8> value from 12194 // <vscale x 4 x i16>. 12195 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 12196 // then we can extract <vscale x 1 x i8>. 12197 if (ValueEltVT != PartEltVT) { 12198 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 12199 assert(Count != 0 && "The number of element should not be zero."); 12200 SameEltTypeVT = 12201 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 12202 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 12203 } 12204 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 12205 DAG.getVectorIdxConstant(0, DL)); 12206 return Val; 12207 } 12208 } 12209 return SDValue(); 12210 } 12211 12212 SDValue 12213 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 12214 SelectionDAG &DAG, 12215 SmallVectorImpl<SDNode *> &Created) const { 12216 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 12217 if (isIntDivCheap(N->getValueType(0), Attr)) 12218 return SDValue(N, 0); // Lower SDIV as SDIV 12219 12220 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 12221 "Unexpected divisor!"); 12222 12223 // Conditional move is needed, so do the transformation iff Zbt is enabled. 12224 if (!Subtarget.hasStdExtZbt()) 12225 return SDValue(); 12226 12227 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 12228 // Besides, more critical path instructions will be generated when dividing 12229 // by 2. So we keep using the original DAGs for these cases. 12230 unsigned Lg2 = Divisor.countTrailingZeros(); 12231 if (Lg2 == 1 || Lg2 >= 12) 12232 return SDValue(); 12233 12234 // fold (sdiv X, pow2) 12235 EVT VT = N->getValueType(0); 12236 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 12237 return SDValue(); 12238 12239 SDLoc DL(N); 12240 SDValue N0 = N->getOperand(0); 12241 SDValue Zero = DAG.getConstant(0, DL, VT); 12242 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 12243 12244 // Add (N0 < 0) ? Pow2 - 1 : 0; 12245 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 12246 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 12247 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 12248 12249 Created.push_back(Cmp.getNode()); 12250 Created.push_back(Add.getNode()); 12251 Created.push_back(Sel.getNode()); 12252 12253 // Divide by pow2. 12254 SDValue SRA = 12255 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 12256 12257 // If we're dividing by a positive value, we're done. Otherwise, we must 12258 // negate the result. 12259 if (Divisor.isNonNegative()) 12260 return SRA; 12261 12262 Created.push_back(SRA.getNode()); 12263 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 12264 } 12265 12266 #define GET_REGISTER_MATCHER 12267 #include "RISCVGenAsmMatcher.inc" 12268 12269 Register 12270 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 12271 const MachineFunction &MF) const { 12272 Register Reg = MatchRegisterAltName(RegName); 12273 if (Reg == RISCV::NoRegister) 12274 Reg = MatchRegisterName(RegName); 12275 if (Reg == RISCV::NoRegister) 12276 report_fatal_error( 12277 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 12278 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 12279 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 12280 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 12281 StringRef(RegName) + "\".")); 12282 return Reg; 12283 } 12284 12285 namespace llvm { 12286 namespace RISCVVIntrinsicsTable { 12287 12288 #define GET_RISCVVIntrinsicsTable_IMPL 12289 #include "RISCVGenSearchableTables.inc" 12290 12291 } // namespace RISCVVIntrinsicsTable 12292 12293 } // namespace llvm 12294