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 } 529 530 for (MVT VT : IntVecVTs) { 531 if (!isTypeLegal(VT)) 532 continue; 533 534 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 535 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 536 537 // Vectors implement MULHS/MULHU. 538 setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand); 539 540 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 541 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) 542 setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand); 543 544 setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT, 545 Legal); 546 547 setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand); 548 549 setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP, ISD::BSWAP}, VT, 550 Expand); 551 552 setOperationAction(ISD::BSWAP, VT, Expand); 553 554 // Custom-lower extensions and truncations from/to mask types. 555 setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, 556 VT, Custom); 557 558 // RVV has native int->float & float->int conversions where the 559 // element type sizes are within one power-of-two of each other. Any 560 // wider distances between type sizes have to be lowered as sequences 561 // which progressively narrow the gap in stages. 562 setOperationAction( 563 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 564 VT, Custom); 565 566 setOperationAction( 567 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal); 568 569 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 570 // nodes which truncate by one power of two at a time. 571 setOperationAction(ISD::TRUNCATE, VT, Custom); 572 573 // Custom-lower insert/extract operations to simplify patterns. 574 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 575 Custom); 576 577 // Custom-lower reduction operations to set up the corresponding custom 578 // nodes' operands. 579 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, 580 ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR, 581 ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 582 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}, 583 VT, Custom); 584 585 setOperationAction(IntegerVPOps, VT, Custom); 586 587 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 588 589 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 590 VT, Custom); 591 592 setOperationAction( 593 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 594 Custom); 595 596 setOperationAction( 597 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 598 VT, Custom); 599 600 setOperationAction(ISD::SELECT, VT, Custom); 601 setOperationAction(ISD::SELECT_CC, VT, Expand); 602 603 setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom); 604 605 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 606 setTruncStoreAction(VT, OtherVT, Expand); 607 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 608 VT, Expand); 609 } 610 611 // Splice 612 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 613 614 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 615 // type that can represent the value exactly. 616 if (VT.getVectorElementType() != MVT::i64) { 617 MVT FloatEltVT = 618 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 619 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 620 if (isTypeLegal(FloatVT)) { 621 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 622 Custom); 623 } 624 } 625 } 626 627 // Expand various CCs to best match the RVV ISA, which natively supports UNE 628 // but no other unordered comparisons, and supports all ordered comparisons 629 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 630 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 631 // and we pattern-match those back to the "original", swapping operands once 632 // more. This way we catch both operations and both "vf" and "fv" forms with 633 // fewer patterns. 634 static const ISD::CondCode VFPCCToExpand[] = { 635 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 636 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 637 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 638 }; 639 640 // Sets common operation actions on RVV floating-point vector types. 641 const auto SetCommonVFPActions = [&](MVT VT) { 642 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 643 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 644 // sizes are within one power-of-two of each other. Therefore conversions 645 // between vXf16 and vXf64 must be lowered as sequences which convert via 646 // vXf32. 647 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 648 // Custom-lower insert/extract operations to simplify patterns. 649 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 650 Custom); 651 // Expand various condition codes (explained above). 652 setCondCodeAction(VFPCCToExpand, VT, Expand); 653 654 setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal); 655 656 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 657 VT, Custom); 658 659 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 660 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 661 VT, Custom); 662 663 // Expand FP operations that need libcalls. 664 setOperationAction(ISD::FREM, VT, Expand); 665 setOperationAction(ISD::FPOW, VT, Expand); 666 setOperationAction(ISD::FCOS, VT, Expand); 667 setOperationAction(ISD::FSIN, VT, Expand); 668 setOperationAction(ISD::FSINCOS, VT, Expand); 669 setOperationAction(ISD::FEXP, VT, Expand); 670 setOperationAction(ISD::FEXP2, VT, Expand); 671 setOperationAction(ISD::FLOG, VT, Expand); 672 setOperationAction(ISD::FLOG2, VT, Expand); 673 setOperationAction(ISD::FLOG10, VT, Expand); 674 setOperationAction(ISD::FRINT, VT, Expand); 675 setOperationAction(ISD::FNEARBYINT, VT, Expand); 676 677 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 678 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 679 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 680 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 681 682 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 683 684 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 685 686 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 687 VT, Custom); 688 689 setOperationAction( 690 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 691 Custom); 692 693 setOperationAction(ISD::SELECT, VT, Custom); 694 setOperationAction(ISD::SELECT_CC, VT, Expand); 695 696 setOperationAction( 697 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 698 VT, Custom); 699 700 setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom); 701 702 setOperationAction(FloatingPointVPOps, VT, Custom); 703 }; 704 705 // Sets common extload/truncstore actions on RVV floating-point vector 706 // types. 707 const auto SetCommonVFPExtLoadTruncStoreActions = 708 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 709 for (auto SmallVT : SmallerVTs) { 710 setTruncStoreAction(VT, SmallVT, Expand); 711 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 712 } 713 }; 714 715 if (Subtarget.hasVInstructionsF16()) { 716 for (MVT VT : F16VecVTs) { 717 if (!isTypeLegal(VT)) 718 continue; 719 SetCommonVFPActions(VT); 720 } 721 } 722 723 if (Subtarget.hasVInstructionsF32()) { 724 for (MVT VT : F32VecVTs) { 725 if (!isTypeLegal(VT)) 726 continue; 727 SetCommonVFPActions(VT); 728 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 729 } 730 } 731 732 if (Subtarget.hasVInstructionsF64()) { 733 for (MVT VT : F64VecVTs) { 734 if (!isTypeLegal(VT)) 735 continue; 736 SetCommonVFPActions(VT); 737 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 738 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 739 } 740 } 741 742 if (Subtarget.useRVVForFixedLengthVectors()) { 743 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 744 if (!useRVVForFixedLengthVectorVT(VT)) 745 continue; 746 747 // By default everything must be expanded. 748 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 749 setOperationAction(Op, VT, Expand); 750 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 751 setTruncStoreAction(VT, OtherVT, Expand); 752 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, 753 OtherVT, VT, Expand); 754 } 755 756 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 757 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 758 Custom); 759 760 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT, 761 Custom); 762 763 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 764 VT, Custom); 765 766 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 767 768 setOperationAction(ISD::SETCC, VT, Custom); 769 770 setOperationAction(ISD::SELECT, VT, Custom); 771 772 setOperationAction(ISD::TRUNCATE, VT, Custom); 773 774 setOperationAction(ISD::BITCAST, VT, Custom); 775 776 setOperationAction( 777 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 778 Custom); 779 780 setOperationAction( 781 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 782 Custom); 783 784 setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, 785 ISD::FP_TO_UINT}, 786 VT, Custom); 787 788 // Operations below are different for between masks and other vectors. 789 if (VT.getVectorElementType() == MVT::i1) { 790 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND, 791 ISD::OR, ISD::XOR}, 792 VT, Custom); 793 794 setOperationAction( 795 {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_TRUNCATE}, 796 VT, Custom); 797 continue; 798 } 799 800 // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to 801 // it before type legalization for i64 vectors on RV32. It will then be 802 // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle. 803 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 804 // improvements first. 805 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 806 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 807 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 808 } 809 810 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 811 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 812 813 setOperationAction( 814 {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom); 815 816 setOperationAction( 817 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 818 Custom); 819 820 setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR, 821 ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV, 822 ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL}, 823 VT, Custom); 824 825 setOperationAction( 826 {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom); 827 828 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 829 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) 830 setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom); 831 832 setOperationAction( 833 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, 834 Custom); 835 836 setOperationAction(ISD::VSELECT, VT, Custom); 837 setOperationAction(ISD::SELECT_CC, VT, Expand); 838 839 setOperationAction( 840 {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom); 841 842 // Custom-lower reduction operations to set up the corresponding custom 843 // nodes' operands. 844 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX, 845 ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX, 846 ISD::VECREDUCE_UMIN}, 847 VT, Custom); 848 849 setOperationAction(IntegerVPOps, VT, Custom); 850 851 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 852 // type that can represent the value exactly. 853 if (VT.getVectorElementType() != MVT::i64) { 854 MVT FloatEltVT = 855 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 856 EVT FloatVT = 857 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 858 if (isTypeLegal(FloatVT)) 859 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 860 Custom); 861 } 862 } 863 864 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 865 if (!useRVVForFixedLengthVectorVT(VT)) 866 continue; 867 868 // By default everything must be expanded. 869 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 870 setOperationAction(Op, VT, Expand); 871 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 872 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 873 setTruncStoreAction(VT, OtherVT, Expand); 874 } 875 876 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 877 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 878 Custom); 879 880 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS, 881 ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT, 882 ISD::EXTRACT_VECTOR_ELT}, 883 VT, Custom); 884 885 setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE, 886 ISD::MGATHER, ISD::MSCATTER}, 887 VT, Custom); 888 889 setOperationAction( 890 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 891 Custom); 892 893 setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV, 894 ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT, 895 ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM}, 896 VT, Custom); 897 898 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 899 900 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 901 VT, Custom); 902 903 for (auto CC : VFPCCToExpand) 904 setCondCodeAction(CC, VT, Expand); 905 906 setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom); 907 setOperationAction(ISD::SELECT_CC, VT, Expand); 908 909 setOperationAction(ISD::BITCAST, VT, Custom); 910 911 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 912 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 913 VT, Custom); 914 915 setOperationAction(FloatingPointVPOps, VT, Custom); 916 } 917 918 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 919 setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64}, 920 Custom); 921 if (Subtarget.hasStdExtZfh()) 922 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 923 if (Subtarget.hasStdExtF()) 924 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 925 if (Subtarget.hasStdExtD()) 926 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 927 } 928 } 929 930 // Function alignments. 931 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 932 setMinFunctionAlignment(FunctionAlignment); 933 setPrefFunctionAlignment(FunctionAlignment); 934 935 setMinimumJumpTableEntries(5); 936 937 // Jumps are expensive, compared to logic 938 setJumpIsExpensive(); 939 940 setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND, 941 ISD::OR, ISD::XOR}); 942 943 if (Subtarget.hasStdExtF()) 944 setTargetDAGCombine({ISD::FADD, ISD::FMAXNUM, ISD::FMINNUM}); 945 946 if (Subtarget.hasStdExtZbp()) 947 setTargetDAGCombine({ISD::ROTL, ISD::ROTR}); 948 949 if (Subtarget.hasStdExtZbb()) 950 setTargetDAGCombine({ISD::UMAX, ISD::UMIN, ISD::SMAX, ISD::SMIN}); 951 952 if (Subtarget.hasStdExtZbkb()) 953 setTargetDAGCombine(ISD::BITREVERSE); 954 if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb()) 955 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 956 if (Subtarget.hasStdExtF()) 957 setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT, 958 ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}); 959 if (Subtarget.hasVInstructions()) 960 setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER, 961 ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL, 962 ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR}); 963 if (Subtarget.useRVVForFixedLengthVectors()) 964 setTargetDAGCombine(ISD::BITCAST); 965 966 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 967 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 968 } 969 970 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 971 LLVMContext &Context, 972 EVT VT) const { 973 if (!VT.isVector()) 974 return getPointerTy(DL); 975 if (Subtarget.hasVInstructions() && 976 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 977 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 978 return VT.changeVectorElementTypeToInteger(); 979 } 980 981 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 982 return Subtarget.getXLenVT(); 983 } 984 985 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 986 const CallInst &I, 987 MachineFunction &MF, 988 unsigned Intrinsic) const { 989 auto &DL = I.getModule()->getDataLayout(); 990 switch (Intrinsic) { 991 default: 992 return false; 993 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 994 case Intrinsic::riscv_masked_atomicrmw_add_i32: 995 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 996 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 997 case Intrinsic::riscv_masked_atomicrmw_max_i32: 998 case Intrinsic::riscv_masked_atomicrmw_min_i32: 999 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1000 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1001 case Intrinsic::riscv_masked_cmpxchg_i32: 1002 Info.opc = ISD::INTRINSIC_W_CHAIN; 1003 Info.memVT = MVT::i32; 1004 Info.ptrVal = I.getArgOperand(0); 1005 Info.offset = 0; 1006 Info.align = Align(4); 1007 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1008 MachineMemOperand::MOVolatile; 1009 return true; 1010 case Intrinsic::riscv_masked_strided_load: 1011 Info.opc = ISD::INTRINSIC_W_CHAIN; 1012 Info.ptrVal = I.getArgOperand(1); 1013 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1014 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1015 Info.size = MemoryLocation::UnknownSize; 1016 Info.flags |= MachineMemOperand::MOLoad; 1017 return true; 1018 case Intrinsic::riscv_masked_strided_store: 1019 Info.opc = ISD::INTRINSIC_VOID; 1020 Info.ptrVal = I.getArgOperand(1); 1021 Info.memVT = 1022 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1023 Info.align = Align( 1024 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1025 8); 1026 Info.size = MemoryLocation::UnknownSize; 1027 Info.flags |= MachineMemOperand::MOStore; 1028 return true; 1029 case Intrinsic::riscv_seg2_load: 1030 case Intrinsic::riscv_seg3_load: 1031 case Intrinsic::riscv_seg4_load: 1032 case Intrinsic::riscv_seg5_load: 1033 case Intrinsic::riscv_seg6_load: 1034 case Intrinsic::riscv_seg7_load: 1035 case Intrinsic::riscv_seg8_load: 1036 Info.opc = ISD::INTRINSIC_W_CHAIN; 1037 Info.ptrVal = I.getArgOperand(0); 1038 Info.memVT = 1039 getValueType(DL, I.getType()->getStructElementType(0)->getScalarType()); 1040 Info.align = 1041 Align(DL.getTypeSizeInBits( 1042 I.getType()->getStructElementType(0)->getScalarType()) / 1043 8); 1044 Info.size = MemoryLocation::UnknownSize; 1045 Info.flags |= MachineMemOperand::MOLoad; 1046 return true; 1047 } 1048 } 1049 1050 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1051 const AddrMode &AM, Type *Ty, 1052 unsigned AS, 1053 Instruction *I) const { 1054 // No global is ever allowed as a base. 1055 if (AM.BaseGV) 1056 return false; 1057 1058 // RVV instructions only support register addressing. 1059 if (Subtarget.hasVInstructions() && isa<VectorType>(Ty)) 1060 return AM.HasBaseReg && AM.Scale == 0 && !AM.BaseOffs; 1061 1062 // Require a 12-bit signed offset. 1063 if (!isInt<12>(AM.BaseOffs)) 1064 return false; 1065 1066 switch (AM.Scale) { 1067 case 0: // "r+i" or just "i", depending on HasBaseReg. 1068 break; 1069 case 1: 1070 if (!AM.HasBaseReg) // allow "r+i". 1071 break; 1072 return false; // disallow "r+r" or "r+r+i". 1073 default: 1074 return false; 1075 } 1076 1077 return true; 1078 } 1079 1080 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1081 return isInt<12>(Imm); 1082 } 1083 1084 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1085 return isInt<12>(Imm); 1086 } 1087 1088 // On RV32, 64-bit integers are split into their high and low parts and held 1089 // in two different registers, so the trunc is free since the low register can 1090 // just be used. 1091 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1092 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1093 return false; 1094 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1095 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1096 return (SrcBits == 64 && DestBits == 32); 1097 } 1098 1099 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1100 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1101 !SrcVT.isInteger() || !DstVT.isInteger()) 1102 return false; 1103 unsigned SrcBits = SrcVT.getSizeInBits(); 1104 unsigned DestBits = DstVT.getSizeInBits(); 1105 return (SrcBits == 64 && DestBits == 32); 1106 } 1107 1108 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1109 // Zexts are free if they can be combined with a load. 1110 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1111 // poorly with type legalization of compares preferring sext. 1112 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1113 EVT MemVT = LD->getMemoryVT(); 1114 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1115 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1116 LD->getExtensionType() == ISD::ZEXTLOAD)) 1117 return true; 1118 } 1119 1120 return TargetLowering::isZExtFree(Val, VT2); 1121 } 1122 1123 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1124 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1125 } 1126 1127 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const { 1128 return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32); 1129 } 1130 1131 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1132 return Subtarget.hasStdExtZbb(); 1133 } 1134 1135 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1136 return Subtarget.hasStdExtZbb(); 1137 } 1138 1139 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1140 EVT VT = Y.getValueType(); 1141 1142 // FIXME: Support vectors once we have tests. 1143 if (VT.isVector()) 1144 return false; 1145 1146 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1147 Subtarget.hasStdExtZbkb()) && 1148 !isa<ConstantSDNode>(Y); 1149 } 1150 1151 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const { 1152 // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position. 1153 auto *C = dyn_cast<ConstantSDNode>(Y); 1154 return C && C->getAPIntValue().ule(10); 1155 } 1156 1157 bool RISCVTargetLowering:: 1158 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 1159 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y, 1160 unsigned OldShiftOpcode, unsigned NewShiftOpcode, 1161 SelectionDAG &DAG) const { 1162 // One interesting pattern that we'd want to form is 'bit extract': 1163 // ((1 >> Y) & 1) ==/!= 0 1164 // But we also need to be careful not to try to reverse that fold. 1165 1166 // Is this '((1 >> Y) & 1)'? 1167 if (XC && OldShiftOpcode == ISD::SRL && XC->isOne()) 1168 return false; // Keep the 'bit extract' pattern. 1169 1170 // Will this be '((1 >> Y) & 1)' after the transform? 1171 if (NewShiftOpcode == ISD::SRL && CC->isOne()) 1172 return true; // Do form the 'bit extract' pattern. 1173 1174 // If 'X' is a constant, and we transform, then we will immediately 1175 // try to undo the fold, thus causing endless combine loop. 1176 // So only do the transform if X is not a constant. This matches the default 1177 // implementation of this function. 1178 return !XC; 1179 } 1180 1181 /// Check if sinking \p I's operands to I's basic block is profitable, because 1182 /// the operands can be folded into a target instruction, e.g. 1183 /// splats of scalars can fold into vector instructions. 1184 bool RISCVTargetLowering::shouldSinkOperands( 1185 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1186 using namespace llvm::PatternMatch; 1187 1188 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1189 return false; 1190 1191 auto IsSinker = [&](Instruction *I, int Operand) { 1192 switch (I->getOpcode()) { 1193 case Instruction::Add: 1194 case Instruction::Sub: 1195 case Instruction::Mul: 1196 case Instruction::And: 1197 case Instruction::Or: 1198 case Instruction::Xor: 1199 case Instruction::FAdd: 1200 case Instruction::FSub: 1201 case Instruction::FMul: 1202 case Instruction::FDiv: 1203 case Instruction::ICmp: 1204 case Instruction::FCmp: 1205 return true; 1206 case Instruction::Shl: 1207 case Instruction::LShr: 1208 case Instruction::AShr: 1209 case Instruction::UDiv: 1210 case Instruction::SDiv: 1211 case Instruction::URem: 1212 case Instruction::SRem: 1213 return Operand == 1; 1214 case Instruction::Call: 1215 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1216 switch (II->getIntrinsicID()) { 1217 case Intrinsic::fma: 1218 case Intrinsic::vp_fma: 1219 return Operand == 0 || Operand == 1; 1220 // FIXME: Our patterns can only match vx/vf instructions when the splat 1221 // it on the RHS, because TableGen doesn't recognize our VP operations 1222 // as commutative. 1223 case Intrinsic::vp_add: 1224 case Intrinsic::vp_mul: 1225 case Intrinsic::vp_and: 1226 case Intrinsic::vp_or: 1227 case Intrinsic::vp_xor: 1228 case Intrinsic::vp_fadd: 1229 case Intrinsic::vp_fmul: 1230 case Intrinsic::vp_shl: 1231 case Intrinsic::vp_lshr: 1232 case Intrinsic::vp_ashr: 1233 case Intrinsic::vp_udiv: 1234 case Intrinsic::vp_sdiv: 1235 case Intrinsic::vp_urem: 1236 case Intrinsic::vp_srem: 1237 return Operand == 1; 1238 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1239 // explicit patterns for both LHS and RHS (as 'vr' versions). 1240 case Intrinsic::vp_sub: 1241 case Intrinsic::vp_fsub: 1242 case Intrinsic::vp_fdiv: 1243 return Operand == 0 || Operand == 1; 1244 default: 1245 return false; 1246 } 1247 } 1248 return false; 1249 default: 1250 return false; 1251 } 1252 }; 1253 1254 for (auto OpIdx : enumerate(I->operands())) { 1255 if (!IsSinker(I, OpIdx.index())) 1256 continue; 1257 1258 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1259 // Make sure we are not already sinking this operand 1260 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1261 continue; 1262 1263 // We are looking for a splat that can be sunk. 1264 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1265 m_Undef(), m_ZeroMask()))) 1266 continue; 1267 1268 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1269 // and vector registers 1270 for (Use &U : Op->uses()) { 1271 Instruction *Insn = cast<Instruction>(U.getUser()); 1272 if (!IsSinker(Insn, U.getOperandNo())) 1273 return false; 1274 } 1275 1276 Ops.push_back(&Op->getOperandUse(0)); 1277 Ops.push_back(&OpIdx.value()); 1278 } 1279 return true; 1280 } 1281 1282 bool RISCVTargetLowering::isOffsetFoldingLegal( 1283 const GlobalAddressSDNode *GA) const { 1284 // In order to maximise the opportunity for common subexpression elimination, 1285 // keep a separate ADD node for the global address offset instead of folding 1286 // it in the global address node. Later peephole optimisations may choose to 1287 // fold it back in when profitable. 1288 return false; 1289 } 1290 1291 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1292 bool ForCodeSize) const { 1293 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1294 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1295 return false; 1296 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1297 return false; 1298 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1299 return false; 1300 return Imm.isZero(); 1301 } 1302 1303 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1304 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1305 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1306 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1307 } 1308 1309 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1310 CallingConv::ID CC, 1311 EVT VT) const { 1312 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1313 // We might still end up using a GPR but that will be decided based on ABI. 1314 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1315 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1316 return MVT::f32; 1317 1318 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1319 } 1320 1321 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1322 CallingConv::ID CC, 1323 EVT VT) const { 1324 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1325 // We might still end up using a GPR but that will be decided based on ABI. 1326 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1327 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1328 return 1; 1329 1330 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1331 } 1332 1333 // Changes the condition code and swaps operands if necessary, so the SetCC 1334 // operation matches one of the comparisons supported directly by branches 1335 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1336 // with 1/-1. 1337 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1338 ISD::CondCode &CC, SelectionDAG &DAG) { 1339 // Convert X > -1 to X >= 0. 1340 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1341 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1342 CC = ISD::SETGE; 1343 return; 1344 } 1345 // Convert X < 1 to 0 >= X. 1346 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1347 RHS = LHS; 1348 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1349 CC = ISD::SETGE; 1350 return; 1351 } 1352 1353 switch (CC) { 1354 default: 1355 break; 1356 case ISD::SETGT: 1357 case ISD::SETLE: 1358 case ISD::SETUGT: 1359 case ISD::SETULE: 1360 CC = ISD::getSetCCSwappedOperands(CC); 1361 std::swap(LHS, RHS); 1362 break; 1363 } 1364 } 1365 1366 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1367 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1368 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1369 if (VT.getVectorElementType() == MVT::i1) 1370 KnownSize *= 8; 1371 1372 switch (KnownSize) { 1373 default: 1374 llvm_unreachable("Invalid LMUL."); 1375 case 8: 1376 return RISCVII::VLMUL::LMUL_F8; 1377 case 16: 1378 return RISCVII::VLMUL::LMUL_F4; 1379 case 32: 1380 return RISCVII::VLMUL::LMUL_F2; 1381 case 64: 1382 return RISCVII::VLMUL::LMUL_1; 1383 case 128: 1384 return RISCVII::VLMUL::LMUL_2; 1385 case 256: 1386 return RISCVII::VLMUL::LMUL_4; 1387 case 512: 1388 return RISCVII::VLMUL::LMUL_8; 1389 } 1390 } 1391 1392 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1393 switch (LMul) { 1394 default: 1395 llvm_unreachable("Invalid LMUL."); 1396 case RISCVII::VLMUL::LMUL_F8: 1397 case RISCVII::VLMUL::LMUL_F4: 1398 case RISCVII::VLMUL::LMUL_F2: 1399 case RISCVII::VLMUL::LMUL_1: 1400 return RISCV::VRRegClassID; 1401 case RISCVII::VLMUL::LMUL_2: 1402 return RISCV::VRM2RegClassID; 1403 case RISCVII::VLMUL::LMUL_4: 1404 return RISCV::VRM4RegClassID; 1405 case RISCVII::VLMUL::LMUL_8: 1406 return RISCV::VRM8RegClassID; 1407 } 1408 } 1409 1410 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1411 RISCVII::VLMUL LMUL = getLMUL(VT); 1412 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1413 LMUL == RISCVII::VLMUL::LMUL_F4 || 1414 LMUL == RISCVII::VLMUL::LMUL_F2 || 1415 LMUL == RISCVII::VLMUL::LMUL_1) { 1416 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1417 "Unexpected subreg numbering"); 1418 return RISCV::sub_vrm1_0 + Index; 1419 } 1420 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1421 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1422 "Unexpected subreg numbering"); 1423 return RISCV::sub_vrm2_0 + Index; 1424 } 1425 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1426 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1427 "Unexpected subreg numbering"); 1428 return RISCV::sub_vrm4_0 + Index; 1429 } 1430 llvm_unreachable("Invalid vector type."); 1431 } 1432 1433 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1434 if (VT.getVectorElementType() == MVT::i1) 1435 return RISCV::VRRegClassID; 1436 return getRegClassIDForLMUL(getLMUL(VT)); 1437 } 1438 1439 // Attempt to decompose a subvector insert/extract between VecVT and 1440 // SubVecVT via subregister indices. Returns the subregister index that 1441 // can perform the subvector insert/extract with the given element index, as 1442 // well as the index corresponding to any leftover subvectors that must be 1443 // further inserted/extracted within the register class for SubVecVT. 1444 std::pair<unsigned, unsigned> 1445 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1446 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1447 const RISCVRegisterInfo *TRI) { 1448 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1449 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1450 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1451 "Register classes not ordered"); 1452 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1453 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1454 // Try to compose a subregister index that takes us from the incoming 1455 // LMUL>1 register class down to the outgoing one. At each step we half 1456 // the LMUL: 1457 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1458 // Note that this is not guaranteed to find a subregister index, such as 1459 // when we are extracting from one VR type to another. 1460 unsigned SubRegIdx = RISCV::NoSubRegister; 1461 for (const unsigned RCID : 1462 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1463 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1464 VecVT = VecVT.getHalfNumVectorElementsVT(); 1465 bool IsHi = 1466 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1467 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1468 getSubregIndexByMVT(VecVT, IsHi)); 1469 if (IsHi) 1470 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1471 } 1472 return {SubRegIdx, InsertExtractIdx}; 1473 } 1474 1475 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1476 // stores for those types. 1477 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1478 return !Subtarget.useRVVForFixedLengthVectors() || 1479 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1480 } 1481 1482 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1483 if (ScalarTy->isPointerTy()) 1484 return true; 1485 1486 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1487 ScalarTy->isIntegerTy(32)) 1488 return true; 1489 1490 if (ScalarTy->isIntegerTy(64)) 1491 return Subtarget.hasVInstructionsI64(); 1492 1493 if (ScalarTy->isHalfTy()) 1494 return Subtarget.hasVInstructionsF16(); 1495 if (ScalarTy->isFloatTy()) 1496 return Subtarget.hasVInstructionsF32(); 1497 if (ScalarTy->isDoubleTy()) 1498 return Subtarget.hasVInstructionsF64(); 1499 1500 return false; 1501 } 1502 1503 static SDValue getVLOperand(SDValue Op) { 1504 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1505 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1506 "Unexpected opcode"); 1507 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1508 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1509 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1510 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1511 if (!II) 1512 return SDValue(); 1513 return Op.getOperand(II->VLOperand + 1 + HasChain); 1514 } 1515 1516 static bool useRVVForFixedLengthVectorVT(MVT VT, 1517 const RISCVSubtarget &Subtarget) { 1518 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1519 if (!Subtarget.useRVVForFixedLengthVectors()) 1520 return false; 1521 1522 // We only support a set of vector types with a consistent maximum fixed size 1523 // across all supported vector element types to avoid legalization issues. 1524 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1525 // fixed-length vector type we support is 1024 bytes. 1526 if (VT.getFixedSizeInBits() > 1024 * 8) 1527 return false; 1528 1529 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1530 1531 MVT EltVT = VT.getVectorElementType(); 1532 1533 // Don't use RVV for vectors we cannot scalarize if required. 1534 switch (EltVT.SimpleTy) { 1535 // i1 is supported but has different rules. 1536 default: 1537 return false; 1538 case MVT::i1: 1539 // Masks can only use a single register. 1540 if (VT.getVectorNumElements() > MinVLen) 1541 return false; 1542 MinVLen /= 8; 1543 break; 1544 case MVT::i8: 1545 case MVT::i16: 1546 case MVT::i32: 1547 break; 1548 case MVT::i64: 1549 if (!Subtarget.hasVInstructionsI64()) 1550 return false; 1551 break; 1552 case MVT::f16: 1553 if (!Subtarget.hasVInstructionsF16()) 1554 return false; 1555 break; 1556 case MVT::f32: 1557 if (!Subtarget.hasVInstructionsF32()) 1558 return false; 1559 break; 1560 case MVT::f64: 1561 if (!Subtarget.hasVInstructionsF64()) 1562 return false; 1563 break; 1564 } 1565 1566 // Reject elements larger than ELEN. 1567 if (EltVT.getSizeInBits() > Subtarget.getELEN()) 1568 return false; 1569 1570 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1571 // Don't use RVV for types that don't fit. 1572 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1573 return false; 1574 1575 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1576 // the base fixed length RVV support in place. 1577 if (!VT.isPow2VectorType()) 1578 return false; 1579 1580 return true; 1581 } 1582 1583 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1584 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1585 } 1586 1587 // Return the largest legal scalable vector type that matches VT's element type. 1588 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1589 const RISCVSubtarget &Subtarget) { 1590 // This may be called before legal types are setup. 1591 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1592 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1593 "Expected legal fixed length vector!"); 1594 1595 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1596 unsigned MaxELen = Subtarget.getELEN(); 1597 1598 MVT EltVT = VT.getVectorElementType(); 1599 switch (EltVT.SimpleTy) { 1600 default: 1601 llvm_unreachable("unexpected element type for RVV container"); 1602 case MVT::i1: 1603 case MVT::i8: 1604 case MVT::i16: 1605 case MVT::i32: 1606 case MVT::i64: 1607 case MVT::f16: 1608 case MVT::f32: 1609 case MVT::f64: { 1610 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1611 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1612 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1613 unsigned NumElts = 1614 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1615 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1616 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1617 return MVT::getScalableVectorVT(EltVT, NumElts); 1618 } 1619 } 1620 } 1621 1622 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1623 const RISCVSubtarget &Subtarget) { 1624 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1625 Subtarget); 1626 } 1627 1628 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1629 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1630 } 1631 1632 // Grow V to consume an entire RVV register. 1633 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1634 const RISCVSubtarget &Subtarget) { 1635 assert(VT.isScalableVector() && 1636 "Expected to convert into a scalable vector!"); 1637 assert(V.getValueType().isFixedLengthVector() && 1638 "Expected a fixed length vector operand!"); 1639 SDLoc DL(V); 1640 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1641 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1642 } 1643 1644 // Shrink V so it's just big enough to maintain a VT's worth of data. 1645 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1646 const RISCVSubtarget &Subtarget) { 1647 assert(VT.isFixedLengthVector() && 1648 "Expected to convert into a fixed length vector!"); 1649 assert(V.getValueType().isScalableVector() && 1650 "Expected a scalable vector operand!"); 1651 SDLoc DL(V); 1652 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1653 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1654 } 1655 1656 /// Return the type of the mask type suitable for masking the provided 1657 /// vector type. This is simply an i1 element type vector of the same 1658 /// (possibly scalable) length. 1659 static MVT getMaskTypeFor(EVT VecVT) { 1660 assert(VecVT.isVector()); 1661 ElementCount EC = VecVT.getVectorElementCount(); 1662 return MVT::getVectorVT(MVT::i1, EC); 1663 } 1664 1665 /// Creates an all ones mask suitable for masking a vector of type VecTy with 1666 /// vector length VL. . 1667 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL, 1668 SelectionDAG &DAG) { 1669 MVT MaskVT = getMaskTypeFor(VecVT); 1670 return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1671 } 1672 1673 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1674 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1675 // the vector type that it is contained in. 1676 static std::pair<SDValue, SDValue> 1677 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1678 const RISCVSubtarget &Subtarget) { 1679 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1680 MVT XLenVT = Subtarget.getXLenVT(); 1681 SDValue VL = VecVT.isFixedLengthVector() 1682 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1683 : DAG.getRegister(RISCV::X0, XLenVT); 1684 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 1685 return {Mask, VL}; 1686 } 1687 1688 // As above but assuming the given type is a scalable vector type. 1689 static std::pair<SDValue, SDValue> 1690 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1691 const RISCVSubtarget &Subtarget) { 1692 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1693 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1694 } 1695 1696 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1697 // of either is (currently) supported. This can get us into an infinite loop 1698 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1699 // as a ..., etc. 1700 // Until either (or both) of these can reliably lower any node, reporting that 1701 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1702 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1703 // which is not desirable. 1704 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1705 EVT VT, unsigned DefinedValues) const { 1706 return false; 1707 } 1708 1709 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1710 const RISCVSubtarget &Subtarget) { 1711 // RISCV FP-to-int conversions saturate to the destination register size, but 1712 // don't produce 0 for nan. We can use a conversion instruction and fix the 1713 // nan case with a compare and a select. 1714 SDValue Src = Op.getOperand(0); 1715 1716 EVT DstVT = Op.getValueType(); 1717 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1718 1719 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1720 unsigned Opc; 1721 if (SatVT == DstVT) 1722 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1723 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1724 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1725 else 1726 return SDValue(); 1727 // FIXME: Support other SatVTs by clamping before or after the conversion. 1728 1729 SDLoc DL(Op); 1730 SDValue FpToInt = DAG.getNode( 1731 Opc, DL, DstVT, Src, 1732 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1733 1734 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1735 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1736 } 1737 1738 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1739 // and back. Taking care to avoid converting values that are nan or already 1740 // correct. 1741 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1742 // have FRM dependencies modeled yet. 1743 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1744 MVT VT = Op.getSimpleValueType(); 1745 assert(VT.isVector() && "Unexpected type"); 1746 1747 SDLoc DL(Op); 1748 1749 // Freeze the source since we are increasing the number of uses. 1750 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1751 1752 // Truncate to integer and convert back to FP. 1753 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1754 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1755 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1756 1757 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1758 1759 if (Op.getOpcode() == ISD::FCEIL) { 1760 // If the truncated value is the greater than or equal to the original 1761 // value, we've computed the ceil. Otherwise, we went the wrong way and 1762 // need to increase by 1. 1763 // FIXME: This should use a masked operation. Handle here or in isel? 1764 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1765 DAG.getConstantFP(1.0, DL, VT)); 1766 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1767 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1768 } else if (Op.getOpcode() == ISD::FFLOOR) { 1769 // If the truncated value is the less than or equal to the original value, 1770 // we've computed the floor. Otherwise, we went the wrong way and need to 1771 // decrease by 1. 1772 // FIXME: This should use a masked operation. Handle here or in isel? 1773 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1774 DAG.getConstantFP(1.0, DL, VT)); 1775 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1776 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1777 } 1778 1779 // Restore the original sign so that -0.0 is preserved. 1780 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1781 1782 // Determine the largest integer that can be represented exactly. This and 1783 // values larger than it don't have any fractional bits so don't need to 1784 // be converted. 1785 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1786 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1787 APFloat MaxVal = APFloat(FltSem); 1788 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1789 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1790 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1791 1792 // If abs(Src) was larger than MaxVal or nan, keep it. 1793 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1794 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1795 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1796 } 1797 1798 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1799 // This mode isn't supported in vector hardware on RISCV. But as long as we 1800 // aren't compiling with trapping math, we can emulate this with 1801 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1802 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1803 // dependencies modeled yet. 1804 // FIXME: Use masked operations to avoid final merge. 1805 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1806 MVT VT = Op.getSimpleValueType(); 1807 assert(VT.isVector() && "Unexpected type"); 1808 1809 SDLoc DL(Op); 1810 1811 // Freeze the source since we are increasing the number of uses. 1812 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1813 1814 // We do the conversion on the absolute value and fix the sign at the end. 1815 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1816 1817 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1818 bool Ignored; 1819 APFloat Point5Pred = APFloat(0.5f); 1820 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1821 Point5Pred.next(/*nextDown*/ true); 1822 1823 // Add the adjustment. 1824 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1825 DAG.getConstantFP(Point5Pred, DL, VT)); 1826 1827 // Truncate to integer and convert back to fp. 1828 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1829 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1830 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1831 1832 // Restore the original sign. 1833 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1834 1835 // Determine the largest integer that can be represented exactly. This and 1836 // values larger than it don't have any fractional bits so don't need to 1837 // be converted. 1838 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1839 APFloat MaxVal = APFloat(FltSem); 1840 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1841 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1842 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1843 1844 // If abs(Src) was larger than MaxVal or nan, keep it. 1845 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1846 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1847 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1848 } 1849 1850 struct VIDSequence { 1851 int64_t StepNumerator; 1852 unsigned StepDenominator; 1853 int64_t Addend; 1854 }; 1855 1856 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1857 // to the (non-zero) step S and start value X. This can be then lowered as the 1858 // RVV sequence (VID * S) + X, for example. 1859 // The step S is represented as an integer numerator divided by a positive 1860 // denominator. Note that the implementation currently only identifies 1861 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1862 // cannot detect 2/3, for example. 1863 // Note that this method will also match potentially unappealing index 1864 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1865 // determine whether this is worth generating code for. 1866 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1867 unsigned NumElts = Op.getNumOperands(); 1868 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1869 if (!Op.getValueType().isInteger()) 1870 return None; 1871 1872 Optional<unsigned> SeqStepDenom; 1873 Optional<int64_t> SeqStepNum, SeqAddend; 1874 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1875 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1876 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1877 // Assume undef elements match the sequence; we just have to be careful 1878 // when interpolating across them. 1879 if (Op.getOperand(Idx).isUndef()) 1880 continue; 1881 // The BUILD_VECTOR must be all constants. 1882 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1883 return None; 1884 1885 uint64_t Val = Op.getConstantOperandVal(Idx) & 1886 maskTrailingOnes<uint64_t>(EltSizeInBits); 1887 1888 if (PrevElt) { 1889 // Calculate the step since the last non-undef element, and ensure 1890 // it's consistent across the entire sequence. 1891 unsigned IdxDiff = Idx - PrevElt->second; 1892 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1893 1894 // A zero-value value difference means that we're somewhere in the middle 1895 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1896 // step change before evaluating the sequence. 1897 if (ValDiff == 0) 1898 continue; 1899 1900 int64_t Remainder = ValDiff % IdxDiff; 1901 // Normalize the step if it's greater than 1. 1902 if (Remainder != ValDiff) { 1903 // The difference must cleanly divide the element span. 1904 if (Remainder != 0) 1905 return None; 1906 ValDiff /= IdxDiff; 1907 IdxDiff = 1; 1908 } 1909 1910 if (!SeqStepNum) 1911 SeqStepNum = ValDiff; 1912 else if (ValDiff != SeqStepNum) 1913 return None; 1914 1915 if (!SeqStepDenom) 1916 SeqStepDenom = IdxDiff; 1917 else if (IdxDiff != *SeqStepDenom) 1918 return None; 1919 } 1920 1921 // Record this non-undef element for later. 1922 if (!PrevElt || PrevElt->first != Val) 1923 PrevElt = std::make_pair(Val, Idx); 1924 } 1925 1926 // We need to have logged a step for this to count as a legal index sequence. 1927 if (!SeqStepNum || !SeqStepDenom) 1928 return None; 1929 1930 // Loop back through the sequence and validate elements we might have skipped 1931 // while waiting for a valid step. While doing this, log any sequence addend. 1932 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1933 if (Op.getOperand(Idx).isUndef()) 1934 continue; 1935 uint64_t Val = Op.getConstantOperandVal(Idx) & 1936 maskTrailingOnes<uint64_t>(EltSizeInBits); 1937 uint64_t ExpectedVal = 1938 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1939 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1940 if (!SeqAddend) 1941 SeqAddend = Addend; 1942 else if (Addend != SeqAddend) 1943 return None; 1944 } 1945 1946 assert(SeqAddend && "Must have an addend if we have a step"); 1947 1948 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1949 } 1950 1951 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1952 // and lower it as a VRGATHER_VX_VL from the source vector. 1953 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 1954 SelectionDAG &DAG, 1955 const RISCVSubtarget &Subtarget) { 1956 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1957 return SDValue(); 1958 SDValue Vec = SplatVal.getOperand(0); 1959 // Only perform this optimization on vectors of the same size for simplicity. 1960 // Don't perform this optimization for i1 vectors. 1961 // FIXME: Support i1 vectors, maybe by promoting to i8? 1962 if (Vec.getValueType() != VT || VT.getVectorElementType() == MVT::i1) 1963 return SDValue(); 1964 SDValue Idx = SplatVal.getOperand(1); 1965 // The index must be a legal type. 1966 if (Idx.getValueType() != Subtarget.getXLenVT()) 1967 return SDValue(); 1968 1969 MVT ContainerVT = VT; 1970 if (VT.isFixedLengthVector()) { 1971 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1972 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 1973 } 1974 1975 SDValue Mask, VL; 1976 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1977 1978 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 1979 Idx, Mask, DAG.getUNDEF(ContainerVT), VL); 1980 1981 if (!VT.isFixedLengthVector()) 1982 return Gather; 1983 1984 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 1985 } 1986 1987 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1988 const RISCVSubtarget &Subtarget) { 1989 MVT VT = Op.getSimpleValueType(); 1990 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1991 1992 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1993 1994 SDLoc DL(Op); 1995 SDValue Mask, VL; 1996 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1997 1998 MVT XLenVT = Subtarget.getXLenVT(); 1999 unsigned NumElts = Op.getNumOperands(); 2000 2001 if (VT.getVectorElementType() == MVT::i1) { 2002 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 2003 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 2004 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 2005 } 2006 2007 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 2008 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 2009 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 2010 } 2011 2012 // Lower constant mask BUILD_VECTORs via an integer vector type, in 2013 // scalar integer chunks whose bit-width depends on the number of mask 2014 // bits and XLEN. 2015 // First, determine the most appropriate scalar integer type to use. This 2016 // is at most XLenVT, but may be shrunk to a smaller vector element type 2017 // according to the size of the final vector - use i8 chunks rather than 2018 // XLenVT if we're producing a v8i1. This results in more consistent 2019 // codegen across RV32 and RV64. 2020 unsigned NumViaIntegerBits = 2021 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 2022 NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN()); 2023 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 2024 // If we have to use more than one INSERT_VECTOR_ELT then this 2025 // optimization is likely to increase code size; avoid peforming it in 2026 // such a case. We can use a load from a constant pool in this case. 2027 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 2028 return SDValue(); 2029 // Now we can create our integer vector type. Note that it may be larger 2030 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2031 MVT IntegerViaVecVT = 2032 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2033 divideCeil(NumElts, NumViaIntegerBits)); 2034 2035 uint64_t Bits = 0; 2036 unsigned BitPos = 0, IntegerEltIdx = 0; 2037 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2038 2039 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2040 // Once we accumulate enough bits to fill our scalar type, insert into 2041 // our vector and clear our accumulated data. 2042 if (I != 0 && I % NumViaIntegerBits == 0) { 2043 if (NumViaIntegerBits <= 32) 2044 Bits = SignExtend64<32>(Bits); 2045 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2046 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2047 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2048 Bits = 0; 2049 BitPos = 0; 2050 IntegerEltIdx++; 2051 } 2052 SDValue V = Op.getOperand(I); 2053 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2054 Bits |= ((uint64_t)BitValue << BitPos); 2055 } 2056 2057 // Insert the (remaining) scalar value into position in our integer 2058 // vector type. 2059 if (NumViaIntegerBits <= 32) 2060 Bits = SignExtend64<32>(Bits); 2061 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2062 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2063 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2064 2065 if (NumElts < NumViaIntegerBits) { 2066 // If we're producing a smaller vector than our minimum legal integer 2067 // type, bitcast to the equivalent (known-legal) mask type, and extract 2068 // our final mask. 2069 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2070 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2071 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2072 DAG.getConstant(0, DL, XLenVT)); 2073 } else { 2074 // Else we must have produced an integer type with the same size as the 2075 // mask type; bitcast for the final result. 2076 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2077 Vec = DAG.getBitcast(VT, Vec); 2078 } 2079 2080 return Vec; 2081 } 2082 2083 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2084 // vector type, we have a legal equivalently-sized i8 type, so we can use 2085 // that. 2086 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2087 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2088 2089 SDValue WideVec; 2090 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2091 // For a splat, perform a scalar truncate before creating the wider 2092 // vector. 2093 assert(Splat.getValueType() == XLenVT && 2094 "Unexpected type for i1 splat value"); 2095 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2096 DAG.getConstant(1, DL, XLenVT)); 2097 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2098 } else { 2099 SmallVector<SDValue, 8> Ops(Op->op_values()); 2100 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2101 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2102 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2103 } 2104 2105 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2106 } 2107 2108 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2109 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2110 return Gather; 2111 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2112 : RISCVISD::VMV_V_X_VL; 2113 Splat = 2114 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2115 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2116 } 2117 2118 // Try and match index sequences, which we can lower to the vid instruction 2119 // with optional modifications. An all-undef vector is matched by 2120 // getSplatValue, above. 2121 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2122 int64_t StepNumerator = SimpleVID->StepNumerator; 2123 unsigned StepDenominator = SimpleVID->StepDenominator; 2124 int64_t Addend = SimpleVID->Addend; 2125 2126 assert(StepNumerator != 0 && "Invalid step"); 2127 bool Negate = false; 2128 int64_t SplatStepVal = StepNumerator; 2129 unsigned StepOpcode = ISD::MUL; 2130 if (StepNumerator != 1) { 2131 if (isPowerOf2_64(std::abs(StepNumerator))) { 2132 Negate = StepNumerator < 0; 2133 StepOpcode = ISD::SHL; 2134 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2135 } 2136 } 2137 2138 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2139 // threshold since it's the immediate value many RVV instructions accept. 2140 // There is no vmul.vi instruction so ensure multiply constant can fit in 2141 // a single addi instruction. 2142 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2143 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2144 isPowerOf2_32(StepDenominator) && 2145 (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) { 2146 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2147 // Convert right out of the scalable type so we can use standard ISD 2148 // nodes for the rest of the computation. If we used scalable types with 2149 // these, we'd lose the fixed-length vector info and generate worse 2150 // vsetvli code. 2151 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2152 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2153 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2154 SDValue SplatStep = DAG.getSplatBuildVector( 2155 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2156 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2157 } 2158 if (StepDenominator != 1) { 2159 SDValue SplatStep = DAG.getSplatBuildVector( 2160 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2161 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2162 } 2163 if (Addend != 0 || Negate) { 2164 SDValue SplatAddend = DAG.getSplatBuildVector( 2165 VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2166 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2167 } 2168 return VID; 2169 } 2170 } 2171 2172 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2173 // when re-interpreted as a vector with a larger element type. For example, 2174 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2175 // could be instead splat as 2176 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2177 // TODO: This optimization could also work on non-constant splats, but it 2178 // would require bit-manipulation instructions to construct the splat value. 2179 SmallVector<SDValue> Sequence; 2180 unsigned EltBitSize = VT.getScalarSizeInBits(); 2181 const auto *BV = cast<BuildVectorSDNode>(Op); 2182 if (VT.isInteger() && EltBitSize < 64 && 2183 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2184 BV->getRepeatedSequence(Sequence) && 2185 (Sequence.size() * EltBitSize) <= 64) { 2186 unsigned SeqLen = Sequence.size(); 2187 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2188 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2189 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2190 ViaIntVT == MVT::i64) && 2191 "Unexpected sequence type"); 2192 2193 unsigned EltIdx = 0; 2194 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2195 uint64_t SplatValue = 0; 2196 // Construct the amalgamated value which can be splatted as this larger 2197 // vector type. 2198 for (const auto &SeqV : Sequence) { 2199 if (!SeqV.isUndef()) 2200 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2201 << (EltIdx * EltBitSize)); 2202 EltIdx++; 2203 } 2204 2205 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2206 // achieve better constant materializion. 2207 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2208 SplatValue = SignExtend64<32>(SplatValue); 2209 2210 // Since we can't introduce illegal i64 types at this stage, we can only 2211 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2212 // way we can use RVV instructions to splat. 2213 assert((ViaIntVT.bitsLE(XLenVT) || 2214 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2215 "Unexpected bitcast sequence"); 2216 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2217 SDValue ViaVL = 2218 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2219 MVT ViaContainerVT = 2220 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2221 SDValue Splat = 2222 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2223 DAG.getUNDEF(ViaContainerVT), 2224 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2225 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2226 return DAG.getBitcast(VT, Splat); 2227 } 2228 } 2229 2230 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2231 // which constitute a large proportion of the elements. In such cases we can 2232 // splat a vector with the dominant element and make up the shortfall with 2233 // INSERT_VECTOR_ELTs. 2234 // Note that this includes vectors of 2 elements by association. The 2235 // upper-most element is the "dominant" one, allowing us to use a splat to 2236 // "insert" the upper element, and an insert of the lower element at position 2237 // 0, which improves codegen. 2238 SDValue DominantValue; 2239 unsigned MostCommonCount = 0; 2240 DenseMap<SDValue, unsigned> ValueCounts; 2241 unsigned NumUndefElts = 2242 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2243 2244 // Track the number of scalar loads we know we'd be inserting, estimated as 2245 // any non-zero floating-point constant. Other kinds of element are either 2246 // already in registers or are materialized on demand. The threshold at which 2247 // a vector load is more desirable than several scalar materializion and 2248 // vector-insertion instructions is not known. 2249 unsigned NumScalarLoads = 0; 2250 2251 for (SDValue V : Op->op_values()) { 2252 if (V.isUndef()) 2253 continue; 2254 2255 ValueCounts.insert(std::make_pair(V, 0)); 2256 unsigned &Count = ValueCounts[V]; 2257 2258 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2259 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2260 2261 // Is this value dominant? In case of a tie, prefer the highest element as 2262 // it's cheaper to insert near the beginning of a vector than it is at the 2263 // end. 2264 if (++Count >= MostCommonCount) { 2265 DominantValue = V; 2266 MostCommonCount = Count; 2267 } 2268 } 2269 2270 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2271 unsigned NumDefElts = NumElts - NumUndefElts; 2272 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2273 2274 // Don't perform this optimization when optimizing for size, since 2275 // materializing elements and inserting them tends to cause code bloat. 2276 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2277 ((MostCommonCount > DominantValueCountThreshold) || 2278 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2279 // Start by splatting the most common element. 2280 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2281 2282 DenseSet<SDValue> Processed{DominantValue}; 2283 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2284 for (const auto &OpIdx : enumerate(Op->ops())) { 2285 const SDValue &V = OpIdx.value(); 2286 if (V.isUndef() || !Processed.insert(V).second) 2287 continue; 2288 if (ValueCounts[V] == 1) { 2289 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2290 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2291 } else { 2292 // Blend in all instances of this value using a VSELECT, using a 2293 // mask where each bit signals whether that element is the one 2294 // we're after. 2295 SmallVector<SDValue> Ops; 2296 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2297 return DAG.getConstant(V == V1, DL, XLenVT); 2298 }); 2299 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2300 DAG.getBuildVector(SelMaskTy, DL, Ops), 2301 DAG.getSplatBuildVector(VT, DL, V), Vec); 2302 } 2303 } 2304 2305 return Vec; 2306 } 2307 2308 return SDValue(); 2309 } 2310 2311 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2312 SDValue Lo, SDValue Hi, SDValue VL, 2313 SelectionDAG &DAG) { 2314 if (!Passthru) 2315 Passthru = DAG.getUNDEF(VT); 2316 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2317 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2318 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2319 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2320 // node in order to try and match RVV vector/scalar instructions. 2321 if ((LoC >> 31) == HiC) 2322 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2323 2324 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2325 // vmv.v.x whose EEW = 32 to lower it. 2326 auto *Const = dyn_cast<ConstantSDNode>(VL); 2327 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2328 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2329 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2330 // access the subtarget here now. 2331 auto InterVec = DAG.getNode( 2332 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2333 DAG.getRegister(RISCV::X0, MVT::i32)); 2334 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2335 } 2336 } 2337 2338 // Fall back to a stack store and stride x0 vector load. 2339 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2340 Hi, VL); 2341 } 2342 2343 // Called by type legalization to handle splat of i64 on RV32. 2344 // FIXME: We can optimize this when the type has sign or zero bits in one 2345 // of the halves. 2346 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2347 SDValue Scalar, SDValue VL, 2348 SelectionDAG &DAG) { 2349 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2350 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2351 DAG.getConstant(0, DL, MVT::i32)); 2352 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2353 DAG.getConstant(1, DL, MVT::i32)); 2354 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2355 } 2356 2357 // This function lowers a splat of a scalar operand Splat with the vector 2358 // length VL. It ensures the final sequence is type legal, which is useful when 2359 // lowering a splat after type legalization. 2360 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2361 MVT VT, SDLoc DL, SelectionDAG &DAG, 2362 const RISCVSubtarget &Subtarget) { 2363 bool HasPassthru = Passthru && !Passthru.isUndef(); 2364 if (!HasPassthru && !Passthru) 2365 Passthru = DAG.getUNDEF(VT); 2366 if (VT.isFloatingPoint()) { 2367 // If VL is 1, we could use vfmv.s.f. 2368 if (isOneConstant(VL)) 2369 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2370 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2371 } 2372 2373 MVT XLenVT = Subtarget.getXLenVT(); 2374 2375 // Simplest case is that the operand needs to be promoted to XLenVT. 2376 if (Scalar.getValueType().bitsLE(XLenVT)) { 2377 // If the operand is a constant, sign extend to increase our chances 2378 // of being able to use a .vi instruction. ANY_EXTEND would become a 2379 // a zero extend and the simm5 check in isel would fail. 2380 // FIXME: Should we ignore the upper bits in isel instead? 2381 unsigned ExtOpc = 2382 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2383 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2384 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2385 // If VL is 1 and the scalar value won't benefit from immediate, we could 2386 // use vmv.s.x. 2387 if (isOneConstant(VL) && 2388 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2389 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2390 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2391 } 2392 2393 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2394 "Unexpected scalar for splat lowering!"); 2395 2396 if (isOneConstant(VL) && isNullConstant(Scalar)) 2397 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2398 DAG.getConstant(0, DL, XLenVT), VL); 2399 2400 // Otherwise use the more complicated splatting algorithm. 2401 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2402 } 2403 2404 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2405 const RISCVSubtarget &Subtarget) { 2406 // We need to be able to widen elements to the next larger integer type. 2407 if (VT.getScalarSizeInBits() >= Subtarget.getELEN()) 2408 return false; 2409 2410 int Size = Mask.size(); 2411 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2412 2413 int Srcs[] = {-1, -1}; 2414 for (int i = 0; i != Size; ++i) { 2415 // Ignore undef elements. 2416 if (Mask[i] < 0) 2417 continue; 2418 2419 // Is this an even or odd element. 2420 int Pol = i % 2; 2421 2422 // Ensure we consistently use the same source for this element polarity. 2423 int Src = Mask[i] / Size; 2424 if (Srcs[Pol] < 0) 2425 Srcs[Pol] = Src; 2426 if (Srcs[Pol] != Src) 2427 return false; 2428 2429 // Make sure the element within the source is appropriate for this element 2430 // in the destination. 2431 int Elt = Mask[i] % Size; 2432 if (Elt != i / 2) 2433 return false; 2434 } 2435 2436 // We need to find a source for each polarity and they can't be the same. 2437 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2438 return false; 2439 2440 // Swap the sources if the second source was in the even polarity. 2441 SwapSources = Srcs[0] > Srcs[1]; 2442 2443 return true; 2444 } 2445 2446 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2447 /// and then extract the original number of elements from the rotated result. 2448 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2449 /// returned rotation amount is for a rotate right, where elements move from 2450 /// higher elements to lower elements. \p LoSrc indicates the first source 2451 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2452 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2453 /// 0 or 1 if a rotation is found. 2454 /// 2455 /// NOTE: We talk about rotate to the right which matches how bit shift and 2456 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2457 /// and the table below write vectors with the lowest elements on the left. 2458 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2459 int Size = Mask.size(); 2460 2461 // We need to detect various ways of spelling a rotation: 2462 // [11, 12, 13, 14, 15, 0, 1, 2] 2463 // [-1, 12, 13, 14, -1, -1, 1, -1] 2464 // [-1, -1, -1, -1, -1, -1, 1, 2] 2465 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2466 // [-1, 4, 5, 6, -1, -1, 9, -1] 2467 // [-1, 4, 5, 6, -1, -1, -1, -1] 2468 int Rotation = 0; 2469 LoSrc = -1; 2470 HiSrc = -1; 2471 for (int i = 0; i != Size; ++i) { 2472 int M = Mask[i]; 2473 if (M < 0) 2474 continue; 2475 2476 // Determine where a rotate vector would have started. 2477 int StartIdx = i - (M % Size); 2478 // The identity rotation isn't interesting, stop. 2479 if (StartIdx == 0) 2480 return -1; 2481 2482 // If we found the tail of a vector the rotation must be the missing 2483 // front. If we found the head of a vector, it must be how much of the 2484 // head. 2485 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2486 2487 if (Rotation == 0) 2488 Rotation = CandidateRotation; 2489 else if (Rotation != CandidateRotation) 2490 // The rotations don't match, so we can't match this mask. 2491 return -1; 2492 2493 // Compute which value this mask is pointing at. 2494 int MaskSrc = M < Size ? 0 : 1; 2495 2496 // Compute which of the two target values this index should be assigned to. 2497 // This reflects whether the high elements are remaining or the low elemnts 2498 // are remaining. 2499 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2500 2501 // Either set up this value if we've not encountered it before, or check 2502 // that it remains consistent. 2503 if (TargetSrc < 0) 2504 TargetSrc = MaskSrc; 2505 else if (TargetSrc != MaskSrc) 2506 // This may be a rotation, but it pulls from the inputs in some 2507 // unsupported interleaving. 2508 return -1; 2509 } 2510 2511 // Check that we successfully analyzed the mask, and normalize the results. 2512 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2513 assert((LoSrc >= 0 || HiSrc >= 0) && 2514 "Failed to find a rotated input vector!"); 2515 2516 return Rotation; 2517 } 2518 2519 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2520 const RISCVSubtarget &Subtarget) { 2521 SDValue V1 = Op.getOperand(0); 2522 SDValue V2 = Op.getOperand(1); 2523 SDLoc DL(Op); 2524 MVT XLenVT = Subtarget.getXLenVT(); 2525 MVT VT = Op.getSimpleValueType(); 2526 unsigned NumElts = VT.getVectorNumElements(); 2527 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2528 2529 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2530 2531 SDValue TrueMask, VL; 2532 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2533 2534 if (SVN->isSplat()) { 2535 const int Lane = SVN->getSplatIndex(); 2536 if (Lane >= 0) { 2537 MVT SVT = VT.getVectorElementType(); 2538 2539 // Turn splatted vector load into a strided load with an X0 stride. 2540 SDValue V = V1; 2541 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2542 // with undef. 2543 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2544 int Offset = Lane; 2545 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2546 int OpElements = 2547 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2548 V = V.getOperand(Offset / OpElements); 2549 Offset %= OpElements; 2550 } 2551 2552 // We need to ensure the load isn't atomic or volatile. 2553 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2554 auto *Ld = cast<LoadSDNode>(V); 2555 Offset *= SVT.getStoreSize(); 2556 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2557 TypeSize::Fixed(Offset), DL); 2558 2559 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2560 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2561 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2562 SDValue IntID = 2563 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2564 SDValue Ops[] = {Ld->getChain(), 2565 IntID, 2566 DAG.getUNDEF(ContainerVT), 2567 NewAddr, 2568 DAG.getRegister(RISCV::X0, XLenVT), 2569 VL}; 2570 SDValue NewLoad = DAG.getMemIntrinsicNode( 2571 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2572 DAG.getMachineFunction().getMachineMemOperand( 2573 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2574 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2575 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2576 } 2577 2578 // Otherwise use a scalar load and splat. This will give the best 2579 // opportunity to fold a splat into the operation. ISel can turn it into 2580 // the x0 strided load if we aren't able to fold away the select. 2581 if (SVT.isFloatingPoint()) 2582 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2583 Ld->getPointerInfo().getWithOffset(Offset), 2584 Ld->getOriginalAlign(), 2585 Ld->getMemOperand()->getFlags()); 2586 else 2587 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2588 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2589 Ld->getOriginalAlign(), 2590 Ld->getMemOperand()->getFlags()); 2591 DAG.makeEquivalentMemoryOrdering(Ld, V); 2592 2593 unsigned Opc = 2594 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2595 SDValue Splat = 2596 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2597 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2598 } 2599 2600 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2601 assert(Lane < (int)NumElts && "Unexpected lane!"); 2602 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, 2603 V1, DAG.getConstant(Lane, DL, XLenVT), 2604 TrueMask, DAG.getUNDEF(ContainerVT), VL); 2605 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2606 } 2607 } 2608 2609 ArrayRef<int> Mask = SVN->getMask(); 2610 2611 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2612 // be undef which can be handled with a single SLIDEDOWN/UP. 2613 int LoSrc, HiSrc; 2614 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2615 if (Rotation > 0) { 2616 SDValue LoV, HiV; 2617 if (LoSrc >= 0) { 2618 LoV = LoSrc == 0 ? V1 : V2; 2619 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2620 } 2621 if (HiSrc >= 0) { 2622 HiV = HiSrc == 0 ? V1 : V2; 2623 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2624 } 2625 2626 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2627 // to slide LoV up by (NumElts - Rotation). 2628 unsigned InvRotate = NumElts - Rotation; 2629 2630 SDValue Res = DAG.getUNDEF(ContainerVT); 2631 if (HiV) { 2632 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2633 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2634 // causes multiple vsetvlis in some test cases such as lowering 2635 // reduce.mul 2636 SDValue DownVL = VL; 2637 if (LoV) 2638 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2639 Res = 2640 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2641 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2642 } 2643 if (LoV) 2644 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2645 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2646 2647 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2648 } 2649 2650 // Detect an interleave shuffle and lower to 2651 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2652 bool SwapSources; 2653 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2654 // Swap sources if needed. 2655 if (SwapSources) 2656 std::swap(V1, V2); 2657 2658 // Extract the lower half of the vectors. 2659 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2660 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2661 DAG.getConstant(0, DL, XLenVT)); 2662 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2663 DAG.getConstant(0, DL, XLenVT)); 2664 2665 // Double the element width and halve the number of elements in an int type. 2666 unsigned EltBits = VT.getScalarSizeInBits(); 2667 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2668 MVT WideIntVT = 2669 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2670 // Convert this to a scalable vector. We need to base this on the 2671 // destination size to ensure there's always a type with a smaller LMUL. 2672 MVT WideIntContainerVT = 2673 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2674 2675 // Convert sources to scalable vectors with the same element count as the 2676 // larger type. 2677 MVT HalfContainerVT = MVT::getVectorVT( 2678 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2679 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2680 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2681 2682 // Cast sources to integer. 2683 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2684 MVT IntHalfVT = 2685 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2686 V1 = DAG.getBitcast(IntHalfVT, V1); 2687 V2 = DAG.getBitcast(IntHalfVT, V2); 2688 2689 // Freeze V2 since we use it twice and we need to be sure that the add and 2690 // multiply see the same value. 2691 V2 = DAG.getFreeze(V2); 2692 2693 // Recreate TrueMask using the widened type's element count. 2694 TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG); 2695 2696 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2697 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2698 V2, TrueMask, VL); 2699 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2700 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2701 DAG.getUNDEF(IntHalfVT), 2702 DAG.getAllOnesConstant(DL, XLenVT)); 2703 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2704 V2, Multiplier, TrueMask, VL); 2705 // Add the new copies to our previous addition giving us 2^eltbits copies of 2706 // V2. This is equivalent to shifting V2 left by eltbits. This should 2707 // combine with the vwmulu.vv above to form vwmaccu.vv. 2708 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2709 TrueMask, VL); 2710 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2711 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2712 // vector VT. 2713 ContainerVT = 2714 MVT::getVectorVT(VT.getVectorElementType(), 2715 WideIntContainerVT.getVectorElementCount() * 2); 2716 Add = DAG.getBitcast(ContainerVT, Add); 2717 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2718 } 2719 2720 // Detect shuffles which can be re-expressed as vector selects; these are 2721 // shuffles in which each element in the destination is taken from an element 2722 // at the corresponding index in either source vectors. 2723 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2724 int MaskIndex = MaskIdx.value(); 2725 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2726 }); 2727 2728 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2729 2730 SmallVector<SDValue> MaskVals; 2731 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2732 // merged with a second vrgather. 2733 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2734 2735 // By default we preserve the original operand order, and use a mask to 2736 // select LHS as true and RHS as false. However, since RVV vector selects may 2737 // feature splats but only on the LHS, we may choose to invert our mask and 2738 // instead select between RHS and LHS. 2739 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2740 bool InvertMask = IsSelect == SwapOps; 2741 2742 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2743 // half. 2744 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2745 2746 // Now construct the mask that will be used by the vselect or blended 2747 // vrgather operation. For vrgathers, construct the appropriate indices into 2748 // each vector. 2749 for (int MaskIndex : Mask) { 2750 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2751 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2752 if (!IsSelect) { 2753 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2754 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2755 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2756 : DAG.getUNDEF(XLenVT)); 2757 GatherIndicesRHS.push_back( 2758 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2759 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2760 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2761 ++LHSIndexCounts[MaskIndex]; 2762 if (!IsLHSOrUndefIndex) 2763 ++RHSIndexCounts[MaskIndex - NumElts]; 2764 } 2765 } 2766 2767 if (SwapOps) { 2768 std::swap(V1, V2); 2769 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2770 } 2771 2772 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2773 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2774 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2775 2776 if (IsSelect) 2777 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2778 2779 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2780 // On such a large vector we're unable to use i8 as the index type. 2781 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2782 // may involve vector splitting if we're already at LMUL=8, or our 2783 // user-supplied maximum fixed-length LMUL. 2784 return SDValue(); 2785 } 2786 2787 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2788 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2789 MVT IndexVT = VT.changeTypeToInteger(); 2790 // Since we can't introduce illegal index types at this stage, use i16 and 2791 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2792 // than XLenVT. 2793 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2794 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2795 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2796 } 2797 2798 MVT IndexContainerVT = 2799 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2800 2801 SDValue Gather; 2802 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2803 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2804 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2805 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2806 Subtarget); 2807 } else { 2808 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2809 // If only one index is used, we can use a "splat" vrgather. 2810 // TODO: We can splat the most-common index and fix-up any stragglers, if 2811 // that's beneficial. 2812 if (LHSIndexCounts.size() == 1) { 2813 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2814 Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2815 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, 2816 DAG.getUNDEF(ContainerVT), VL); 2817 } else { 2818 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2819 LHSIndices = 2820 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2821 2822 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2823 TrueMask, DAG.getUNDEF(ContainerVT), VL); 2824 } 2825 } 2826 2827 // If a second vector operand is used by this shuffle, blend it in with an 2828 // additional vrgather. 2829 if (!V2.isUndef()) { 2830 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2831 2832 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2833 SelectMask = 2834 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2835 2836 // If only one index is used, we can use a "splat" vrgather. 2837 // TODO: We can splat the most-common index and fix-up any stragglers, if 2838 // that's beneficial. 2839 if (RHSIndexCounts.size() == 1) { 2840 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2841 Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2842 DAG.getConstant(SplatIndex, DL, XLenVT), SelectMask, 2843 Gather, VL); 2844 } else { 2845 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2846 RHSIndices = 2847 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2848 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, 2849 SelectMask, Gather, VL); 2850 } 2851 } 2852 2853 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2854 } 2855 2856 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2857 // Support splats for any type. These should type legalize well. 2858 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2859 return true; 2860 2861 // Only support legal VTs for other shuffles for now. 2862 if (!isTypeLegal(VT)) 2863 return false; 2864 2865 MVT SVT = VT.getSimpleVT(); 2866 2867 bool SwapSources; 2868 int LoSrc, HiSrc; 2869 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2870 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2871 } 2872 2873 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2874 // the exponent. 2875 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2876 MVT VT = Op.getSimpleValueType(); 2877 unsigned EltSize = VT.getScalarSizeInBits(); 2878 SDValue Src = Op.getOperand(0); 2879 SDLoc DL(Op); 2880 2881 // We need a FP type that can represent the value. 2882 // TODO: Use f16 for i8 when possible? 2883 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2884 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2885 2886 // Legal types should have been checked in the RISCVTargetLowering 2887 // constructor. 2888 // TODO: Splitting may make sense in some cases. 2889 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2890 "Expected legal float type!"); 2891 2892 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2893 // The trailing zero count is equal to log2 of this single bit value. 2894 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2895 SDValue Neg = 2896 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2897 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2898 } 2899 2900 // We have a legal FP type, convert to it. 2901 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2902 // Bitcast to integer and shift the exponent to the LSB. 2903 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2904 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2905 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2906 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2907 DAG.getConstant(ShiftAmt, DL, IntVT)); 2908 // Truncate back to original type to allow vnsrl. 2909 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2910 // The exponent contains log2 of the value in biased form. 2911 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2912 2913 // For trailing zeros, we just need to subtract the bias. 2914 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2915 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2916 DAG.getConstant(ExponentBias, DL, VT)); 2917 2918 // For leading zeros, we need to remove the bias and convert from log2 to 2919 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2920 unsigned Adjust = ExponentBias + (EltSize - 1); 2921 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2922 } 2923 2924 // While RVV has alignment restrictions, we should always be able to load as a 2925 // legal equivalently-sized byte-typed vector instead. This method is 2926 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2927 // the load is already correctly-aligned, it returns SDValue(). 2928 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2929 SelectionDAG &DAG) const { 2930 auto *Load = cast<LoadSDNode>(Op); 2931 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2932 2933 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2934 Load->getMemoryVT(), 2935 *Load->getMemOperand())) 2936 return SDValue(); 2937 2938 SDLoc DL(Op); 2939 MVT VT = Op.getSimpleValueType(); 2940 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2941 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2942 "Unexpected unaligned RVV load type"); 2943 MVT NewVT = 2944 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2945 assert(NewVT.isValid() && 2946 "Expecting equally-sized RVV vector types to be legal"); 2947 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2948 Load->getPointerInfo(), Load->getOriginalAlign(), 2949 Load->getMemOperand()->getFlags()); 2950 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2951 } 2952 2953 // While RVV has alignment restrictions, we should always be able to store as a 2954 // legal equivalently-sized byte-typed vector instead. This method is 2955 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2956 // returns SDValue() if the store is already correctly aligned. 2957 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2958 SelectionDAG &DAG) const { 2959 auto *Store = cast<StoreSDNode>(Op); 2960 assert(Store && Store->getValue().getValueType().isVector() && 2961 "Expected vector store"); 2962 2963 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2964 Store->getMemoryVT(), 2965 *Store->getMemOperand())) 2966 return SDValue(); 2967 2968 SDLoc DL(Op); 2969 SDValue StoredVal = Store->getValue(); 2970 MVT VT = StoredVal.getSimpleValueType(); 2971 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2972 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2973 "Unexpected unaligned RVV store type"); 2974 MVT NewVT = 2975 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2976 assert(NewVT.isValid() && 2977 "Expecting equally-sized RVV vector types to be legal"); 2978 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2979 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2980 Store->getPointerInfo(), Store->getOriginalAlign(), 2981 Store->getMemOperand()->getFlags()); 2982 } 2983 2984 static SDValue lowerConstant(SDValue Op, SelectionDAG &DAG, 2985 const RISCVSubtarget &Subtarget) { 2986 assert(Op.getValueType() == MVT::i64 && "Unexpected VT"); 2987 2988 int64_t Imm = cast<ConstantSDNode>(Op)->getSExtValue(); 2989 2990 // All simm32 constants should be handled by isel. 2991 // NOTE: The getMaxBuildIntsCost call below should return a value >= 2 making 2992 // this check redundant, but small immediates are common so this check 2993 // should have better compile time. 2994 if (isInt<32>(Imm)) 2995 return Op; 2996 2997 // We only need to cost the immediate, if constant pool lowering is enabled. 2998 if (!Subtarget.useConstantPoolForLargeInts()) 2999 return Op; 3000 3001 RISCVMatInt::InstSeq Seq = 3002 RISCVMatInt::generateInstSeq(Imm, Subtarget.getFeatureBits()); 3003 if (Seq.size() <= Subtarget.getMaxBuildIntsCost()) 3004 return Op; 3005 3006 // Expand to a constant pool using the default expansion code. 3007 return SDValue(); 3008 } 3009 3010 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 3011 SelectionDAG &DAG) const { 3012 switch (Op.getOpcode()) { 3013 default: 3014 report_fatal_error("unimplemented operand"); 3015 case ISD::GlobalAddress: 3016 return lowerGlobalAddress(Op, DAG); 3017 case ISD::BlockAddress: 3018 return lowerBlockAddress(Op, DAG); 3019 case ISD::ConstantPool: 3020 return lowerConstantPool(Op, DAG); 3021 case ISD::JumpTable: 3022 return lowerJumpTable(Op, DAG); 3023 case ISD::GlobalTLSAddress: 3024 return lowerGlobalTLSAddress(Op, DAG); 3025 case ISD::Constant: 3026 return lowerConstant(Op, DAG, Subtarget); 3027 case ISD::SELECT: 3028 return lowerSELECT(Op, DAG); 3029 case ISD::BRCOND: 3030 return lowerBRCOND(Op, DAG); 3031 case ISD::VASTART: 3032 return lowerVASTART(Op, DAG); 3033 case ISD::FRAMEADDR: 3034 return lowerFRAMEADDR(Op, DAG); 3035 case ISD::RETURNADDR: 3036 return lowerRETURNADDR(Op, DAG); 3037 case ISD::SHL_PARTS: 3038 return lowerShiftLeftParts(Op, DAG); 3039 case ISD::SRA_PARTS: 3040 return lowerShiftRightParts(Op, DAG, true); 3041 case ISD::SRL_PARTS: 3042 return lowerShiftRightParts(Op, DAG, false); 3043 case ISD::BITCAST: { 3044 SDLoc DL(Op); 3045 EVT VT = Op.getValueType(); 3046 SDValue Op0 = Op.getOperand(0); 3047 EVT Op0VT = Op0.getValueType(); 3048 MVT XLenVT = Subtarget.getXLenVT(); 3049 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 3050 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 3051 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 3052 return FPConv; 3053 } 3054 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 3055 Subtarget.hasStdExtF()) { 3056 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3057 SDValue FPConv = 3058 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3059 return FPConv; 3060 } 3061 3062 // Consider other scalar<->scalar casts as legal if the types are legal. 3063 // Otherwise expand them. 3064 if (!VT.isVector() && !Op0VT.isVector()) { 3065 if (isTypeLegal(VT) && isTypeLegal(Op0VT)) 3066 return Op; 3067 return SDValue(); 3068 } 3069 3070 assert(!VT.isScalableVector() && !Op0VT.isScalableVector() && 3071 "Unexpected types"); 3072 3073 if (VT.isFixedLengthVector()) { 3074 // We can handle fixed length vector bitcasts with a simple replacement 3075 // in isel. 3076 if (Op0VT.isFixedLengthVector()) 3077 return Op; 3078 // When bitcasting from scalar to fixed-length vector, insert the scalar 3079 // into a one-element vector of the result type, and perform a vector 3080 // bitcast. 3081 if (!Op0VT.isVector()) { 3082 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 3083 if (!isTypeLegal(BVT)) 3084 return SDValue(); 3085 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 3086 DAG.getUNDEF(BVT), Op0, 3087 DAG.getConstant(0, DL, XLenVT))); 3088 } 3089 return SDValue(); 3090 } 3091 // Custom-legalize bitcasts from fixed-length vector types to scalar types 3092 // thus: bitcast the vector to a one-element vector type whose element type 3093 // is the same as the result type, and extract the first element. 3094 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 3095 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 3096 if (!isTypeLegal(BVT)) 3097 return SDValue(); 3098 SDValue BVec = DAG.getBitcast(BVT, Op0); 3099 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 3100 DAG.getConstant(0, DL, XLenVT)); 3101 } 3102 return SDValue(); 3103 } 3104 case ISD::INTRINSIC_WO_CHAIN: 3105 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3106 case ISD::INTRINSIC_W_CHAIN: 3107 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3108 case ISD::INTRINSIC_VOID: 3109 return LowerINTRINSIC_VOID(Op, DAG); 3110 case ISD::BSWAP: 3111 case ISD::BITREVERSE: { 3112 MVT VT = Op.getSimpleValueType(); 3113 SDLoc DL(Op); 3114 if (Subtarget.hasStdExtZbp()) { 3115 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3116 // Start with the maximum immediate value which is the bitwidth - 1. 3117 unsigned Imm = VT.getSizeInBits() - 1; 3118 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3119 if (Op.getOpcode() == ISD::BSWAP) 3120 Imm &= ~0x7U; 3121 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3122 DAG.getConstant(Imm, DL, VT)); 3123 } 3124 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3125 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3126 // Expand bitreverse to a bswap(rev8) followed by brev8. 3127 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3128 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3129 // as brev8 by an isel pattern. 3130 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3131 DAG.getConstant(7, DL, VT)); 3132 } 3133 case ISD::FSHL: 3134 case ISD::FSHR: { 3135 MVT VT = Op.getSimpleValueType(); 3136 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3137 SDLoc DL(Op); 3138 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3139 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3140 // accidentally setting the extra bit. 3141 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3142 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3143 DAG.getConstant(ShAmtWidth, DL, VT)); 3144 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3145 // instruction use different orders. fshl will return its first operand for 3146 // shift of zero, fshr will return its second operand. fsl and fsr both 3147 // return rs1 so the ISD nodes need to have different operand orders. 3148 // Shift amount is in rs2. 3149 SDValue Op0 = Op.getOperand(0); 3150 SDValue Op1 = Op.getOperand(1); 3151 unsigned Opc = RISCVISD::FSL; 3152 if (Op.getOpcode() == ISD::FSHR) { 3153 std::swap(Op0, Op1); 3154 Opc = RISCVISD::FSR; 3155 } 3156 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3157 } 3158 case ISD::TRUNCATE: 3159 // Only custom-lower vector truncates 3160 if (!Op.getSimpleValueType().isVector()) 3161 return Op; 3162 return lowerVectorTruncLike(Op, DAG); 3163 case ISD::ANY_EXTEND: 3164 case ISD::ZERO_EXTEND: 3165 if (Op.getOperand(0).getValueType().isVector() && 3166 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3167 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3168 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3169 case ISD::SIGN_EXTEND: 3170 if (Op.getOperand(0).getValueType().isVector() && 3171 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3172 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3173 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3174 case ISD::SPLAT_VECTOR_PARTS: 3175 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3176 case ISD::INSERT_VECTOR_ELT: 3177 return lowerINSERT_VECTOR_ELT(Op, DAG); 3178 case ISD::EXTRACT_VECTOR_ELT: 3179 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3180 case ISD::VSCALE: { 3181 MVT VT = Op.getSimpleValueType(); 3182 SDLoc DL(Op); 3183 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3184 // We define our scalable vector types for lmul=1 to use a 64 bit known 3185 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3186 // vscale as VLENB / 8. 3187 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3188 if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock) 3189 report_fatal_error("Support for VLEN==32 is incomplete."); 3190 // We assume VLENB is a multiple of 8. We manually choose the best shift 3191 // here because SimplifyDemandedBits isn't always able to simplify it. 3192 uint64_t Val = Op.getConstantOperandVal(0); 3193 if (isPowerOf2_64(Val)) { 3194 uint64_t Log2 = Log2_64(Val); 3195 if (Log2 < 3) 3196 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3197 DAG.getConstant(3 - Log2, DL, VT)); 3198 if (Log2 > 3) 3199 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3200 DAG.getConstant(Log2 - 3, DL, VT)); 3201 return VLENB; 3202 } 3203 // If the multiplier is a multiple of 8, scale it down to avoid needing 3204 // to shift the VLENB value. 3205 if ((Val % 8) == 0) 3206 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3207 DAG.getConstant(Val / 8, DL, VT)); 3208 3209 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3210 DAG.getConstant(3, DL, VT)); 3211 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3212 } 3213 case ISD::FPOWI: { 3214 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3215 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3216 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3217 Op.getOperand(1).getValueType() == MVT::i32) { 3218 SDLoc DL(Op); 3219 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3220 SDValue Powi = 3221 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3222 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3223 DAG.getIntPtrConstant(0, DL)); 3224 } 3225 return SDValue(); 3226 } 3227 case ISD::FP_EXTEND: 3228 case ISD::FP_ROUND: 3229 if (!Op.getValueType().isVector()) 3230 return Op; 3231 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3232 case ISD::FP_TO_SINT: 3233 case ISD::FP_TO_UINT: 3234 case ISD::SINT_TO_FP: 3235 case ISD::UINT_TO_FP: { 3236 // RVV can only do fp<->int conversions to types half/double the size as 3237 // the source. We custom-lower any conversions that do two hops into 3238 // sequences. 3239 MVT VT = Op.getSimpleValueType(); 3240 if (!VT.isVector()) 3241 return Op; 3242 SDLoc DL(Op); 3243 SDValue Src = Op.getOperand(0); 3244 MVT EltVT = VT.getVectorElementType(); 3245 MVT SrcVT = Src.getSimpleValueType(); 3246 MVT SrcEltVT = SrcVT.getVectorElementType(); 3247 unsigned EltSize = EltVT.getSizeInBits(); 3248 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3249 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3250 "Unexpected vector element types"); 3251 3252 bool IsInt2FP = SrcEltVT.isInteger(); 3253 // Widening conversions 3254 if (EltSize > (2 * SrcEltSize)) { 3255 if (IsInt2FP) { 3256 // Do a regular integer sign/zero extension then convert to float. 3257 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), 3258 VT.getVectorElementCount()); 3259 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3260 ? ISD::ZERO_EXTEND 3261 : ISD::SIGN_EXTEND; 3262 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3263 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3264 } 3265 // FP2Int 3266 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3267 // Do one doubling fp_extend then complete the operation by converting 3268 // to int. 3269 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3270 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3271 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3272 } 3273 3274 // Narrowing conversions 3275 if (SrcEltSize > (2 * EltSize)) { 3276 if (IsInt2FP) { 3277 // One narrowing int_to_fp, then an fp_round. 3278 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3279 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3280 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3281 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3282 } 3283 // FP2Int 3284 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3285 // representable by the integer, the result is poison. 3286 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 3287 VT.getVectorElementCount()); 3288 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3289 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3290 } 3291 3292 // Scalable vectors can exit here. Patterns will handle equally-sized 3293 // conversions halving/doubling ones. 3294 if (!VT.isFixedLengthVector()) 3295 return Op; 3296 3297 // For fixed-length vectors we lower to a custom "VL" node. 3298 unsigned RVVOpc = 0; 3299 switch (Op.getOpcode()) { 3300 default: 3301 llvm_unreachable("Impossible opcode"); 3302 case ISD::FP_TO_SINT: 3303 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3304 break; 3305 case ISD::FP_TO_UINT: 3306 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3307 break; 3308 case ISD::SINT_TO_FP: 3309 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3310 break; 3311 case ISD::UINT_TO_FP: 3312 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3313 break; 3314 } 3315 3316 MVT ContainerVT, SrcContainerVT; 3317 // Derive the reference container type from the larger vector type. 3318 if (SrcEltSize > EltSize) { 3319 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3320 ContainerVT = 3321 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3322 } else { 3323 ContainerVT = getContainerForFixedLengthVector(VT); 3324 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3325 } 3326 3327 SDValue Mask, VL; 3328 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3329 3330 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3331 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3332 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3333 } 3334 case ISD::FP_TO_SINT_SAT: 3335 case ISD::FP_TO_UINT_SAT: 3336 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3337 case ISD::FTRUNC: 3338 case ISD::FCEIL: 3339 case ISD::FFLOOR: 3340 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3341 case ISD::FROUND: 3342 return lowerFROUND(Op, DAG); 3343 case ISD::VECREDUCE_ADD: 3344 case ISD::VECREDUCE_UMAX: 3345 case ISD::VECREDUCE_SMAX: 3346 case ISD::VECREDUCE_UMIN: 3347 case ISD::VECREDUCE_SMIN: 3348 return lowerVECREDUCE(Op, DAG); 3349 case ISD::VECREDUCE_AND: 3350 case ISD::VECREDUCE_OR: 3351 case ISD::VECREDUCE_XOR: 3352 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3353 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3354 return lowerVECREDUCE(Op, DAG); 3355 case ISD::VECREDUCE_FADD: 3356 case ISD::VECREDUCE_SEQ_FADD: 3357 case ISD::VECREDUCE_FMIN: 3358 case ISD::VECREDUCE_FMAX: 3359 return lowerFPVECREDUCE(Op, DAG); 3360 case ISD::VP_REDUCE_ADD: 3361 case ISD::VP_REDUCE_UMAX: 3362 case ISD::VP_REDUCE_SMAX: 3363 case ISD::VP_REDUCE_UMIN: 3364 case ISD::VP_REDUCE_SMIN: 3365 case ISD::VP_REDUCE_FADD: 3366 case ISD::VP_REDUCE_SEQ_FADD: 3367 case ISD::VP_REDUCE_FMIN: 3368 case ISD::VP_REDUCE_FMAX: 3369 return lowerVPREDUCE(Op, DAG); 3370 case ISD::VP_REDUCE_AND: 3371 case ISD::VP_REDUCE_OR: 3372 case ISD::VP_REDUCE_XOR: 3373 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3374 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3375 return lowerVPREDUCE(Op, DAG); 3376 case ISD::INSERT_SUBVECTOR: 3377 return lowerINSERT_SUBVECTOR(Op, DAG); 3378 case ISD::EXTRACT_SUBVECTOR: 3379 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3380 case ISD::STEP_VECTOR: 3381 return lowerSTEP_VECTOR(Op, DAG); 3382 case ISD::VECTOR_REVERSE: 3383 return lowerVECTOR_REVERSE(Op, DAG); 3384 case ISD::VECTOR_SPLICE: 3385 return lowerVECTOR_SPLICE(Op, DAG); 3386 case ISD::BUILD_VECTOR: 3387 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3388 case ISD::SPLAT_VECTOR: 3389 if (Op.getValueType().getVectorElementType() == MVT::i1) 3390 return lowerVectorMaskSplat(Op, DAG); 3391 return SDValue(); 3392 case ISD::VECTOR_SHUFFLE: 3393 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3394 case ISD::CONCAT_VECTORS: { 3395 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3396 // better than going through the stack, as the default expansion does. 3397 SDLoc DL(Op); 3398 MVT VT = Op.getSimpleValueType(); 3399 unsigned NumOpElts = 3400 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3401 SDValue Vec = DAG.getUNDEF(VT); 3402 for (const auto &OpIdx : enumerate(Op->ops())) { 3403 SDValue SubVec = OpIdx.value(); 3404 // Don't insert undef subvectors. 3405 if (SubVec.isUndef()) 3406 continue; 3407 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3408 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3409 } 3410 return Vec; 3411 } 3412 case ISD::LOAD: 3413 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3414 return V; 3415 if (Op.getValueType().isFixedLengthVector()) 3416 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3417 return Op; 3418 case ISD::STORE: 3419 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3420 return V; 3421 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3422 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3423 return Op; 3424 case ISD::MLOAD: 3425 case ISD::VP_LOAD: 3426 return lowerMaskedLoad(Op, DAG); 3427 case ISD::MSTORE: 3428 case ISD::VP_STORE: 3429 return lowerMaskedStore(Op, DAG); 3430 case ISD::SETCC: 3431 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3432 case ISD::ADD: 3433 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3434 case ISD::SUB: 3435 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3436 case ISD::MUL: 3437 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3438 case ISD::MULHS: 3439 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3440 case ISD::MULHU: 3441 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3442 case ISD::AND: 3443 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3444 RISCVISD::AND_VL); 3445 case ISD::OR: 3446 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3447 RISCVISD::OR_VL); 3448 case ISD::XOR: 3449 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3450 RISCVISD::XOR_VL); 3451 case ISD::SDIV: 3452 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3453 case ISD::SREM: 3454 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3455 case ISD::UDIV: 3456 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3457 case ISD::UREM: 3458 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3459 case ISD::SHL: 3460 case ISD::SRA: 3461 case ISD::SRL: 3462 if (Op.getSimpleValueType().isFixedLengthVector()) 3463 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3464 // This can be called for an i32 shift amount that needs to be promoted. 3465 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3466 "Unexpected custom legalisation"); 3467 return SDValue(); 3468 case ISD::SADDSAT: 3469 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3470 case ISD::UADDSAT: 3471 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3472 case ISD::SSUBSAT: 3473 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3474 case ISD::USUBSAT: 3475 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3476 case ISD::FADD: 3477 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3478 case ISD::FSUB: 3479 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3480 case ISD::FMUL: 3481 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3482 case ISD::FDIV: 3483 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3484 case ISD::FNEG: 3485 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3486 case ISD::FABS: 3487 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3488 case ISD::FSQRT: 3489 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3490 case ISD::FMA: 3491 return lowerToScalableOp(Op, DAG, RISCVISD::VFMADD_VL); 3492 case ISD::SMIN: 3493 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3494 case ISD::SMAX: 3495 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3496 case ISD::UMIN: 3497 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3498 case ISD::UMAX: 3499 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3500 case ISD::FMINNUM: 3501 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3502 case ISD::FMAXNUM: 3503 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3504 case ISD::ABS: 3505 return lowerABS(Op, DAG); 3506 case ISD::CTLZ_ZERO_UNDEF: 3507 case ISD::CTTZ_ZERO_UNDEF: 3508 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3509 case ISD::VSELECT: 3510 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3511 case ISD::FCOPYSIGN: 3512 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3513 case ISD::MGATHER: 3514 case ISD::VP_GATHER: 3515 return lowerMaskedGather(Op, DAG); 3516 case ISD::MSCATTER: 3517 case ISD::VP_SCATTER: 3518 return lowerMaskedScatter(Op, DAG); 3519 case ISD::FLT_ROUNDS_: 3520 return lowerGET_ROUNDING(Op, DAG); 3521 case ISD::SET_ROUNDING: 3522 return lowerSET_ROUNDING(Op, DAG); 3523 case ISD::EH_DWARF_CFA: 3524 return lowerEH_DWARF_CFA(Op, DAG); 3525 case ISD::VP_SELECT: 3526 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3527 case ISD::VP_MERGE: 3528 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3529 case ISD::VP_ADD: 3530 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3531 case ISD::VP_SUB: 3532 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3533 case ISD::VP_MUL: 3534 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3535 case ISD::VP_SDIV: 3536 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3537 case ISD::VP_UDIV: 3538 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3539 case ISD::VP_SREM: 3540 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3541 case ISD::VP_UREM: 3542 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3543 case ISD::VP_AND: 3544 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3545 case ISD::VP_OR: 3546 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3547 case ISD::VP_XOR: 3548 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3549 case ISD::VP_ASHR: 3550 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3551 case ISD::VP_LSHR: 3552 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3553 case ISD::VP_SHL: 3554 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3555 case ISD::VP_FADD: 3556 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3557 case ISD::VP_FSUB: 3558 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3559 case ISD::VP_FMUL: 3560 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3561 case ISD::VP_FDIV: 3562 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3563 case ISD::VP_FNEG: 3564 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3565 case ISD::VP_FMA: 3566 return lowerVPOp(Op, DAG, RISCVISD::VFMADD_VL); 3567 case ISD::VP_SIGN_EXTEND: 3568 case ISD::VP_ZERO_EXTEND: 3569 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3570 return lowerVPExtMaskOp(Op, DAG); 3571 return lowerVPOp(Op, DAG, 3572 Op.getOpcode() == ISD::VP_SIGN_EXTEND 3573 ? RISCVISD::VSEXT_VL 3574 : RISCVISD::VZEXT_VL); 3575 case ISD::VP_TRUNCATE: 3576 return lowerVectorTruncLike(Op, DAG); 3577 case ISD::VP_FP_EXTEND: 3578 case ISD::VP_FP_ROUND: 3579 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3580 case ISD::VP_FPTOSI: 3581 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL); 3582 case ISD::VP_FPTOUI: 3583 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL); 3584 case ISD::VP_SITOFP: 3585 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL); 3586 case ISD::VP_UITOFP: 3587 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL); 3588 case ISD::VP_SETCC: 3589 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3590 return lowerVPSetCCMaskOp(Op, DAG); 3591 return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL); 3592 } 3593 } 3594 3595 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3596 SelectionDAG &DAG, unsigned Flags) { 3597 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3598 } 3599 3600 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3601 SelectionDAG &DAG, unsigned Flags) { 3602 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3603 Flags); 3604 } 3605 3606 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3607 SelectionDAG &DAG, unsigned Flags) { 3608 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3609 N->getOffset(), Flags); 3610 } 3611 3612 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3613 SelectionDAG &DAG, unsigned Flags) { 3614 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3615 } 3616 3617 template <class NodeTy> 3618 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3619 bool IsLocal) const { 3620 SDLoc DL(N); 3621 EVT Ty = getPointerTy(DAG.getDataLayout()); 3622 3623 if (isPositionIndependent()) { 3624 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3625 if (IsLocal) 3626 // Use PC-relative addressing to access the symbol. This generates the 3627 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3628 // %pcrel_lo(auipc)). 3629 return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr); 3630 3631 // Use PC-relative addressing to access the GOT for this symbol, then load 3632 // the address from the GOT. This generates the pattern (PseudoLA sym), 3633 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3634 MachineFunction &MF = DAG.getMachineFunction(); 3635 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3636 MachinePointerInfo::getGOT(MF), 3637 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3638 MachineMemOperand::MOInvariant, 3639 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3640 SDValue Load = 3641 DAG.getMemIntrinsicNode(RISCVISD::LA, DL, DAG.getVTList(Ty, MVT::Other), 3642 {DAG.getEntryNode(), Addr}, Ty, MemOp); 3643 return Load; 3644 } 3645 3646 switch (getTargetMachine().getCodeModel()) { 3647 default: 3648 report_fatal_error("Unsupported code model for lowering"); 3649 case CodeModel::Small: { 3650 // Generate a sequence for accessing addresses within the first 2 GiB of 3651 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3652 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3653 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3654 SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi); 3655 return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNHi, AddrLo); 3656 } 3657 case CodeModel::Medium: { 3658 // Generate a sequence for accessing addresses within any 2GiB range within 3659 // the address space. This generates the pattern (PseudoLLA sym), which 3660 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3661 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3662 return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr); 3663 } 3664 } 3665 } 3666 3667 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3668 SelectionDAG &DAG) const { 3669 SDLoc DL(Op); 3670 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3671 assert(N->getOffset() == 0 && "unexpected offset in global node"); 3672 3673 const GlobalValue *GV = N->getGlobal(); 3674 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3675 return getAddr(N, DAG, IsLocal); 3676 } 3677 3678 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3679 SelectionDAG &DAG) const { 3680 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3681 3682 return getAddr(N, DAG); 3683 } 3684 3685 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3686 SelectionDAG &DAG) const { 3687 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3688 3689 return getAddr(N, DAG); 3690 } 3691 3692 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3693 SelectionDAG &DAG) const { 3694 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3695 3696 return getAddr(N, DAG); 3697 } 3698 3699 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3700 SelectionDAG &DAG, 3701 bool UseGOT) const { 3702 SDLoc DL(N); 3703 EVT Ty = getPointerTy(DAG.getDataLayout()); 3704 const GlobalValue *GV = N->getGlobal(); 3705 MVT XLenVT = Subtarget.getXLenVT(); 3706 3707 if (UseGOT) { 3708 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3709 // load the address from the GOT and add the thread pointer. This generates 3710 // the pattern (PseudoLA_TLS_IE sym), which expands to 3711 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3712 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3713 MachineFunction &MF = DAG.getMachineFunction(); 3714 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3715 MachinePointerInfo::getGOT(MF), 3716 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3717 MachineMemOperand::MOInvariant, 3718 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3719 SDValue Load = DAG.getMemIntrinsicNode( 3720 RISCVISD::LA_TLS_IE, DL, DAG.getVTList(Ty, MVT::Other), 3721 {DAG.getEntryNode(), Addr}, Ty, MemOp); 3722 3723 // Add the thread pointer. 3724 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3725 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3726 } 3727 3728 // Generate a sequence for accessing the address relative to the thread 3729 // pointer, with the appropriate adjustment for the thread pointer offset. 3730 // This generates the pattern 3731 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3732 SDValue AddrHi = 3733 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3734 SDValue AddrAdd = 3735 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3736 SDValue AddrLo = 3737 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3738 3739 SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi); 3740 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3741 SDValue MNAdd = 3742 DAG.getNode(RISCVISD::ADD_TPREL, DL, Ty, MNHi, TPReg, AddrAdd); 3743 return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNAdd, AddrLo); 3744 } 3745 3746 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3747 SelectionDAG &DAG) const { 3748 SDLoc DL(N); 3749 EVT Ty = getPointerTy(DAG.getDataLayout()); 3750 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3751 const GlobalValue *GV = N->getGlobal(); 3752 3753 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3754 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3755 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3756 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3757 SDValue Load = DAG.getNode(RISCVISD::LA_TLS_GD, DL, Ty, Addr); 3758 3759 // Prepare argument list to generate call. 3760 ArgListTy Args; 3761 ArgListEntry Entry; 3762 Entry.Node = Load; 3763 Entry.Ty = CallTy; 3764 Args.push_back(Entry); 3765 3766 // Setup call to __tls_get_addr. 3767 TargetLowering::CallLoweringInfo CLI(DAG); 3768 CLI.setDebugLoc(DL) 3769 .setChain(DAG.getEntryNode()) 3770 .setLibCallee(CallingConv::C, CallTy, 3771 DAG.getExternalSymbol("__tls_get_addr", Ty), 3772 std::move(Args)); 3773 3774 return LowerCallTo(CLI).first; 3775 } 3776 3777 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3778 SelectionDAG &DAG) const { 3779 SDLoc DL(Op); 3780 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3781 assert(N->getOffset() == 0 && "unexpected offset in global node"); 3782 3783 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3784 3785 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3786 CallingConv::GHC) 3787 report_fatal_error("In GHC calling convention TLS is not supported"); 3788 3789 SDValue Addr; 3790 switch (Model) { 3791 case TLSModel::LocalExec: 3792 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3793 break; 3794 case TLSModel::InitialExec: 3795 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3796 break; 3797 case TLSModel::LocalDynamic: 3798 case TLSModel::GeneralDynamic: 3799 Addr = getDynamicTLSAddr(N, DAG); 3800 break; 3801 } 3802 3803 return Addr; 3804 } 3805 3806 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3807 SDValue CondV = Op.getOperand(0); 3808 SDValue TrueV = Op.getOperand(1); 3809 SDValue FalseV = Op.getOperand(2); 3810 SDLoc DL(Op); 3811 MVT VT = Op.getSimpleValueType(); 3812 MVT XLenVT = Subtarget.getXLenVT(); 3813 3814 // Lower vector SELECTs to VSELECTs by splatting the condition. 3815 if (VT.isVector()) { 3816 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3817 SDValue CondSplat = VT.isScalableVector() 3818 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3819 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3820 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3821 } 3822 3823 // If the result type is XLenVT and CondV is the output of a SETCC node 3824 // which also operated on XLenVT inputs, then merge the SETCC node into the 3825 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3826 // compare+branch instructions. i.e.: 3827 // (select (setcc lhs, rhs, cc), truev, falsev) 3828 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3829 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3830 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3831 SDValue LHS = CondV.getOperand(0); 3832 SDValue RHS = CondV.getOperand(1); 3833 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3834 ISD::CondCode CCVal = CC->get(); 3835 3836 // Special case for a select of 2 constants that have a diffence of 1. 3837 // Normally this is done by DAGCombine, but if the select is introduced by 3838 // type legalization or op legalization, we miss it. Restricting to SETLT 3839 // case for now because that is what signed saturating add/sub need. 3840 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3841 // but we would probably want to swap the true/false values if the condition 3842 // is SETGE/SETLE to avoid an XORI. 3843 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3844 CCVal == ISD::SETLT) { 3845 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3846 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3847 if (TrueVal - 1 == FalseVal) 3848 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3849 if (TrueVal + 1 == FalseVal) 3850 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3851 } 3852 3853 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3854 3855 SDValue TargetCC = DAG.getCondCode(CCVal); 3856 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3857 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3858 } 3859 3860 // Otherwise: 3861 // (select condv, truev, falsev) 3862 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3863 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3864 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3865 3866 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3867 3868 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3869 } 3870 3871 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3872 SDValue CondV = Op.getOperand(1); 3873 SDLoc DL(Op); 3874 MVT XLenVT = Subtarget.getXLenVT(); 3875 3876 if (CondV.getOpcode() == ISD::SETCC && 3877 CondV.getOperand(0).getValueType() == XLenVT) { 3878 SDValue LHS = CondV.getOperand(0); 3879 SDValue RHS = CondV.getOperand(1); 3880 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3881 3882 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3883 3884 SDValue TargetCC = DAG.getCondCode(CCVal); 3885 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3886 LHS, RHS, TargetCC, Op.getOperand(2)); 3887 } 3888 3889 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3890 CondV, DAG.getConstant(0, DL, XLenVT), 3891 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3892 } 3893 3894 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3895 MachineFunction &MF = DAG.getMachineFunction(); 3896 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3897 3898 SDLoc DL(Op); 3899 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3900 getPointerTy(MF.getDataLayout())); 3901 3902 // vastart just stores the address of the VarArgsFrameIndex slot into the 3903 // memory location argument. 3904 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3905 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3906 MachinePointerInfo(SV)); 3907 } 3908 3909 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3910 SelectionDAG &DAG) const { 3911 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3912 MachineFunction &MF = DAG.getMachineFunction(); 3913 MachineFrameInfo &MFI = MF.getFrameInfo(); 3914 MFI.setFrameAddressIsTaken(true); 3915 Register FrameReg = RI.getFrameRegister(MF); 3916 int XLenInBytes = Subtarget.getXLen() / 8; 3917 3918 EVT VT = Op.getValueType(); 3919 SDLoc DL(Op); 3920 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3921 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3922 while (Depth--) { 3923 int Offset = -(XLenInBytes * 2); 3924 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3925 DAG.getIntPtrConstant(Offset, DL)); 3926 FrameAddr = 3927 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3928 } 3929 return FrameAddr; 3930 } 3931 3932 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3933 SelectionDAG &DAG) const { 3934 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3935 MachineFunction &MF = DAG.getMachineFunction(); 3936 MachineFrameInfo &MFI = MF.getFrameInfo(); 3937 MFI.setReturnAddressIsTaken(true); 3938 MVT XLenVT = Subtarget.getXLenVT(); 3939 int XLenInBytes = Subtarget.getXLen() / 8; 3940 3941 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3942 return SDValue(); 3943 3944 EVT VT = Op.getValueType(); 3945 SDLoc DL(Op); 3946 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3947 if (Depth) { 3948 int Off = -XLenInBytes; 3949 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3950 SDValue Offset = DAG.getConstant(Off, DL, VT); 3951 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3952 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3953 MachinePointerInfo()); 3954 } 3955 3956 // Return the value of the return address register, marking it an implicit 3957 // live-in. 3958 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3959 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3960 } 3961 3962 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3963 SelectionDAG &DAG) const { 3964 SDLoc DL(Op); 3965 SDValue Lo = Op.getOperand(0); 3966 SDValue Hi = Op.getOperand(1); 3967 SDValue Shamt = Op.getOperand(2); 3968 EVT VT = Lo.getValueType(); 3969 3970 // if Shamt-XLEN < 0: // Shamt < XLEN 3971 // Lo = Lo << Shamt 3972 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 3973 // else: 3974 // Lo = 0 3975 // Hi = Lo << (Shamt-XLEN) 3976 3977 SDValue Zero = DAG.getConstant(0, DL, VT); 3978 SDValue One = DAG.getConstant(1, DL, VT); 3979 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3980 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3981 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3982 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 3983 3984 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3985 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3986 SDValue ShiftRightLo = 3987 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3988 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3989 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3990 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3991 3992 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3993 3994 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3995 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3996 3997 SDValue Parts[2] = {Lo, Hi}; 3998 return DAG.getMergeValues(Parts, DL); 3999 } 4000 4001 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 4002 bool IsSRA) const { 4003 SDLoc DL(Op); 4004 SDValue Lo = Op.getOperand(0); 4005 SDValue Hi = Op.getOperand(1); 4006 SDValue Shamt = Op.getOperand(2); 4007 EVT VT = Lo.getValueType(); 4008 4009 // SRA expansion: 4010 // if Shamt-XLEN < 0: // Shamt < XLEN 4011 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4012 // Hi = Hi >>s Shamt 4013 // else: 4014 // Lo = Hi >>s (Shamt-XLEN); 4015 // Hi = Hi >>s (XLEN-1) 4016 // 4017 // SRL expansion: 4018 // if Shamt-XLEN < 0: // Shamt < XLEN 4019 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4020 // Hi = Hi >>u Shamt 4021 // else: 4022 // Lo = Hi >>u (Shamt-XLEN); 4023 // Hi = 0; 4024 4025 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 4026 4027 SDValue Zero = DAG.getConstant(0, DL, VT); 4028 SDValue One = DAG.getConstant(1, DL, VT); 4029 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4030 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4031 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4032 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4033 4034 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 4035 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 4036 SDValue ShiftLeftHi = 4037 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 4038 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 4039 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 4040 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 4041 SDValue HiFalse = 4042 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 4043 4044 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4045 4046 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 4047 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4048 4049 SDValue Parts[2] = {Lo, Hi}; 4050 return DAG.getMergeValues(Parts, DL); 4051 } 4052 4053 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 4054 // legal equivalently-sized i8 type, so we can use that as a go-between. 4055 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4056 SelectionDAG &DAG) const { 4057 SDLoc DL(Op); 4058 MVT VT = Op.getSimpleValueType(); 4059 SDValue SplatVal = Op.getOperand(0); 4060 // All-zeros or all-ones splats are handled specially. 4061 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4062 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4063 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4064 } 4065 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4066 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4067 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4068 } 4069 MVT XLenVT = Subtarget.getXLenVT(); 4070 assert(SplatVal.getValueType() == XLenVT && 4071 "Unexpected type for i1 splat value"); 4072 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4073 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4074 DAG.getConstant(1, DL, XLenVT)); 4075 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4076 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4077 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4078 } 4079 4080 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4081 // illegal (currently only vXi64 RV32). 4082 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4083 // them to VMV_V_X_VL. 4084 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4085 SelectionDAG &DAG) const { 4086 SDLoc DL(Op); 4087 MVT VecVT = Op.getSimpleValueType(); 4088 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4089 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4090 4091 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4092 SDValue Lo = Op.getOperand(0); 4093 SDValue Hi = Op.getOperand(1); 4094 4095 if (VecVT.isFixedLengthVector()) { 4096 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4097 SDLoc DL(Op); 4098 SDValue Mask, VL; 4099 std::tie(Mask, VL) = 4100 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4101 4102 SDValue Res = 4103 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4104 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4105 } 4106 4107 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4108 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4109 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4110 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4111 // node in order to try and match RVV vector/scalar instructions. 4112 if ((LoC >> 31) == HiC) 4113 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4114 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4115 } 4116 4117 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4118 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4119 isa<ConstantSDNode>(Hi.getOperand(1)) && 4120 Hi.getConstantOperandVal(1) == 31) 4121 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4122 DAG.getRegister(RISCV::X0, MVT::i32)); 4123 4124 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4125 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4126 DAG.getUNDEF(VecVT), Lo, Hi, 4127 DAG.getRegister(RISCV::X0, MVT::i32)); 4128 } 4129 4130 // Custom-lower extensions from mask vectors by using a vselect either with 1 4131 // for zero/any-extension or -1 for sign-extension: 4132 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4133 // Note that any-extension is lowered identically to zero-extension. 4134 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4135 int64_t ExtTrueVal) const { 4136 SDLoc DL(Op); 4137 MVT VecVT = Op.getSimpleValueType(); 4138 SDValue Src = Op.getOperand(0); 4139 // Only custom-lower extensions from mask types 4140 assert(Src.getValueType().isVector() && 4141 Src.getValueType().getVectorElementType() == MVT::i1); 4142 4143 if (VecVT.isScalableVector()) { 4144 SDValue SplatZero = DAG.getConstant(0, DL, VecVT); 4145 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT); 4146 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4147 } 4148 4149 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4150 MVT I1ContainerVT = 4151 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4152 4153 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4154 4155 SDValue Mask, VL; 4156 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4157 4158 MVT XLenVT = Subtarget.getXLenVT(); 4159 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4160 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4161 4162 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4163 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4164 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4165 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4166 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4167 SplatTrueVal, SplatZero, VL); 4168 4169 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4170 } 4171 4172 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4173 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4174 MVT ExtVT = Op.getSimpleValueType(); 4175 // Only custom-lower extensions from fixed-length vector types. 4176 if (!ExtVT.isFixedLengthVector()) 4177 return Op; 4178 MVT VT = Op.getOperand(0).getSimpleValueType(); 4179 // Grab the canonical container type for the extended type. Infer the smaller 4180 // type from that to ensure the same number of vector elements, as we know 4181 // the LMUL will be sufficient to hold the smaller type. 4182 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4183 // Get the extended container type manually to ensure the same number of 4184 // vector elements between source and dest. 4185 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4186 ContainerExtVT.getVectorElementCount()); 4187 4188 SDValue Op1 = 4189 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4190 4191 SDLoc DL(Op); 4192 SDValue Mask, VL; 4193 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4194 4195 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4196 4197 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4198 } 4199 4200 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4201 // setcc operation: 4202 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4203 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op, 4204 SelectionDAG &DAG) const { 4205 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4206 SDLoc DL(Op); 4207 EVT MaskVT = Op.getValueType(); 4208 // Only expect to custom-lower truncations to mask types 4209 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4210 "Unexpected type for vector mask lowering"); 4211 SDValue Src = Op.getOperand(0); 4212 MVT VecVT = Src.getSimpleValueType(); 4213 SDValue Mask, VL; 4214 if (IsVPTrunc) { 4215 Mask = Op.getOperand(1); 4216 VL = Op.getOperand(2); 4217 } 4218 // If this is a fixed vector, we need to convert it to a scalable vector. 4219 MVT ContainerVT = VecVT; 4220 4221 if (VecVT.isFixedLengthVector()) { 4222 ContainerVT = getContainerForFixedLengthVector(VecVT); 4223 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4224 if (IsVPTrunc) { 4225 MVT MaskContainerVT = 4226 getContainerForFixedLengthVector(Mask.getSimpleValueType()); 4227 Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget); 4228 } 4229 } 4230 4231 if (!IsVPTrunc) { 4232 std::tie(Mask, VL) = 4233 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4234 } 4235 4236 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4237 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4238 4239 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4240 DAG.getUNDEF(ContainerVT), SplatOne, VL); 4241 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4242 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4243 4244 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4245 SDValue Trunc = 4246 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4247 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4248 DAG.getCondCode(ISD::SETNE), Mask, VL); 4249 if (MaskVT.isFixedLengthVector()) 4250 Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4251 return Trunc; 4252 } 4253 4254 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op, 4255 SelectionDAG &DAG) const { 4256 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4257 SDLoc DL(Op); 4258 4259 MVT VT = Op.getSimpleValueType(); 4260 // Only custom-lower vector truncates 4261 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4262 4263 // Truncates to mask types are handled differently 4264 if (VT.getVectorElementType() == MVT::i1) 4265 return lowerVectorMaskTruncLike(Op, DAG); 4266 4267 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 4268 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 4269 // truncate by one power of two at a time. 4270 MVT DstEltVT = VT.getVectorElementType(); 4271 4272 SDValue Src = Op.getOperand(0); 4273 MVT SrcVT = Src.getSimpleValueType(); 4274 MVT SrcEltVT = SrcVT.getVectorElementType(); 4275 4276 assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) && 4277 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 4278 "Unexpected vector truncate lowering"); 4279 4280 MVT ContainerVT = SrcVT; 4281 SDValue Mask, VL; 4282 if (IsVPTrunc) { 4283 Mask = Op.getOperand(1); 4284 VL = Op.getOperand(2); 4285 } 4286 if (SrcVT.isFixedLengthVector()) { 4287 ContainerVT = getContainerForFixedLengthVector(SrcVT); 4288 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4289 if (IsVPTrunc) { 4290 MVT MaskVT = getMaskTypeFor(ContainerVT); 4291 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4292 } 4293 } 4294 4295 SDValue Result = Src; 4296 if (!IsVPTrunc) { 4297 std::tie(Mask, VL) = 4298 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4299 } 4300 4301 LLVMContext &Context = *DAG.getContext(); 4302 const ElementCount Count = ContainerVT.getVectorElementCount(); 4303 do { 4304 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 4305 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 4306 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 4307 Mask, VL); 4308 } while (SrcEltVT != DstEltVT); 4309 4310 if (SrcVT.isFixedLengthVector()) 4311 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4312 4313 return Result; 4314 } 4315 4316 SDValue 4317 RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op, 4318 SelectionDAG &DAG) const { 4319 bool IsVP = 4320 Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND; 4321 bool IsExtend = 4322 Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND; 4323 // RVV can only do truncate fp to types half the size as the source. We 4324 // custom-lower f64->f16 rounds via RVV's round-to-odd float 4325 // conversion instruction. 4326 SDLoc DL(Op); 4327 MVT VT = Op.getSimpleValueType(); 4328 4329 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4330 4331 SDValue Src = Op.getOperand(0); 4332 MVT SrcVT = Src.getSimpleValueType(); 4333 4334 bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 || 4335 SrcVT.getVectorElementType() != MVT::f16); 4336 bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 || 4337 SrcVT.getVectorElementType() != MVT::f64); 4338 4339 bool IsDirectConv = IsDirectExtend || IsDirectTrunc; 4340 4341 // Prepare any fixed-length vector operands. 4342 MVT ContainerVT = VT; 4343 SDValue Mask, VL; 4344 if (IsVP) { 4345 Mask = Op.getOperand(1); 4346 VL = Op.getOperand(2); 4347 } 4348 if (VT.isFixedLengthVector()) { 4349 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 4350 ContainerVT = 4351 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 4352 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 4353 if (IsVP) { 4354 MVT MaskVT = getMaskTypeFor(ContainerVT); 4355 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4356 } 4357 } 4358 4359 if (!IsVP) 4360 std::tie(Mask, VL) = 4361 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4362 4363 unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL; 4364 4365 if (IsDirectConv) { 4366 Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL); 4367 if (VT.isFixedLengthVector()) 4368 Src = convertFromScalableVector(VT, Src, DAG, Subtarget); 4369 return Src; 4370 } 4371 4372 unsigned InterConvOpc = 4373 IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL; 4374 4375 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 4376 SDValue IntermediateConv = 4377 DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL); 4378 SDValue Result = 4379 DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL); 4380 if (VT.isFixedLengthVector()) 4381 return convertFromScalableVector(VT, Result, DAG, Subtarget); 4382 return Result; 4383 } 4384 4385 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4386 // first position of a vector, and that vector is slid up to the insert index. 4387 // By limiting the active vector length to index+1 and merging with the 4388 // original vector (with an undisturbed tail policy for elements >= VL), we 4389 // achieve the desired result of leaving all elements untouched except the one 4390 // at VL-1, which is replaced with the desired value. 4391 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4392 SelectionDAG &DAG) const { 4393 SDLoc DL(Op); 4394 MVT VecVT = Op.getSimpleValueType(); 4395 SDValue Vec = Op.getOperand(0); 4396 SDValue Val = Op.getOperand(1); 4397 SDValue Idx = Op.getOperand(2); 4398 4399 if (VecVT.getVectorElementType() == MVT::i1) { 4400 // FIXME: For now we just promote to an i8 vector and insert into that, 4401 // but this is probably not optimal. 4402 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4403 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4404 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4405 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4406 } 4407 4408 MVT ContainerVT = VecVT; 4409 // If the operand is a fixed-length vector, convert to a scalable one. 4410 if (VecVT.isFixedLengthVector()) { 4411 ContainerVT = getContainerForFixedLengthVector(VecVT); 4412 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4413 } 4414 4415 MVT XLenVT = Subtarget.getXLenVT(); 4416 4417 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4418 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4419 // Even i64-element vectors on RV32 can be lowered without scalar 4420 // legalization if the most-significant 32 bits of the value are not affected 4421 // by the sign-extension of the lower 32 bits. 4422 // TODO: We could also catch sign extensions of a 32-bit value. 4423 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4424 const auto *CVal = cast<ConstantSDNode>(Val); 4425 if (isInt<32>(CVal->getSExtValue())) { 4426 IsLegalInsert = true; 4427 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4428 } 4429 } 4430 4431 SDValue Mask, VL; 4432 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4433 4434 SDValue ValInVec; 4435 4436 if (IsLegalInsert) { 4437 unsigned Opc = 4438 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4439 if (isNullConstant(Idx)) { 4440 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4441 if (!VecVT.isFixedLengthVector()) 4442 return Vec; 4443 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4444 } 4445 ValInVec = 4446 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4447 } else { 4448 // On RV32, i64-element vectors must be specially handled to place the 4449 // value at element 0, by using two vslide1up instructions in sequence on 4450 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4451 // this. 4452 SDValue One = DAG.getConstant(1, DL, XLenVT); 4453 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4454 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4455 MVT I32ContainerVT = 4456 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4457 SDValue I32Mask = 4458 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4459 // Limit the active VL to two. 4460 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4461 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4462 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4463 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4464 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4465 // First slide in the hi value, then the lo in underneath it. 4466 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4467 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4468 I32Mask, InsertI64VL); 4469 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4470 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4471 I32Mask, InsertI64VL); 4472 // Bitcast back to the right container type. 4473 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4474 } 4475 4476 // Now that the value is in a vector, slide it into position. 4477 SDValue InsertVL = 4478 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4479 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4480 ValInVec, Idx, Mask, InsertVL); 4481 if (!VecVT.isFixedLengthVector()) 4482 return Slideup; 4483 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4484 } 4485 4486 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4487 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4488 // types this is done using VMV_X_S to allow us to glean information about the 4489 // sign bits of the result. 4490 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4491 SelectionDAG &DAG) const { 4492 SDLoc DL(Op); 4493 SDValue Idx = Op.getOperand(1); 4494 SDValue Vec = Op.getOperand(0); 4495 EVT EltVT = Op.getValueType(); 4496 MVT VecVT = Vec.getSimpleValueType(); 4497 MVT XLenVT = Subtarget.getXLenVT(); 4498 4499 if (VecVT.getVectorElementType() == MVT::i1) { 4500 if (VecVT.isFixedLengthVector()) { 4501 unsigned NumElts = VecVT.getVectorNumElements(); 4502 if (NumElts >= 8) { 4503 MVT WideEltVT; 4504 unsigned WidenVecLen; 4505 SDValue ExtractElementIdx; 4506 SDValue ExtractBitIdx; 4507 unsigned MaxEEW = Subtarget.getELEN(); 4508 MVT LargestEltVT = MVT::getIntegerVT( 4509 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4510 if (NumElts <= LargestEltVT.getSizeInBits()) { 4511 assert(isPowerOf2_32(NumElts) && 4512 "the number of elements should be power of 2"); 4513 WideEltVT = MVT::getIntegerVT(NumElts); 4514 WidenVecLen = 1; 4515 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4516 ExtractBitIdx = Idx; 4517 } else { 4518 WideEltVT = LargestEltVT; 4519 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4520 // extract element index = index / element width 4521 ExtractElementIdx = DAG.getNode( 4522 ISD::SRL, DL, XLenVT, Idx, 4523 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4524 // mask bit index = index % element width 4525 ExtractBitIdx = DAG.getNode( 4526 ISD::AND, DL, XLenVT, Idx, 4527 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4528 } 4529 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4530 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4531 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4532 Vec, ExtractElementIdx); 4533 // Extract the bit from GPR. 4534 SDValue ShiftRight = 4535 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4536 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4537 DAG.getConstant(1, DL, XLenVT)); 4538 } 4539 } 4540 // Otherwise, promote to an i8 vector and extract from that. 4541 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4542 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4543 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4544 } 4545 4546 // If this is a fixed vector, we need to convert it to a scalable vector. 4547 MVT ContainerVT = VecVT; 4548 if (VecVT.isFixedLengthVector()) { 4549 ContainerVT = getContainerForFixedLengthVector(VecVT); 4550 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4551 } 4552 4553 // If the index is 0, the vector is already in the right position. 4554 if (!isNullConstant(Idx)) { 4555 // Use a VL of 1 to avoid processing more elements than we need. 4556 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4557 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 4558 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4559 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4560 } 4561 4562 if (!EltVT.isInteger()) { 4563 // Floating-point extracts are handled in TableGen. 4564 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4565 DAG.getConstant(0, DL, XLenVT)); 4566 } 4567 4568 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4569 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4570 } 4571 4572 // Some RVV intrinsics may claim that they want an integer operand to be 4573 // promoted or expanded. 4574 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG, 4575 const RISCVSubtarget &Subtarget) { 4576 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4577 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4578 "Unexpected opcode"); 4579 4580 if (!Subtarget.hasVInstructions()) 4581 return SDValue(); 4582 4583 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4584 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4585 SDLoc DL(Op); 4586 4587 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4588 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4589 if (!II || !II->hasScalarOperand()) 4590 return SDValue(); 4591 4592 unsigned SplatOp = II->ScalarOperand + 1 + HasChain; 4593 assert(SplatOp < Op.getNumOperands()); 4594 4595 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4596 SDValue &ScalarOp = Operands[SplatOp]; 4597 MVT OpVT = ScalarOp.getSimpleValueType(); 4598 MVT XLenVT = Subtarget.getXLenVT(); 4599 4600 // If this isn't a scalar, or its type is XLenVT we're done. 4601 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4602 return SDValue(); 4603 4604 // Simplest case is that the operand needs to be promoted to XLenVT. 4605 if (OpVT.bitsLT(XLenVT)) { 4606 // If the operand is a constant, sign extend to increase our chances 4607 // of being able to use a .vi instruction. ANY_EXTEND would become a 4608 // a zero extend and the simm5 check in isel would fail. 4609 // FIXME: Should we ignore the upper bits in isel instead? 4610 unsigned ExtOpc = 4611 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4612 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4613 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4614 } 4615 4616 // Use the previous operand to get the vXi64 VT. The result might be a mask 4617 // VT for compares. Using the previous operand assumes that the previous 4618 // operand will never have a smaller element size than a scalar operand and 4619 // that a widening operation never uses SEW=64. 4620 // NOTE: If this fails the below assert, we can probably just find the 4621 // element count from any operand or result and use it to construct the VT. 4622 assert(II->ScalarOperand > 0 && "Unexpected splat operand!"); 4623 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4624 4625 // The more complex case is when the scalar is larger than XLenVT. 4626 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4627 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4628 4629 // If this is a sign-extended 32-bit value, we can truncate it and rely on the 4630 // instruction to sign-extend since SEW>XLEN. 4631 if (DAG.ComputeNumSignBits(ScalarOp) > 32) { 4632 ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp); 4633 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4634 } 4635 4636 switch (IntNo) { 4637 case Intrinsic::riscv_vslide1up: 4638 case Intrinsic::riscv_vslide1down: 4639 case Intrinsic::riscv_vslide1up_mask: 4640 case Intrinsic::riscv_vslide1down_mask: { 4641 // We need to special case these when the scalar is larger than XLen. 4642 unsigned NumOps = Op.getNumOperands(); 4643 bool IsMasked = NumOps == 7; 4644 4645 // Convert the vector source to the equivalent nxvXi32 vector. 4646 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4647 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4648 4649 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4650 DAG.getConstant(0, DL, XLenVT)); 4651 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4652 DAG.getConstant(1, DL, XLenVT)); 4653 4654 // Double the VL since we halved SEW. 4655 SDValue AVL = getVLOperand(Op); 4656 SDValue I32VL; 4657 4658 // Optimize for constant AVL 4659 if (isa<ConstantSDNode>(AVL)) { 4660 unsigned EltSize = VT.getScalarSizeInBits(); 4661 unsigned MinSize = VT.getSizeInBits().getKnownMinValue(); 4662 4663 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 4664 unsigned MaxVLMAX = 4665 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 4666 4667 unsigned VectorBitsMin = Subtarget.getRealMinVLen(); 4668 unsigned MinVLMAX = 4669 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize); 4670 4671 uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue(); 4672 if (AVLInt <= MinVLMAX) { 4673 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT); 4674 } else if (AVLInt >= 2 * MaxVLMAX) { 4675 // Just set vl to VLMAX in this situation 4676 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT); 4677 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4678 unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits()); 4679 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4680 SDValue SETVLMAX = DAG.getTargetConstant( 4681 Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32); 4682 I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW, 4683 LMUL); 4684 } else { 4685 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl 4686 // is related to the hardware implementation. 4687 // So let the following code handle 4688 } 4689 } 4690 if (!I32VL) { 4691 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT); 4692 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4693 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits()); 4694 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4695 SDValue SETVL = 4696 DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32); 4697 // Using vsetvli instruction to get actually used length which related to 4698 // the hardware implementation 4699 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL, 4700 SEW, LMUL); 4701 I32VL = 4702 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4703 } 4704 4705 SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG); 4706 4707 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4708 // instructions. 4709 SDValue Passthru; 4710 if (IsMasked) 4711 Passthru = DAG.getUNDEF(I32VT); 4712 else 4713 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4714 4715 if (IntNo == Intrinsic::riscv_vslide1up || 4716 IntNo == Intrinsic::riscv_vslide1up_mask) { 4717 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4718 ScalarHi, I32Mask, I32VL); 4719 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4720 ScalarLo, I32Mask, I32VL); 4721 } else { 4722 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4723 ScalarLo, I32Mask, I32VL); 4724 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4725 ScalarHi, I32Mask, I32VL); 4726 } 4727 4728 // Convert back to nxvXi64. 4729 Vec = DAG.getBitcast(VT, Vec); 4730 4731 if (!IsMasked) 4732 return Vec; 4733 // Apply mask after the operation. 4734 SDValue Mask = Operands[NumOps - 3]; 4735 SDValue MaskedOff = Operands[1]; 4736 // Assume Policy operand is the last operand. 4737 uint64_t Policy = 4738 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4739 // We don't need to select maskedoff if it's undef. 4740 if (MaskedOff.isUndef()) 4741 return Vec; 4742 // TAMU 4743 if (Policy == RISCVII::TAIL_AGNOSTIC) 4744 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4745 AVL); 4746 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4747 // It's fine because vmerge does not care mask policy. 4748 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, 4749 AVL); 4750 } 4751 } 4752 4753 // We need to convert the scalar to a splat vector. 4754 SDValue VL = getVLOperand(Op); 4755 assert(VL.getValueType() == XLenVT); 4756 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4757 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4758 } 4759 4760 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4761 SelectionDAG &DAG) const { 4762 unsigned IntNo = Op.getConstantOperandVal(0); 4763 SDLoc DL(Op); 4764 MVT XLenVT = Subtarget.getXLenVT(); 4765 4766 switch (IntNo) { 4767 default: 4768 break; // Don't custom lower most intrinsics. 4769 case Intrinsic::thread_pointer: { 4770 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4771 return DAG.getRegister(RISCV::X4, PtrVT); 4772 } 4773 case Intrinsic::riscv_orc_b: 4774 case Intrinsic::riscv_brev8: { 4775 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4776 unsigned Opc = 4777 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4778 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4779 DAG.getConstant(7, DL, XLenVT)); 4780 } 4781 case Intrinsic::riscv_grev: 4782 case Intrinsic::riscv_gorc: { 4783 unsigned Opc = 4784 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4785 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4786 } 4787 case Intrinsic::riscv_zip: 4788 case Intrinsic::riscv_unzip: { 4789 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4790 // For i32 the immediate is 15. For i64 the immediate is 31. 4791 unsigned Opc = 4792 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4793 unsigned BitWidth = Op.getValueSizeInBits(); 4794 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4795 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4796 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4797 } 4798 case Intrinsic::riscv_shfl: 4799 case Intrinsic::riscv_unshfl: { 4800 unsigned Opc = 4801 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4802 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4803 } 4804 case Intrinsic::riscv_bcompress: 4805 case Intrinsic::riscv_bdecompress: { 4806 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4807 : RISCVISD::BDECOMPRESS; 4808 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4809 } 4810 case Intrinsic::riscv_bfp: 4811 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4812 Op.getOperand(2)); 4813 case Intrinsic::riscv_fsl: 4814 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4815 Op.getOperand(2), Op.getOperand(3)); 4816 case Intrinsic::riscv_fsr: 4817 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4818 Op.getOperand(2), Op.getOperand(3)); 4819 case Intrinsic::riscv_vmv_x_s: 4820 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4821 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4822 Op.getOperand(1)); 4823 case Intrinsic::riscv_vmv_v_x: 4824 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4825 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4826 Subtarget); 4827 case Intrinsic::riscv_vfmv_v_f: 4828 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4829 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4830 case Intrinsic::riscv_vmv_s_x: { 4831 SDValue Scalar = Op.getOperand(2); 4832 4833 if (Scalar.getValueType().bitsLE(XLenVT)) { 4834 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4835 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4836 Op.getOperand(1), Scalar, Op.getOperand(3)); 4837 } 4838 4839 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4840 4841 // This is an i64 value that lives in two scalar registers. We have to 4842 // insert this in a convoluted way. First we build vXi64 splat containing 4843 // the two values that we assemble using some bit math. Next we'll use 4844 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4845 // to merge element 0 from our splat into the source vector. 4846 // FIXME: This is probably not the best way to do this, but it is 4847 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4848 // point. 4849 // sw lo, (a0) 4850 // sw hi, 4(a0) 4851 // vlse vX, (a0) 4852 // 4853 // vid.v vVid 4854 // vmseq.vx mMask, vVid, 0 4855 // vmerge.vvm vDest, vSrc, vVal, mMask 4856 MVT VT = Op.getSimpleValueType(); 4857 SDValue Vec = Op.getOperand(1); 4858 SDValue VL = getVLOperand(Op); 4859 4860 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4861 if (Op.getOperand(1).isUndef()) 4862 return SplattedVal; 4863 SDValue SplattedIdx = 4864 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4865 DAG.getConstant(0, DL, MVT::i32), VL); 4866 4867 MVT MaskVT = getMaskTypeFor(VT); 4868 SDValue Mask = getAllOnesMask(VT, VL, DL, DAG); 4869 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4870 SDValue SelectCond = 4871 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4872 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4873 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4874 Vec, VL); 4875 } 4876 } 4877 4878 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4879 } 4880 4881 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4882 SelectionDAG &DAG) const { 4883 unsigned IntNo = Op.getConstantOperandVal(1); 4884 switch (IntNo) { 4885 default: 4886 break; 4887 case Intrinsic::riscv_masked_strided_load: { 4888 SDLoc DL(Op); 4889 MVT XLenVT = Subtarget.getXLenVT(); 4890 4891 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4892 // the selection of the masked intrinsics doesn't do this for us. 4893 SDValue Mask = Op.getOperand(5); 4894 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4895 4896 MVT VT = Op->getSimpleValueType(0); 4897 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4898 4899 SDValue PassThru = Op.getOperand(2); 4900 if (!IsUnmasked) { 4901 MVT MaskVT = getMaskTypeFor(ContainerVT); 4902 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4903 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4904 } 4905 4906 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4907 4908 SDValue IntID = DAG.getTargetConstant( 4909 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4910 XLenVT); 4911 4912 auto *Load = cast<MemIntrinsicSDNode>(Op); 4913 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4914 if (IsUnmasked) 4915 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4916 else 4917 Ops.push_back(PassThru); 4918 Ops.push_back(Op.getOperand(3)); // Ptr 4919 Ops.push_back(Op.getOperand(4)); // Stride 4920 if (!IsUnmasked) 4921 Ops.push_back(Mask); 4922 Ops.push_back(VL); 4923 if (!IsUnmasked) { 4924 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4925 Ops.push_back(Policy); 4926 } 4927 4928 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4929 SDValue Result = 4930 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4931 Load->getMemoryVT(), Load->getMemOperand()); 4932 SDValue Chain = Result.getValue(1); 4933 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4934 return DAG.getMergeValues({Result, Chain}, DL); 4935 } 4936 case Intrinsic::riscv_seg2_load: 4937 case Intrinsic::riscv_seg3_load: 4938 case Intrinsic::riscv_seg4_load: 4939 case Intrinsic::riscv_seg5_load: 4940 case Intrinsic::riscv_seg6_load: 4941 case Intrinsic::riscv_seg7_load: 4942 case Intrinsic::riscv_seg8_load: { 4943 SDLoc DL(Op); 4944 static const Intrinsic::ID VlsegInts[7] = { 4945 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 4946 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 4947 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 4948 Intrinsic::riscv_vlseg8}; 4949 unsigned NF = Op->getNumValues() - 1; 4950 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 4951 MVT XLenVT = Subtarget.getXLenVT(); 4952 MVT VT = Op->getSimpleValueType(0); 4953 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4954 4955 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4956 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 4957 auto *Load = cast<MemIntrinsicSDNode>(Op); 4958 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 4959 ContainerVTs.push_back(MVT::Other); 4960 SDVTList VTs = DAG.getVTList(ContainerVTs); 4961 SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID}; 4962 Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT)); 4963 Ops.push_back(Op.getOperand(2)); 4964 Ops.push_back(VL); 4965 SDValue Result = 4966 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4967 Load->getMemoryVT(), Load->getMemOperand()); 4968 SmallVector<SDValue, 9> Results; 4969 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 4970 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 4971 DAG, Subtarget)); 4972 Results.push_back(Result.getValue(NF)); 4973 return DAG.getMergeValues(Results, DL); 4974 } 4975 } 4976 4977 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4978 } 4979 4980 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4981 SelectionDAG &DAG) const { 4982 unsigned IntNo = Op.getConstantOperandVal(1); 4983 switch (IntNo) { 4984 default: 4985 break; 4986 case Intrinsic::riscv_masked_strided_store: { 4987 SDLoc DL(Op); 4988 MVT XLenVT = Subtarget.getXLenVT(); 4989 4990 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4991 // the selection of the masked intrinsics doesn't do this for us. 4992 SDValue Mask = Op.getOperand(5); 4993 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4994 4995 SDValue Val = Op.getOperand(2); 4996 MVT VT = Val.getSimpleValueType(); 4997 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4998 4999 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5000 if (!IsUnmasked) { 5001 MVT MaskVT = getMaskTypeFor(ContainerVT); 5002 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5003 } 5004 5005 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5006 5007 SDValue IntID = DAG.getTargetConstant( 5008 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 5009 XLenVT); 5010 5011 auto *Store = cast<MemIntrinsicSDNode>(Op); 5012 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 5013 Ops.push_back(Val); 5014 Ops.push_back(Op.getOperand(3)); // Ptr 5015 Ops.push_back(Op.getOperand(4)); // Stride 5016 if (!IsUnmasked) 5017 Ops.push_back(Mask); 5018 Ops.push_back(VL); 5019 5020 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 5021 Ops, Store->getMemoryVT(), 5022 Store->getMemOperand()); 5023 } 5024 } 5025 5026 return SDValue(); 5027 } 5028 5029 static MVT getLMUL1VT(MVT VT) { 5030 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 5031 "Unexpected vector MVT"); 5032 return MVT::getScalableVectorVT( 5033 VT.getVectorElementType(), 5034 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 5035 } 5036 5037 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 5038 switch (ISDOpcode) { 5039 default: 5040 llvm_unreachable("Unhandled reduction"); 5041 case ISD::VECREDUCE_ADD: 5042 return RISCVISD::VECREDUCE_ADD_VL; 5043 case ISD::VECREDUCE_UMAX: 5044 return RISCVISD::VECREDUCE_UMAX_VL; 5045 case ISD::VECREDUCE_SMAX: 5046 return RISCVISD::VECREDUCE_SMAX_VL; 5047 case ISD::VECREDUCE_UMIN: 5048 return RISCVISD::VECREDUCE_UMIN_VL; 5049 case ISD::VECREDUCE_SMIN: 5050 return RISCVISD::VECREDUCE_SMIN_VL; 5051 case ISD::VECREDUCE_AND: 5052 return RISCVISD::VECREDUCE_AND_VL; 5053 case ISD::VECREDUCE_OR: 5054 return RISCVISD::VECREDUCE_OR_VL; 5055 case ISD::VECREDUCE_XOR: 5056 return RISCVISD::VECREDUCE_XOR_VL; 5057 } 5058 } 5059 5060 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 5061 SelectionDAG &DAG, 5062 bool IsVP) const { 5063 SDLoc DL(Op); 5064 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 5065 MVT VecVT = Vec.getSimpleValueType(); 5066 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 5067 Op.getOpcode() == ISD::VECREDUCE_OR || 5068 Op.getOpcode() == ISD::VECREDUCE_XOR || 5069 Op.getOpcode() == ISD::VP_REDUCE_AND || 5070 Op.getOpcode() == ISD::VP_REDUCE_OR || 5071 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5072 "Unexpected reduction lowering"); 5073 5074 MVT XLenVT = Subtarget.getXLenVT(); 5075 assert(Op.getValueType() == XLenVT && 5076 "Expected reduction output to be legalized to XLenVT"); 5077 5078 MVT ContainerVT = VecVT; 5079 if (VecVT.isFixedLengthVector()) { 5080 ContainerVT = getContainerForFixedLengthVector(VecVT); 5081 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5082 } 5083 5084 SDValue Mask, VL; 5085 if (IsVP) { 5086 Mask = Op.getOperand(2); 5087 VL = Op.getOperand(3); 5088 } else { 5089 std::tie(Mask, VL) = 5090 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5091 } 5092 5093 unsigned BaseOpc; 5094 ISD::CondCode CC; 5095 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5096 5097 switch (Op.getOpcode()) { 5098 default: 5099 llvm_unreachable("Unhandled reduction"); 5100 case ISD::VECREDUCE_AND: 5101 case ISD::VP_REDUCE_AND: { 5102 // vcpop ~x == 0 5103 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5104 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5105 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5106 CC = ISD::SETEQ; 5107 BaseOpc = ISD::AND; 5108 break; 5109 } 5110 case ISD::VECREDUCE_OR: 5111 case ISD::VP_REDUCE_OR: 5112 // vcpop x != 0 5113 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5114 CC = ISD::SETNE; 5115 BaseOpc = ISD::OR; 5116 break; 5117 case ISD::VECREDUCE_XOR: 5118 case ISD::VP_REDUCE_XOR: { 5119 // ((vcpop x) & 1) != 0 5120 SDValue One = DAG.getConstant(1, DL, XLenVT); 5121 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5122 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5123 CC = ISD::SETNE; 5124 BaseOpc = ISD::XOR; 5125 break; 5126 } 5127 } 5128 5129 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5130 5131 if (!IsVP) 5132 return SetCC; 5133 5134 // Now include the start value in the operation. 5135 // Note that we must return the start value when no elements are operated 5136 // upon. The vcpop instructions we've emitted in each case above will return 5137 // 0 for an inactive vector, and so we've already received the neutral value: 5138 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5139 // can simply include the start value. 5140 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5141 } 5142 5143 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5144 SelectionDAG &DAG) const { 5145 SDLoc DL(Op); 5146 SDValue Vec = Op.getOperand(0); 5147 EVT VecEVT = Vec.getValueType(); 5148 5149 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5150 5151 // Due to ordering in legalize types we may have a vector type that needs to 5152 // be split. Do that manually so we can get down to a legal type. 5153 while (getTypeAction(*DAG.getContext(), VecEVT) == 5154 TargetLowering::TypeSplitVector) { 5155 SDValue Lo, Hi; 5156 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5157 VecEVT = Lo.getValueType(); 5158 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5159 } 5160 5161 // TODO: The type may need to be widened rather than split. Or widened before 5162 // it can be split. 5163 if (!isTypeLegal(VecEVT)) 5164 return SDValue(); 5165 5166 MVT VecVT = VecEVT.getSimpleVT(); 5167 MVT VecEltVT = VecVT.getVectorElementType(); 5168 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5169 5170 MVT ContainerVT = VecVT; 5171 if (VecVT.isFixedLengthVector()) { 5172 ContainerVT = getContainerForFixedLengthVector(VecVT); 5173 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5174 } 5175 5176 MVT M1VT = getLMUL1VT(ContainerVT); 5177 MVT XLenVT = Subtarget.getXLenVT(); 5178 5179 SDValue Mask, VL; 5180 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5181 5182 SDValue NeutralElem = 5183 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5184 SDValue IdentitySplat = 5185 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5186 M1VT, DL, DAG, Subtarget); 5187 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5188 IdentitySplat, Mask, VL); 5189 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5190 DAG.getConstant(0, DL, XLenVT)); 5191 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5192 } 5193 5194 // Given a reduction op, this function returns the matching reduction opcode, 5195 // the vector SDValue and the scalar SDValue required to lower this to a 5196 // RISCVISD node. 5197 static std::tuple<unsigned, SDValue, SDValue> 5198 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5199 SDLoc DL(Op); 5200 auto Flags = Op->getFlags(); 5201 unsigned Opcode = Op.getOpcode(); 5202 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5203 switch (Opcode) { 5204 default: 5205 llvm_unreachable("Unhandled reduction"); 5206 case ISD::VECREDUCE_FADD: { 5207 // Use positive zero if we can. It is cheaper to materialize. 5208 SDValue Zero = 5209 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5210 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5211 } 5212 case ISD::VECREDUCE_SEQ_FADD: 5213 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5214 Op.getOperand(0)); 5215 case ISD::VECREDUCE_FMIN: 5216 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5217 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5218 case ISD::VECREDUCE_FMAX: 5219 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5220 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5221 } 5222 } 5223 5224 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5225 SelectionDAG &DAG) const { 5226 SDLoc DL(Op); 5227 MVT VecEltVT = Op.getSimpleValueType(); 5228 5229 unsigned RVVOpcode; 5230 SDValue VectorVal, ScalarVal; 5231 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5232 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5233 MVT VecVT = VectorVal.getSimpleValueType(); 5234 5235 MVT ContainerVT = VecVT; 5236 if (VecVT.isFixedLengthVector()) { 5237 ContainerVT = getContainerForFixedLengthVector(VecVT); 5238 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5239 } 5240 5241 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5242 MVT XLenVT = Subtarget.getXLenVT(); 5243 5244 SDValue Mask, VL; 5245 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5246 5247 SDValue ScalarSplat = 5248 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5249 M1VT, DL, DAG, Subtarget); 5250 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5251 VectorVal, ScalarSplat, Mask, VL); 5252 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5253 DAG.getConstant(0, DL, XLenVT)); 5254 } 5255 5256 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5257 switch (ISDOpcode) { 5258 default: 5259 llvm_unreachable("Unhandled reduction"); 5260 case ISD::VP_REDUCE_ADD: 5261 return RISCVISD::VECREDUCE_ADD_VL; 5262 case ISD::VP_REDUCE_UMAX: 5263 return RISCVISD::VECREDUCE_UMAX_VL; 5264 case ISD::VP_REDUCE_SMAX: 5265 return RISCVISD::VECREDUCE_SMAX_VL; 5266 case ISD::VP_REDUCE_UMIN: 5267 return RISCVISD::VECREDUCE_UMIN_VL; 5268 case ISD::VP_REDUCE_SMIN: 5269 return RISCVISD::VECREDUCE_SMIN_VL; 5270 case ISD::VP_REDUCE_AND: 5271 return RISCVISD::VECREDUCE_AND_VL; 5272 case ISD::VP_REDUCE_OR: 5273 return RISCVISD::VECREDUCE_OR_VL; 5274 case ISD::VP_REDUCE_XOR: 5275 return RISCVISD::VECREDUCE_XOR_VL; 5276 case ISD::VP_REDUCE_FADD: 5277 return RISCVISD::VECREDUCE_FADD_VL; 5278 case ISD::VP_REDUCE_SEQ_FADD: 5279 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5280 case ISD::VP_REDUCE_FMAX: 5281 return RISCVISD::VECREDUCE_FMAX_VL; 5282 case ISD::VP_REDUCE_FMIN: 5283 return RISCVISD::VECREDUCE_FMIN_VL; 5284 } 5285 } 5286 5287 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5288 SelectionDAG &DAG) const { 5289 SDLoc DL(Op); 5290 SDValue Vec = Op.getOperand(1); 5291 EVT VecEVT = Vec.getValueType(); 5292 5293 // TODO: The type may need to be widened rather than split. Or widened before 5294 // it can be split. 5295 if (!isTypeLegal(VecEVT)) 5296 return SDValue(); 5297 5298 MVT VecVT = VecEVT.getSimpleVT(); 5299 MVT VecEltVT = VecVT.getVectorElementType(); 5300 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5301 5302 MVT ContainerVT = VecVT; 5303 if (VecVT.isFixedLengthVector()) { 5304 ContainerVT = getContainerForFixedLengthVector(VecVT); 5305 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5306 } 5307 5308 SDValue VL = Op.getOperand(3); 5309 SDValue Mask = Op.getOperand(2); 5310 5311 MVT M1VT = getLMUL1VT(ContainerVT); 5312 MVT XLenVT = Subtarget.getXLenVT(); 5313 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5314 5315 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5316 DAG.getConstant(1, DL, XLenVT), M1VT, 5317 DL, DAG, Subtarget); 5318 SDValue Reduction = 5319 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5320 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5321 DAG.getConstant(0, DL, XLenVT)); 5322 if (!VecVT.isInteger()) 5323 return Elt0; 5324 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5325 } 5326 5327 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5328 SelectionDAG &DAG) const { 5329 SDValue Vec = Op.getOperand(0); 5330 SDValue SubVec = Op.getOperand(1); 5331 MVT VecVT = Vec.getSimpleValueType(); 5332 MVT SubVecVT = SubVec.getSimpleValueType(); 5333 5334 SDLoc DL(Op); 5335 MVT XLenVT = Subtarget.getXLenVT(); 5336 unsigned OrigIdx = Op.getConstantOperandVal(2); 5337 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5338 5339 // We don't have the ability to slide mask vectors up indexed by their i1 5340 // elements; the smallest we can do is i8. Often we are able to bitcast to 5341 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5342 // into a scalable one, we might not necessarily have enough scalable 5343 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5344 if (SubVecVT.getVectorElementType() == MVT::i1 && 5345 (OrigIdx != 0 || !Vec.isUndef())) { 5346 if (VecVT.getVectorMinNumElements() >= 8 && 5347 SubVecVT.getVectorMinNumElements() >= 8) { 5348 assert(OrigIdx % 8 == 0 && "Invalid index"); 5349 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5350 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5351 "Unexpected mask vector lowering"); 5352 OrigIdx /= 8; 5353 SubVecVT = 5354 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5355 SubVecVT.isScalableVector()); 5356 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5357 VecVT.isScalableVector()); 5358 Vec = DAG.getBitcast(VecVT, Vec); 5359 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5360 } else { 5361 // We can't slide this mask vector up indexed by its i1 elements. 5362 // This poses a problem when we wish to insert a scalable vector which 5363 // can't be re-expressed as a larger type. Just choose the slow path and 5364 // extend to a larger type, then truncate back down. 5365 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5366 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5367 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5368 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5369 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5370 Op.getOperand(2)); 5371 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5372 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5373 } 5374 } 5375 5376 // If the subvector vector is a fixed-length type, we cannot use subregister 5377 // manipulation to simplify the codegen; we don't know which register of a 5378 // LMUL group contains the specific subvector as we only know the minimum 5379 // register size. Therefore we must slide the vector group up the full 5380 // amount. 5381 if (SubVecVT.isFixedLengthVector()) { 5382 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5383 return Op; 5384 MVT ContainerVT = VecVT; 5385 if (VecVT.isFixedLengthVector()) { 5386 ContainerVT = getContainerForFixedLengthVector(VecVT); 5387 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5388 } 5389 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5390 DAG.getUNDEF(ContainerVT), SubVec, 5391 DAG.getConstant(0, DL, XLenVT)); 5392 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5393 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5394 return DAG.getBitcast(Op.getValueType(), SubVec); 5395 } 5396 SDValue Mask = 5397 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5398 // Set the vector length to only the number of elements we care about. Note 5399 // that for slideup this includes the offset. 5400 SDValue VL = 5401 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5402 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5403 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5404 SubVec, SlideupAmt, Mask, VL); 5405 if (VecVT.isFixedLengthVector()) 5406 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5407 return DAG.getBitcast(Op.getValueType(), Slideup); 5408 } 5409 5410 unsigned SubRegIdx, RemIdx; 5411 std::tie(SubRegIdx, RemIdx) = 5412 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5413 VecVT, SubVecVT, OrigIdx, TRI); 5414 5415 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5416 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5417 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5418 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5419 5420 // 1. If the Idx has been completely eliminated and this subvector's size is 5421 // a vector register or a multiple thereof, or the surrounding elements are 5422 // undef, then this is a subvector insert which naturally aligns to a vector 5423 // register. These can easily be handled using subregister manipulation. 5424 // 2. If the subvector is smaller than a vector register, then the insertion 5425 // must preserve the undisturbed elements of the register. We do this by 5426 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5427 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5428 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5429 // LMUL=1 type back into the larger vector (resolving to another subregister 5430 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5431 // to avoid allocating a large register group to hold our subvector. 5432 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5433 return Op; 5434 5435 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5436 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5437 // (in our case undisturbed). This means we can set up a subvector insertion 5438 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5439 // size of the subvector. 5440 MVT InterSubVT = VecVT; 5441 SDValue AlignedExtract = Vec; 5442 unsigned AlignedIdx = OrigIdx - RemIdx; 5443 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5444 InterSubVT = getLMUL1VT(VecVT); 5445 // Extract a subvector equal to the nearest full vector register type. This 5446 // should resolve to a EXTRACT_SUBREG instruction. 5447 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5448 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5449 } 5450 5451 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5452 // For scalable vectors this must be further multiplied by vscale. 5453 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5454 5455 SDValue Mask, VL; 5456 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5457 5458 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5459 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5460 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5461 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5462 5463 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5464 DAG.getUNDEF(InterSubVT), SubVec, 5465 DAG.getConstant(0, DL, XLenVT)); 5466 5467 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5468 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5469 5470 // If required, insert this subvector back into the correct vector register. 5471 // This should resolve to an INSERT_SUBREG instruction. 5472 if (VecVT.bitsGT(InterSubVT)) 5473 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5474 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5475 5476 // We might have bitcast from a mask type: cast back to the original type if 5477 // required. 5478 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5479 } 5480 5481 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5482 SelectionDAG &DAG) const { 5483 SDValue Vec = Op.getOperand(0); 5484 MVT SubVecVT = Op.getSimpleValueType(); 5485 MVT VecVT = Vec.getSimpleValueType(); 5486 5487 SDLoc DL(Op); 5488 MVT XLenVT = Subtarget.getXLenVT(); 5489 unsigned OrigIdx = Op.getConstantOperandVal(1); 5490 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5491 5492 // We don't have the ability to slide mask vectors down indexed by their i1 5493 // elements; the smallest we can do is i8. Often we are able to bitcast to 5494 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5495 // from a scalable one, we might not necessarily have enough scalable 5496 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5497 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5498 if (VecVT.getVectorMinNumElements() >= 8 && 5499 SubVecVT.getVectorMinNumElements() >= 8) { 5500 assert(OrigIdx % 8 == 0 && "Invalid index"); 5501 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5502 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5503 "Unexpected mask vector lowering"); 5504 OrigIdx /= 8; 5505 SubVecVT = 5506 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5507 SubVecVT.isScalableVector()); 5508 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5509 VecVT.isScalableVector()); 5510 Vec = DAG.getBitcast(VecVT, Vec); 5511 } else { 5512 // We can't slide this mask vector down, indexed by its i1 elements. 5513 // This poses a problem when we wish to extract a scalable vector which 5514 // can't be re-expressed as a larger type. Just choose the slow path and 5515 // extend to a larger type, then truncate back down. 5516 // TODO: We could probably improve this when extracting certain fixed 5517 // from fixed, where we can extract as i8 and shift the correct element 5518 // right to reach the desired subvector? 5519 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5520 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5521 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5522 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5523 Op.getOperand(1)); 5524 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5525 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5526 } 5527 } 5528 5529 // If the subvector vector is a fixed-length type, we cannot use subregister 5530 // manipulation to simplify the codegen; we don't know which register of a 5531 // LMUL group contains the specific subvector as we only know the minimum 5532 // register size. Therefore we must slide the vector group down the full 5533 // amount. 5534 if (SubVecVT.isFixedLengthVector()) { 5535 // With an index of 0 this is a cast-like subvector, which can be performed 5536 // with subregister operations. 5537 if (OrigIdx == 0) 5538 return Op; 5539 MVT ContainerVT = VecVT; 5540 if (VecVT.isFixedLengthVector()) { 5541 ContainerVT = getContainerForFixedLengthVector(VecVT); 5542 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5543 } 5544 SDValue Mask = 5545 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5546 // Set the vector length to only the number of elements we care about. This 5547 // avoids sliding down elements we're going to discard straight away. 5548 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5549 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5550 SDValue Slidedown = 5551 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5552 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5553 // Now we can use a cast-like subvector extract to get the result. 5554 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5555 DAG.getConstant(0, DL, XLenVT)); 5556 return DAG.getBitcast(Op.getValueType(), Slidedown); 5557 } 5558 5559 unsigned SubRegIdx, RemIdx; 5560 std::tie(SubRegIdx, RemIdx) = 5561 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5562 VecVT, SubVecVT, OrigIdx, TRI); 5563 5564 // If the Idx has been completely eliminated then this is a subvector extract 5565 // which naturally aligns to a vector register. These can easily be handled 5566 // using subregister manipulation. 5567 if (RemIdx == 0) 5568 return Op; 5569 5570 // Else we must shift our vector register directly to extract the subvector. 5571 // Do this using VSLIDEDOWN. 5572 5573 // If the vector type is an LMUL-group type, extract a subvector equal to the 5574 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5575 // instruction. 5576 MVT InterSubVT = VecVT; 5577 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5578 InterSubVT = getLMUL1VT(VecVT); 5579 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5580 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5581 } 5582 5583 // Slide this vector register down by the desired number of elements in order 5584 // to place the desired subvector starting at element 0. 5585 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5586 // For scalable vectors this must be further multiplied by vscale. 5587 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5588 5589 SDValue Mask, VL; 5590 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5591 SDValue Slidedown = 5592 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5593 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5594 5595 // Now the vector is in the right position, extract our final subvector. This 5596 // should resolve to a COPY. 5597 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5598 DAG.getConstant(0, DL, XLenVT)); 5599 5600 // We might have bitcast from a mask type: cast back to the original type if 5601 // required. 5602 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5603 } 5604 5605 // Lower step_vector to the vid instruction. Any non-identity step value must 5606 // be accounted for my manual expansion. 5607 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5608 SelectionDAG &DAG) const { 5609 SDLoc DL(Op); 5610 MVT VT = Op.getSimpleValueType(); 5611 MVT XLenVT = Subtarget.getXLenVT(); 5612 SDValue Mask, VL; 5613 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5614 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5615 uint64_t StepValImm = Op.getConstantOperandVal(0); 5616 if (StepValImm != 1) { 5617 if (isPowerOf2_64(StepValImm)) { 5618 SDValue StepVal = 5619 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5620 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5621 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5622 } else { 5623 SDValue StepVal = lowerScalarSplat( 5624 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5625 VL, VT, DL, DAG, Subtarget); 5626 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5627 } 5628 } 5629 return StepVec; 5630 } 5631 5632 // Implement vector_reverse using vrgather.vv with indices determined by 5633 // subtracting the id of each element from (VLMAX-1). This will convert 5634 // the indices like so: 5635 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5636 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5637 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5638 SelectionDAG &DAG) const { 5639 SDLoc DL(Op); 5640 MVT VecVT = Op.getSimpleValueType(); 5641 unsigned EltSize = VecVT.getScalarSizeInBits(); 5642 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5643 5644 unsigned MaxVLMAX = 0; 5645 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5646 if (VectorBitsMax != 0) 5647 MaxVLMAX = 5648 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 5649 5650 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5651 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5652 5653 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5654 // to use vrgatherei16.vv. 5655 // TODO: It's also possible to use vrgatherei16.vv for other types to 5656 // decrease register width for the index calculation. 5657 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5658 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5659 // Reverse each half, then reassemble them in reverse order. 5660 // NOTE: It's also possible that after splitting that VLMAX no longer 5661 // requires vrgatherei16.vv. 5662 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5663 SDValue Lo, Hi; 5664 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5665 EVT LoVT, HiVT; 5666 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5667 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5668 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5669 // Reassemble the low and high pieces reversed. 5670 // FIXME: This is a CONCAT_VECTORS. 5671 SDValue Res = 5672 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5673 DAG.getIntPtrConstant(0, DL)); 5674 return DAG.getNode( 5675 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5676 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5677 } 5678 5679 // Just promote the int type to i16 which will double the LMUL. 5680 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5681 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5682 } 5683 5684 MVT XLenVT = Subtarget.getXLenVT(); 5685 SDValue Mask, VL; 5686 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5687 5688 // Calculate VLMAX-1 for the desired SEW. 5689 unsigned MinElts = VecVT.getVectorMinNumElements(); 5690 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5691 DAG.getConstant(MinElts, DL, XLenVT)); 5692 SDValue VLMinus1 = 5693 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5694 5695 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5696 bool IsRV32E64 = 5697 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5698 SDValue SplatVL; 5699 if (!IsRV32E64) 5700 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5701 else 5702 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5703 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5704 5705 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5706 SDValue Indices = 5707 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5708 5709 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, 5710 DAG.getUNDEF(VecVT), VL); 5711 } 5712 5713 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5714 SelectionDAG &DAG) const { 5715 SDLoc DL(Op); 5716 SDValue V1 = Op.getOperand(0); 5717 SDValue V2 = Op.getOperand(1); 5718 MVT XLenVT = Subtarget.getXLenVT(); 5719 MVT VecVT = Op.getSimpleValueType(); 5720 5721 unsigned MinElts = VecVT.getVectorMinNumElements(); 5722 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5723 DAG.getConstant(MinElts, DL, XLenVT)); 5724 5725 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5726 SDValue DownOffset, UpOffset; 5727 if (ImmValue >= 0) { 5728 // The operand is a TargetConstant, we need to rebuild it as a regular 5729 // constant. 5730 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5731 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5732 } else { 5733 // The operand is a TargetConstant, we need to rebuild it as a regular 5734 // constant rather than negating the original operand. 5735 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5736 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5737 } 5738 5739 SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG); 5740 5741 SDValue SlideDown = 5742 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5743 DownOffset, TrueMask, UpOffset); 5744 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5745 TrueMask, 5746 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 5747 } 5748 5749 SDValue 5750 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5751 SelectionDAG &DAG) const { 5752 SDLoc DL(Op); 5753 auto *Load = cast<LoadSDNode>(Op); 5754 5755 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5756 Load->getMemoryVT(), 5757 *Load->getMemOperand()) && 5758 "Expecting a correctly-aligned load"); 5759 5760 MVT VT = Op.getSimpleValueType(); 5761 MVT XLenVT = Subtarget.getXLenVT(); 5762 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5763 5764 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5765 5766 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5767 SDValue IntID = DAG.getTargetConstant( 5768 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 5769 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 5770 if (!IsMaskOp) 5771 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5772 Ops.push_back(Load->getBasePtr()); 5773 Ops.push_back(VL); 5774 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5775 SDValue NewLoad = 5776 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5777 Load->getMemoryVT(), Load->getMemOperand()); 5778 5779 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5780 return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL); 5781 } 5782 5783 SDValue 5784 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5785 SelectionDAG &DAG) const { 5786 SDLoc DL(Op); 5787 auto *Store = cast<StoreSDNode>(Op); 5788 5789 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5790 Store->getMemoryVT(), 5791 *Store->getMemOperand()) && 5792 "Expecting a correctly-aligned store"); 5793 5794 SDValue StoreVal = Store->getValue(); 5795 MVT VT = StoreVal.getSimpleValueType(); 5796 MVT XLenVT = Subtarget.getXLenVT(); 5797 5798 // If the size less than a byte, we need to pad with zeros to make a byte. 5799 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5800 VT = MVT::v8i1; 5801 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5802 DAG.getConstant(0, DL, VT), StoreVal, 5803 DAG.getIntPtrConstant(0, DL)); 5804 } 5805 5806 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5807 5808 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5809 5810 SDValue NewValue = 5811 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5812 5813 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5814 SDValue IntID = DAG.getTargetConstant( 5815 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 5816 return DAG.getMemIntrinsicNode( 5817 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 5818 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 5819 Store->getMemoryVT(), Store->getMemOperand()); 5820 } 5821 5822 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5823 SelectionDAG &DAG) const { 5824 SDLoc DL(Op); 5825 MVT VT = Op.getSimpleValueType(); 5826 5827 const auto *MemSD = cast<MemSDNode>(Op); 5828 EVT MemVT = MemSD->getMemoryVT(); 5829 MachineMemOperand *MMO = MemSD->getMemOperand(); 5830 SDValue Chain = MemSD->getChain(); 5831 SDValue BasePtr = MemSD->getBasePtr(); 5832 5833 SDValue Mask, PassThru, VL; 5834 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5835 Mask = VPLoad->getMask(); 5836 PassThru = DAG.getUNDEF(VT); 5837 VL = VPLoad->getVectorLength(); 5838 } else { 5839 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5840 Mask = MLoad->getMask(); 5841 PassThru = MLoad->getPassThru(); 5842 } 5843 5844 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5845 5846 MVT XLenVT = Subtarget.getXLenVT(); 5847 5848 MVT ContainerVT = VT; 5849 if (VT.isFixedLengthVector()) { 5850 ContainerVT = getContainerForFixedLengthVector(VT); 5851 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5852 if (!IsUnmasked) { 5853 MVT MaskVT = getMaskTypeFor(ContainerVT); 5854 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5855 } 5856 } 5857 5858 if (!VL) 5859 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5860 5861 unsigned IntID = 5862 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5863 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5864 if (IsUnmasked) 5865 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5866 else 5867 Ops.push_back(PassThru); 5868 Ops.push_back(BasePtr); 5869 if (!IsUnmasked) 5870 Ops.push_back(Mask); 5871 Ops.push_back(VL); 5872 if (!IsUnmasked) 5873 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5874 5875 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5876 5877 SDValue Result = 5878 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5879 Chain = Result.getValue(1); 5880 5881 if (VT.isFixedLengthVector()) 5882 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5883 5884 return DAG.getMergeValues({Result, Chain}, DL); 5885 } 5886 5887 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5888 SelectionDAG &DAG) const { 5889 SDLoc DL(Op); 5890 5891 const auto *MemSD = cast<MemSDNode>(Op); 5892 EVT MemVT = MemSD->getMemoryVT(); 5893 MachineMemOperand *MMO = MemSD->getMemOperand(); 5894 SDValue Chain = MemSD->getChain(); 5895 SDValue BasePtr = MemSD->getBasePtr(); 5896 SDValue Val, Mask, VL; 5897 5898 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5899 Val = VPStore->getValue(); 5900 Mask = VPStore->getMask(); 5901 VL = VPStore->getVectorLength(); 5902 } else { 5903 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5904 Val = MStore->getValue(); 5905 Mask = MStore->getMask(); 5906 } 5907 5908 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5909 5910 MVT VT = Val.getSimpleValueType(); 5911 MVT XLenVT = Subtarget.getXLenVT(); 5912 5913 MVT ContainerVT = VT; 5914 if (VT.isFixedLengthVector()) { 5915 ContainerVT = getContainerForFixedLengthVector(VT); 5916 5917 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5918 if (!IsUnmasked) { 5919 MVT MaskVT = getMaskTypeFor(ContainerVT); 5920 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5921 } 5922 } 5923 5924 if (!VL) 5925 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5926 5927 unsigned IntID = 5928 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5929 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5930 Ops.push_back(Val); 5931 Ops.push_back(BasePtr); 5932 if (!IsUnmasked) 5933 Ops.push_back(Mask); 5934 Ops.push_back(VL); 5935 5936 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5937 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5938 } 5939 5940 SDValue 5941 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5942 SelectionDAG &DAG) const { 5943 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5944 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5945 5946 MVT VT = Op.getSimpleValueType(); 5947 5948 SDValue Op1 = 5949 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5950 SDValue Op2 = 5951 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5952 5953 SDLoc DL(Op); 5954 SDValue VL = 5955 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5956 5957 MVT MaskVT = getMaskTypeFor(ContainerVT); 5958 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 5959 5960 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5961 Op.getOperand(2), Mask, VL); 5962 5963 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5964 } 5965 5966 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5967 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5968 MVT VT = Op.getSimpleValueType(); 5969 5970 if (VT.getVectorElementType() == MVT::i1) 5971 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5972 5973 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5974 } 5975 5976 SDValue 5977 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5978 SelectionDAG &DAG) const { 5979 unsigned Opc; 5980 switch (Op.getOpcode()) { 5981 default: llvm_unreachable("Unexpected opcode!"); 5982 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5983 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5984 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5985 } 5986 5987 return lowerToScalableOp(Op, DAG, Opc); 5988 } 5989 5990 // Lower vector ABS to smax(X, sub(0, X)). 5991 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5992 SDLoc DL(Op); 5993 MVT VT = Op.getSimpleValueType(); 5994 SDValue X = Op.getOperand(0); 5995 5996 assert(VT.isFixedLengthVector() && "Unexpected type"); 5997 5998 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5999 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 6000 6001 SDValue Mask, VL; 6002 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6003 6004 SDValue SplatZero = DAG.getNode( 6005 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 6006 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 6007 SDValue NegX = 6008 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 6009 SDValue Max = 6010 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 6011 6012 return convertFromScalableVector(VT, Max, DAG, Subtarget); 6013 } 6014 6015 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 6016 SDValue Op, SelectionDAG &DAG) const { 6017 SDLoc DL(Op); 6018 MVT VT = Op.getSimpleValueType(); 6019 SDValue Mag = Op.getOperand(0); 6020 SDValue Sign = Op.getOperand(1); 6021 assert(Mag.getValueType() == Sign.getValueType() && 6022 "Can only handle COPYSIGN with matching types."); 6023 6024 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6025 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 6026 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 6027 6028 SDValue Mask, VL; 6029 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6030 6031 SDValue CopySign = 6032 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 6033 6034 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 6035 } 6036 6037 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 6038 SDValue Op, SelectionDAG &DAG) const { 6039 MVT VT = Op.getSimpleValueType(); 6040 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6041 6042 MVT I1ContainerVT = 6043 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6044 6045 SDValue CC = 6046 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 6047 SDValue Op1 = 6048 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 6049 SDValue Op2 = 6050 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 6051 6052 SDLoc DL(Op); 6053 SDValue Mask, VL; 6054 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6055 6056 SDValue Select = 6057 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 6058 6059 return convertFromScalableVector(VT, Select, DAG, Subtarget); 6060 } 6061 6062 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 6063 unsigned NewOpc, 6064 bool HasMask) const { 6065 MVT VT = Op.getSimpleValueType(); 6066 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6067 6068 // Create list of operands by converting existing ones to scalable types. 6069 SmallVector<SDValue, 6> Ops; 6070 for (const SDValue &V : Op->op_values()) { 6071 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6072 6073 // Pass through non-vector operands. 6074 if (!V.getValueType().isVector()) { 6075 Ops.push_back(V); 6076 continue; 6077 } 6078 6079 // "cast" fixed length vector to a scalable vector. 6080 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6081 "Only fixed length vectors are supported!"); 6082 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6083 } 6084 6085 SDLoc DL(Op); 6086 SDValue Mask, VL; 6087 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6088 if (HasMask) 6089 Ops.push_back(Mask); 6090 Ops.push_back(VL); 6091 6092 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6093 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6094 } 6095 6096 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6097 // * Operands of each node are assumed to be in the same order. 6098 // * The EVL operand is promoted from i32 to i64 on RV64. 6099 // * Fixed-length vectors are converted to their scalable-vector container 6100 // types. 6101 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6102 unsigned RISCVISDOpc) const { 6103 SDLoc DL(Op); 6104 MVT VT = Op.getSimpleValueType(); 6105 SmallVector<SDValue, 4> Ops; 6106 6107 for (const auto &OpIdx : enumerate(Op->ops())) { 6108 SDValue V = OpIdx.value(); 6109 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6110 // Pass through operands which aren't fixed-length vectors. 6111 if (!V.getValueType().isFixedLengthVector()) { 6112 Ops.push_back(V); 6113 continue; 6114 } 6115 // "cast" fixed length vector to a scalable vector. 6116 MVT OpVT = V.getSimpleValueType(); 6117 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6118 assert(useRVVForFixedLengthVectorVT(OpVT) && 6119 "Only fixed length vectors are supported!"); 6120 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6121 } 6122 6123 if (!VT.isFixedLengthVector()) 6124 return DAG.getNode(RISCVISDOpc, DL, VT, Ops, Op->getFlags()); 6125 6126 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6127 6128 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops, Op->getFlags()); 6129 6130 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6131 } 6132 6133 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op, 6134 SelectionDAG &DAG) const { 6135 SDLoc DL(Op); 6136 MVT VT = Op.getSimpleValueType(); 6137 6138 SDValue Src = Op.getOperand(0); 6139 // NOTE: Mask is dropped. 6140 SDValue VL = Op.getOperand(2); 6141 6142 MVT ContainerVT = VT; 6143 if (VT.isFixedLengthVector()) { 6144 ContainerVT = getContainerForFixedLengthVector(VT); 6145 MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6146 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6147 } 6148 6149 MVT XLenVT = Subtarget.getXLenVT(); 6150 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6151 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6152 DAG.getUNDEF(ContainerVT), Zero, VL); 6153 6154 SDValue SplatValue = DAG.getConstant( 6155 Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT); 6156 SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6157 DAG.getUNDEF(ContainerVT), SplatValue, VL); 6158 6159 SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src, 6160 Splat, ZeroSplat, VL); 6161 if (!VT.isFixedLengthVector()) 6162 return Result; 6163 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6164 } 6165 6166 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op, 6167 SelectionDAG &DAG) const { 6168 SDLoc DL(Op); 6169 MVT VT = Op.getSimpleValueType(); 6170 6171 SDValue Op1 = Op.getOperand(0); 6172 SDValue Op2 = Op.getOperand(1); 6173 ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 6174 // NOTE: Mask is dropped. 6175 SDValue VL = Op.getOperand(4); 6176 6177 MVT ContainerVT = VT; 6178 if (VT.isFixedLengthVector()) { 6179 ContainerVT = getContainerForFixedLengthVector(VT); 6180 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6181 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6182 } 6183 6184 SDValue Result; 6185 SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 6186 6187 switch (Condition) { 6188 default: 6189 break; 6190 // X != Y --> (X^Y) 6191 case ISD::SETNE: 6192 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6193 break; 6194 // X == Y --> ~(X^Y) 6195 case ISD::SETEQ: { 6196 SDValue Temp = 6197 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6198 Result = 6199 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL); 6200 break; 6201 } 6202 // X >s Y --> X == 0 & Y == 1 --> ~X & Y 6203 // X <u Y --> X == 0 & Y == 1 --> ~X & Y 6204 case ISD::SETGT: 6205 case ISD::SETULT: { 6206 SDValue Temp = 6207 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6208 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL); 6209 break; 6210 } 6211 // X <s Y --> X == 1 & Y == 0 --> ~Y & X 6212 // X >u Y --> X == 1 & Y == 0 --> ~Y & X 6213 case ISD::SETLT: 6214 case ISD::SETUGT: { 6215 SDValue Temp = 6216 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6217 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL); 6218 break; 6219 } 6220 // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 6221 // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 6222 case ISD::SETGE: 6223 case ISD::SETULE: { 6224 SDValue Temp = 6225 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6226 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL); 6227 break; 6228 } 6229 // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 6230 // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 6231 case ISD::SETLE: 6232 case ISD::SETUGE: { 6233 SDValue Temp = 6234 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6235 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL); 6236 break; 6237 } 6238 } 6239 6240 if (!VT.isFixedLengthVector()) 6241 return Result; 6242 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6243 } 6244 6245 // Lower Floating-Point/Integer Type-Convert VP SDNodes 6246 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG, 6247 unsigned RISCVISDOpc) const { 6248 SDLoc DL(Op); 6249 6250 SDValue Src = Op.getOperand(0); 6251 SDValue Mask = Op.getOperand(1); 6252 SDValue VL = Op.getOperand(2); 6253 6254 MVT DstVT = Op.getSimpleValueType(); 6255 MVT SrcVT = Src.getSimpleValueType(); 6256 if (DstVT.isFixedLengthVector()) { 6257 DstVT = getContainerForFixedLengthVector(DstVT); 6258 SrcVT = getContainerForFixedLengthVector(SrcVT); 6259 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6260 MVT MaskVT = getMaskTypeFor(DstVT); 6261 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6262 } 6263 6264 unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL || 6265 RISCVISDOpc == RISCVISD::FP_TO_SINT_VL) 6266 ? RISCVISD::VSEXT_VL 6267 : RISCVISD::VZEXT_VL; 6268 6269 unsigned DstEltSize = DstVT.getScalarSizeInBits(); 6270 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 6271 6272 SDValue Result; 6273 if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion. 6274 if (SrcVT.isInteger()) { 6275 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6276 6277 // Do we need to do any pre-widening before converting? 6278 if (SrcEltSize == 1) { 6279 MVT IntVT = DstVT.changeVectorElementTypeToInteger(); 6280 MVT XLenVT = Subtarget.getXLenVT(); 6281 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6282 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6283 DAG.getUNDEF(IntVT), Zero, VL); 6284 SDValue One = DAG.getConstant( 6285 RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT); 6286 SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6287 DAG.getUNDEF(IntVT), One, VL); 6288 Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat, 6289 ZeroSplat, VL); 6290 } else if (DstEltSize > (2 * SrcEltSize)) { 6291 // Widen before converting. 6292 MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2), 6293 DstVT.getVectorElementCount()); 6294 Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL); 6295 } 6296 6297 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6298 } else { 6299 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6300 "Wrong input/output vector types"); 6301 6302 // Convert f16 to f32 then convert f32 to i64. 6303 if (DstEltSize > (2 * SrcEltSize)) { 6304 assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6305 MVT InterimFVT = 6306 MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6307 Src = 6308 DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL); 6309 } 6310 6311 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6312 } 6313 } else { // Narrowing + Conversion 6314 if (SrcVT.isInteger()) { 6315 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6316 // First do a narrowing convert to an FP type half the size, then round 6317 // the FP type to a small FP type if needed. 6318 6319 MVT InterimFVT = DstVT; 6320 if (SrcEltSize > (2 * DstEltSize)) { 6321 assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!"); 6322 assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6323 InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6324 } 6325 6326 Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL); 6327 6328 if (InterimFVT != DstVT) { 6329 Src = Result; 6330 Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL); 6331 } 6332 } else { 6333 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6334 "Wrong input/output vector types"); 6335 // First do a narrowing conversion to an integer half the size, then 6336 // truncate if needed. 6337 6338 if (DstEltSize == 1) { 6339 // First convert to the same size integer, then convert to mask using 6340 // setcc. 6341 assert(SrcEltSize >= 16 && "Unexpected FP type!"); 6342 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize), 6343 DstVT.getVectorElementCount()); 6344 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6345 6346 // Compare the integer result to 0. The integer should be 0 or 1/-1, 6347 // otherwise the conversion was undefined. 6348 MVT XLenVT = Subtarget.getXLenVT(); 6349 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 6350 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT, 6351 DAG.getUNDEF(InterimIVT), SplatZero); 6352 Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero, 6353 DAG.getCondCode(ISD::SETNE), Mask, VL); 6354 } else { 6355 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6356 DstVT.getVectorElementCount()); 6357 6358 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6359 6360 while (InterimIVT != DstVT) { 6361 SrcEltSize /= 2; 6362 Src = Result; 6363 InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6364 DstVT.getVectorElementCount()); 6365 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT, 6366 Src, Mask, VL); 6367 } 6368 } 6369 } 6370 } 6371 6372 MVT VT = Op.getSimpleValueType(); 6373 if (!VT.isFixedLengthVector()) 6374 return Result; 6375 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6376 } 6377 6378 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6379 unsigned MaskOpc, 6380 unsigned VecOpc) const { 6381 MVT VT = Op.getSimpleValueType(); 6382 if (VT.getVectorElementType() != MVT::i1) 6383 return lowerVPOp(Op, DAG, VecOpc); 6384 6385 // It is safe to drop mask parameter as masked-off elements are undef. 6386 SDValue Op1 = Op->getOperand(0); 6387 SDValue Op2 = Op->getOperand(1); 6388 SDValue VL = Op->getOperand(3); 6389 6390 MVT ContainerVT = VT; 6391 const bool IsFixed = VT.isFixedLengthVector(); 6392 if (IsFixed) { 6393 ContainerVT = getContainerForFixedLengthVector(VT); 6394 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6395 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6396 } 6397 6398 SDLoc DL(Op); 6399 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6400 if (!IsFixed) 6401 return Val; 6402 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6403 } 6404 6405 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6406 // matched to a RVV indexed load. The RVV indexed load instructions only 6407 // support the "unsigned unscaled" addressing mode; indices are implicitly 6408 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6409 // signed or scaled indexing is extended to the XLEN value type and scaled 6410 // accordingly. 6411 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6412 SelectionDAG &DAG) const { 6413 SDLoc DL(Op); 6414 MVT VT = Op.getSimpleValueType(); 6415 6416 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6417 EVT MemVT = MemSD->getMemoryVT(); 6418 MachineMemOperand *MMO = MemSD->getMemOperand(); 6419 SDValue Chain = MemSD->getChain(); 6420 SDValue BasePtr = MemSD->getBasePtr(); 6421 6422 ISD::LoadExtType LoadExtType; 6423 SDValue Index, Mask, PassThru, VL; 6424 6425 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6426 Index = VPGN->getIndex(); 6427 Mask = VPGN->getMask(); 6428 PassThru = DAG.getUNDEF(VT); 6429 VL = VPGN->getVectorLength(); 6430 // VP doesn't support extending loads. 6431 LoadExtType = ISD::NON_EXTLOAD; 6432 } else { 6433 // Else it must be a MGATHER. 6434 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6435 Index = MGN->getIndex(); 6436 Mask = MGN->getMask(); 6437 PassThru = MGN->getPassThru(); 6438 LoadExtType = MGN->getExtensionType(); 6439 } 6440 6441 MVT IndexVT = Index.getSimpleValueType(); 6442 MVT XLenVT = Subtarget.getXLenVT(); 6443 6444 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6445 "Unexpected VTs!"); 6446 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6447 // Targets have to explicitly opt-in for extending vector loads. 6448 assert(LoadExtType == ISD::NON_EXTLOAD && 6449 "Unexpected extending MGATHER/VP_GATHER"); 6450 (void)LoadExtType; 6451 6452 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6453 // the selection of the masked intrinsics doesn't do this for us. 6454 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6455 6456 MVT ContainerVT = VT; 6457 if (VT.isFixedLengthVector()) { 6458 ContainerVT = getContainerForFixedLengthVector(VT); 6459 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6460 ContainerVT.getVectorElementCount()); 6461 6462 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6463 6464 if (!IsUnmasked) { 6465 MVT MaskVT = getMaskTypeFor(ContainerVT); 6466 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6467 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6468 } 6469 } 6470 6471 if (!VL) 6472 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6473 6474 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6475 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6476 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6477 VL); 6478 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6479 TrueMask, VL); 6480 } 6481 6482 unsigned IntID = 6483 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6484 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6485 if (IsUnmasked) 6486 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6487 else 6488 Ops.push_back(PassThru); 6489 Ops.push_back(BasePtr); 6490 Ops.push_back(Index); 6491 if (!IsUnmasked) 6492 Ops.push_back(Mask); 6493 Ops.push_back(VL); 6494 if (!IsUnmasked) 6495 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6496 6497 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6498 SDValue Result = 6499 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6500 Chain = Result.getValue(1); 6501 6502 if (VT.isFixedLengthVector()) 6503 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6504 6505 return DAG.getMergeValues({Result, Chain}, DL); 6506 } 6507 6508 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6509 // matched to a RVV indexed store. The RVV indexed store instructions only 6510 // support the "unsigned unscaled" addressing mode; indices are implicitly 6511 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6512 // signed or scaled indexing is extended to the XLEN value type and scaled 6513 // accordingly. 6514 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6515 SelectionDAG &DAG) const { 6516 SDLoc DL(Op); 6517 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6518 EVT MemVT = MemSD->getMemoryVT(); 6519 MachineMemOperand *MMO = MemSD->getMemOperand(); 6520 SDValue Chain = MemSD->getChain(); 6521 SDValue BasePtr = MemSD->getBasePtr(); 6522 6523 bool IsTruncatingStore = false; 6524 SDValue Index, Mask, Val, VL; 6525 6526 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6527 Index = VPSN->getIndex(); 6528 Mask = VPSN->getMask(); 6529 Val = VPSN->getValue(); 6530 VL = VPSN->getVectorLength(); 6531 // VP doesn't support truncating stores. 6532 IsTruncatingStore = false; 6533 } else { 6534 // Else it must be a MSCATTER. 6535 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6536 Index = MSN->getIndex(); 6537 Mask = MSN->getMask(); 6538 Val = MSN->getValue(); 6539 IsTruncatingStore = MSN->isTruncatingStore(); 6540 } 6541 6542 MVT VT = Val.getSimpleValueType(); 6543 MVT IndexVT = Index.getSimpleValueType(); 6544 MVT XLenVT = Subtarget.getXLenVT(); 6545 6546 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6547 "Unexpected VTs!"); 6548 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6549 // Targets have to explicitly opt-in for extending vector loads and 6550 // truncating vector stores. 6551 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6552 (void)IsTruncatingStore; 6553 6554 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6555 // the selection of the masked intrinsics doesn't do this for us. 6556 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6557 6558 MVT ContainerVT = VT; 6559 if (VT.isFixedLengthVector()) { 6560 ContainerVT = getContainerForFixedLengthVector(VT); 6561 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6562 ContainerVT.getVectorElementCount()); 6563 6564 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6565 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6566 6567 if (!IsUnmasked) { 6568 MVT MaskVT = getMaskTypeFor(ContainerVT); 6569 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6570 } 6571 } 6572 6573 if (!VL) 6574 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6575 6576 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6577 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6578 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6579 VL); 6580 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6581 TrueMask, VL); 6582 } 6583 6584 unsigned IntID = 6585 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6586 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6587 Ops.push_back(Val); 6588 Ops.push_back(BasePtr); 6589 Ops.push_back(Index); 6590 if (!IsUnmasked) 6591 Ops.push_back(Mask); 6592 Ops.push_back(VL); 6593 6594 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6595 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6596 } 6597 6598 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6599 SelectionDAG &DAG) const { 6600 const MVT XLenVT = Subtarget.getXLenVT(); 6601 SDLoc DL(Op); 6602 SDValue Chain = Op->getOperand(0); 6603 SDValue SysRegNo = DAG.getTargetConstant( 6604 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6605 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6606 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6607 6608 // Encoding used for rounding mode in RISCV differs from that used in 6609 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6610 // table, which consists of a sequence of 4-bit fields, each representing 6611 // corresponding FLT_ROUNDS mode. 6612 static const int Table = 6613 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6614 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6615 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6616 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6617 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6618 6619 SDValue Shift = 6620 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6621 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6622 DAG.getConstant(Table, DL, XLenVT), Shift); 6623 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6624 DAG.getConstant(7, DL, XLenVT)); 6625 6626 return DAG.getMergeValues({Masked, Chain}, DL); 6627 } 6628 6629 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6630 SelectionDAG &DAG) const { 6631 const MVT XLenVT = Subtarget.getXLenVT(); 6632 SDLoc DL(Op); 6633 SDValue Chain = Op->getOperand(0); 6634 SDValue RMValue = Op->getOperand(1); 6635 SDValue SysRegNo = DAG.getTargetConstant( 6636 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6637 6638 // Encoding used for rounding mode in RISCV differs from that used in 6639 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6640 // a table, which consists of a sequence of 4-bit fields, each representing 6641 // corresponding RISCV mode. 6642 static const unsigned Table = 6643 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6644 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6645 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6646 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6647 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6648 6649 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6650 DAG.getConstant(2, DL, XLenVT)); 6651 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6652 DAG.getConstant(Table, DL, XLenVT), Shift); 6653 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6654 DAG.getConstant(0x7, DL, XLenVT)); 6655 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6656 RMValue); 6657 } 6658 6659 SDValue RISCVTargetLowering::lowerEH_DWARF_CFA(SDValue Op, 6660 SelectionDAG &DAG) const { 6661 MachineFunction &MF = DAG.getMachineFunction(); 6662 6663 bool isRISCV64 = Subtarget.is64Bit(); 6664 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6665 6666 int FI = MF.getFrameInfo().CreateFixedObject(isRISCV64 ? 8 : 4, 0, false); 6667 return DAG.getFrameIndex(FI, PtrVT); 6668 } 6669 6670 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6671 switch (IntNo) { 6672 default: 6673 llvm_unreachable("Unexpected Intrinsic"); 6674 case Intrinsic::riscv_bcompress: 6675 return RISCVISD::BCOMPRESSW; 6676 case Intrinsic::riscv_bdecompress: 6677 return RISCVISD::BDECOMPRESSW; 6678 case Intrinsic::riscv_bfp: 6679 return RISCVISD::BFPW; 6680 case Intrinsic::riscv_fsl: 6681 return RISCVISD::FSLW; 6682 case Intrinsic::riscv_fsr: 6683 return RISCVISD::FSRW; 6684 } 6685 } 6686 6687 // Converts the given intrinsic to a i64 operation with any extension. 6688 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6689 unsigned IntNo) { 6690 SDLoc DL(N); 6691 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6692 // Deal with the Instruction Operands 6693 SmallVector<SDValue, 3> NewOps; 6694 for (SDValue Op : drop_begin(N->ops())) 6695 // Promote the operand to i64 type 6696 NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op)); 6697 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps); 6698 // ReplaceNodeResults requires we maintain the same type for the return value. 6699 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6700 } 6701 6702 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6703 // form of the given Opcode. 6704 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6705 switch (Opcode) { 6706 default: 6707 llvm_unreachable("Unexpected opcode"); 6708 case ISD::SHL: 6709 return RISCVISD::SLLW; 6710 case ISD::SRA: 6711 return RISCVISD::SRAW; 6712 case ISD::SRL: 6713 return RISCVISD::SRLW; 6714 case ISD::SDIV: 6715 return RISCVISD::DIVW; 6716 case ISD::UDIV: 6717 return RISCVISD::DIVUW; 6718 case ISD::UREM: 6719 return RISCVISD::REMUW; 6720 case ISD::ROTL: 6721 return RISCVISD::ROLW; 6722 case ISD::ROTR: 6723 return RISCVISD::RORW; 6724 } 6725 } 6726 6727 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6728 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6729 // otherwise be promoted to i64, making it difficult to select the 6730 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6731 // type i8/i16/i32 is lost. 6732 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6733 unsigned ExtOpc = ISD::ANY_EXTEND) { 6734 SDLoc DL(N); 6735 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6736 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6737 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6738 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6739 // ReplaceNodeResults requires we maintain the same type for the return value. 6740 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6741 } 6742 6743 // Converts the given 32-bit operation to a i64 operation with signed extension 6744 // semantic to reduce the signed extension instructions. 6745 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6746 SDLoc DL(N); 6747 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6748 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6749 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6750 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6751 DAG.getValueType(MVT::i32)); 6752 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6753 } 6754 6755 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6756 SmallVectorImpl<SDValue> &Results, 6757 SelectionDAG &DAG) const { 6758 SDLoc DL(N); 6759 switch (N->getOpcode()) { 6760 default: 6761 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6762 case ISD::STRICT_FP_TO_SINT: 6763 case ISD::STRICT_FP_TO_UINT: 6764 case ISD::FP_TO_SINT: 6765 case ISD::FP_TO_UINT: { 6766 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6767 "Unexpected custom legalisation"); 6768 bool IsStrict = N->isStrictFPOpcode(); 6769 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6770 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6771 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6772 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6773 TargetLowering::TypeSoftenFloat) { 6774 if (!isTypeLegal(Op0.getValueType())) 6775 return; 6776 if (IsStrict) { 6777 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6778 : RISCVISD::STRICT_FCVT_WU_RV64; 6779 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6780 SDValue Res = DAG.getNode( 6781 Opc, DL, VTs, N->getOperand(0), Op0, 6782 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6783 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6784 Results.push_back(Res.getValue(1)); 6785 return; 6786 } 6787 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6788 SDValue Res = 6789 DAG.getNode(Opc, DL, MVT::i64, Op0, 6790 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6791 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6792 return; 6793 } 6794 // If the FP type needs to be softened, emit a library call using the 'si' 6795 // version. If we left it to default legalization we'd end up with 'di'. If 6796 // the FP type doesn't need to be softened just let generic type 6797 // legalization promote the result type. 6798 RTLIB::Libcall LC; 6799 if (IsSigned) 6800 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6801 else 6802 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6803 MakeLibCallOptions CallOptions; 6804 EVT OpVT = Op0.getValueType(); 6805 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6806 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6807 SDValue Result; 6808 std::tie(Result, Chain) = 6809 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6810 Results.push_back(Result); 6811 if (IsStrict) 6812 Results.push_back(Chain); 6813 break; 6814 } 6815 case ISD::READCYCLECOUNTER: { 6816 assert(!Subtarget.is64Bit() && 6817 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6818 6819 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6820 SDValue RCW = 6821 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6822 6823 Results.push_back( 6824 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6825 Results.push_back(RCW.getValue(2)); 6826 break; 6827 } 6828 case ISD::MUL: { 6829 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6830 unsigned XLen = Subtarget.getXLen(); 6831 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6832 if (Size > XLen) { 6833 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6834 SDValue LHS = N->getOperand(0); 6835 SDValue RHS = N->getOperand(1); 6836 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6837 6838 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6839 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6840 // We need exactly one side to be unsigned. 6841 if (LHSIsU == RHSIsU) 6842 return; 6843 6844 auto MakeMULPair = [&](SDValue S, SDValue U) { 6845 MVT XLenVT = Subtarget.getXLenVT(); 6846 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6847 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6848 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6849 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6850 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6851 }; 6852 6853 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6854 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6855 6856 // The other operand should be signed, but still prefer MULH when 6857 // possible. 6858 if (RHSIsU && LHSIsS && !RHSIsS) 6859 Results.push_back(MakeMULPair(LHS, RHS)); 6860 else if (LHSIsU && RHSIsS && !LHSIsS) 6861 Results.push_back(MakeMULPair(RHS, LHS)); 6862 6863 return; 6864 } 6865 LLVM_FALLTHROUGH; 6866 } 6867 case ISD::ADD: 6868 case ISD::SUB: 6869 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6870 "Unexpected custom legalisation"); 6871 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6872 break; 6873 case ISD::SHL: 6874 case ISD::SRA: 6875 case ISD::SRL: 6876 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6877 "Unexpected custom legalisation"); 6878 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6879 // If we can use a BSET instruction, allow default promotion to apply. 6880 if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() && 6881 isOneConstant(N->getOperand(0))) 6882 break; 6883 Results.push_back(customLegalizeToWOp(N, DAG)); 6884 break; 6885 } 6886 6887 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6888 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6889 // shift amount. 6890 if (N->getOpcode() == ISD::SHL) { 6891 SDLoc DL(N); 6892 SDValue NewOp0 = 6893 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6894 SDValue NewOp1 = 6895 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6896 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6897 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6898 DAG.getValueType(MVT::i32)); 6899 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6900 } 6901 6902 break; 6903 case ISD::ROTL: 6904 case ISD::ROTR: 6905 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6906 "Unexpected custom legalisation"); 6907 Results.push_back(customLegalizeToWOp(N, DAG)); 6908 break; 6909 case ISD::CTTZ: 6910 case ISD::CTTZ_ZERO_UNDEF: 6911 case ISD::CTLZ: 6912 case ISD::CTLZ_ZERO_UNDEF: { 6913 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6914 "Unexpected custom legalisation"); 6915 6916 SDValue NewOp0 = 6917 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6918 bool IsCTZ = 6919 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6920 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6921 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6922 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6923 return; 6924 } 6925 case ISD::SDIV: 6926 case ISD::UDIV: 6927 case ISD::UREM: { 6928 MVT VT = N->getSimpleValueType(0); 6929 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6930 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6931 "Unexpected custom legalisation"); 6932 // Don't promote division/remainder by constant since we should expand those 6933 // to multiply by magic constant. 6934 // FIXME: What if the expansion is disabled for minsize. 6935 if (N->getOperand(1).getOpcode() == ISD::Constant) 6936 return; 6937 6938 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6939 // the upper 32 bits. For other types we need to sign or zero extend 6940 // based on the opcode. 6941 unsigned ExtOpc = ISD::ANY_EXTEND; 6942 if (VT != MVT::i32) 6943 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6944 : ISD::ZERO_EXTEND; 6945 6946 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6947 break; 6948 } 6949 case ISD::UADDO: 6950 case ISD::USUBO: { 6951 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6952 "Unexpected custom legalisation"); 6953 bool IsAdd = N->getOpcode() == ISD::UADDO; 6954 // Create an ADDW or SUBW. 6955 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6956 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6957 SDValue Res = 6958 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6959 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6960 DAG.getValueType(MVT::i32)); 6961 6962 SDValue Overflow; 6963 if (IsAdd && isOneConstant(RHS)) { 6964 // Special case uaddo X, 1 overflowed if the addition result is 0. 6965 // The general case (X + C) < C is not necessarily beneficial. Although we 6966 // reduce the live range of X, we may introduce the materialization of 6967 // constant C, especially when the setcc result is used by branch. We have 6968 // no compare with constant and branch instructions. 6969 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, 6970 DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ); 6971 } else { 6972 // Sign extend the LHS and perform an unsigned compare with the ADDW 6973 // result. Since the inputs are sign extended from i32, this is equivalent 6974 // to comparing the lower 32 bits. 6975 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6976 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6977 IsAdd ? ISD::SETULT : ISD::SETUGT); 6978 } 6979 6980 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6981 Results.push_back(Overflow); 6982 return; 6983 } 6984 case ISD::UADDSAT: 6985 case ISD::USUBSAT: { 6986 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6987 "Unexpected custom legalisation"); 6988 if (Subtarget.hasStdExtZbb()) { 6989 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6990 // sign extend allows overflow of the lower 32 bits to be detected on 6991 // the promoted size. 6992 SDValue LHS = 6993 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6994 SDValue RHS = 6995 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6996 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6997 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6998 return; 6999 } 7000 7001 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 7002 // promotion for UADDO/USUBO. 7003 Results.push_back(expandAddSubSat(N, DAG)); 7004 return; 7005 } 7006 case ISD::ABS: { 7007 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7008 "Unexpected custom legalisation"); 7009 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 7010 7011 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 7012 7013 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7014 7015 // Freeze the source so we can increase it's use count. 7016 Src = DAG.getFreeze(Src); 7017 7018 // Copy sign bit to all bits using the sraiw pattern. 7019 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 7020 DAG.getValueType(MVT::i32)); 7021 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 7022 DAG.getConstant(31, DL, MVT::i64)); 7023 7024 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 7025 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 7026 7027 // NOTE: The result is only required to be anyextended, but sext is 7028 // consistent with type legalization of sub. 7029 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 7030 DAG.getValueType(MVT::i32)); 7031 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 7032 return; 7033 } 7034 case ISD::BITCAST: { 7035 EVT VT = N->getValueType(0); 7036 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 7037 SDValue Op0 = N->getOperand(0); 7038 EVT Op0VT = Op0.getValueType(); 7039 MVT XLenVT = Subtarget.getXLenVT(); 7040 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 7041 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 7042 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 7043 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 7044 Subtarget.hasStdExtF()) { 7045 SDValue FPConv = 7046 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 7047 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 7048 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 7049 isTypeLegal(Op0VT)) { 7050 // Custom-legalize bitcasts from fixed-length vector types to illegal 7051 // scalar types in order to improve codegen. Bitcast the vector to a 7052 // one-element vector type whose element type is the same as the result 7053 // type, and extract the first element. 7054 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 7055 if (isTypeLegal(BVT)) { 7056 SDValue BVec = DAG.getBitcast(BVT, Op0); 7057 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 7058 DAG.getConstant(0, DL, XLenVT))); 7059 } 7060 } 7061 break; 7062 } 7063 case RISCVISD::GREV: 7064 case RISCVISD::GORC: 7065 case RISCVISD::SHFL: { 7066 MVT VT = N->getSimpleValueType(0); 7067 MVT XLenVT = Subtarget.getXLenVT(); 7068 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) && 7069 "Unexpected custom legalisation"); 7070 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 7071 assert((Subtarget.hasStdExtZbp() || 7072 (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV && 7073 N->getConstantOperandVal(1) == 7)) && 7074 "Unexpected extension"); 7075 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7076 SDValue NewOp1 = 7077 DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1)); 7078 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1); 7079 // ReplaceNodeResults requires we maintain the same type for the return 7080 // value. 7081 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes)); 7082 break; 7083 } 7084 case ISD::BSWAP: 7085 case ISD::BITREVERSE: { 7086 MVT VT = N->getSimpleValueType(0); 7087 MVT XLenVT = Subtarget.getXLenVT(); 7088 assert((VT == MVT::i8 || VT == MVT::i16 || 7089 (VT == MVT::i32 && Subtarget.is64Bit())) && 7090 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 7091 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7092 unsigned Imm = VT.getSizeInBits() - 1; 7093 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 7094 if (N->getOpcode() == ISD::BSWAP) 7095 Imm &= ~0x7U; 7096 SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0, 7097 DAG.getConstant(Imm, DL, XLenVT)); 7098 // ReplaceNodeResults requires we maintain the same type for the return 7099 // value. 7100 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 7101 break; 7102 } 7103 case ISD::FSHL: 7104 case ISD::FSHR: { 7105 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7106 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 7107 SDValue NewOp0 = 7108 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7109 SDValue NewOp1 = 7110 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7111 SDValue NewShAmt = 7112 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7113 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 7114 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 7115 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 7116 DAG.getConstant(0x1f, DL, MVT::i64)); 7117 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 7118 // instruction use different orders. fshl will return its first operand for 7119 // shift of zero, fshr will return its second operand. fsl and fsr both 7120 // return rs1 so the ISD nodes need to have different operand orders. 7121 // Shift amount is in rs2. 7122 unsigned Opc = RISCVISD::FSLW; 7123 if (N->getOpcode() == ISD::FSHR) { 7124 std::swap(NewOp0, NewOp1); 7125 Opc = RISCVISD::FSRW; 7126 } 7127 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 7128 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 7129 break; 7130 } 7131 case ISD::EXTRACT_VECTOR_ELT: { 7132 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 7133 // type is illegal (currently only vXi64 RV32). 7134 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 7135 // transferred to the destination register. We issue two of these from the 7136 // upper- and lower- halves of the SEW-bit vector element, slid down to the 7137 // first element. 7138 SDValue Vec = N->getOperand(0); 7139 SDValue Idx = N->getOperand(1); 7140 7141 // The vector type hasn't been legalized yet so we can't issue target 7142 // specific nodes if it needs legalization. 7143 // FIXME: We would manually legalize if it's important. 7144 if (!isTypeLegal(Vec.getValueType())) 7145 return; 7146 7147 MVT VecVT = Vec.getSimpleValueType(); 7148 7149 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 7150 VecVT.getVectorElementType() == MVT::i64 && 7151 "Unexpected EXTRACT_VECTOR_ELT legalization"); 7152 7153 // If this is a fixed vector, we need to convert it to a scalable vector. 7154 MVT ContainerVT = VecVT; 7155 if (VecVT.isFixedLengthVector()) { 7156 ContainerVT = getContainerForFixedLengthVector(VecVT); 7157 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 7158 } 7159 7160 MVT XLenVT = Subtarget.getXLenVT(); 7161 7162 // Use a VL of 1 to avoid processing more elements than we need. 7163 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7164 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 7165 7166 // Unless the index is known to be 0, we must slide the vector down to get 7167 // the desired element into index 0. 7168 if (!isNullConstant(Idx)) { 7169 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 7170 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 7171 } 7172 7173 // Extract the lower XLEN bits of the correct vector element. 7174 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7175 7176 // To extract the upper XLEN bits of the vector element, shift the first 7177 // element right by 32 bits and re-extract the lower XLEN bits. 7178 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 7179 DAG.getUNDEF(ContainerVT), 7180 DAG.getConstant(32, DL, XLenVT), VL); 7181 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 7182 ThirtyTwoV, Mask, VL); 7183 7184 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7185 7186 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7187 break; 7188 } 7189 case ISD::INTRINSIC_WO_CHAIN: { 7190 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7191 switch (IntNo) { 7192 default: 7193 llvm_unreachable( 7194 "Don't know how to custom type legalize this intrinsic!"); 7195 case Intrinsic::riscv_grev: 7196 case Intrinsic::riscv_gorc: { 7197 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7198 "Unexpected custom legalisation"); 7199 SDValue NewOp1 = 7200 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7201 SDValue NewOp2 = 7202 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7203 unsigned Opc = 7204 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 7205 // If the control is a constant, promote the node by clearing any extra 7206 // bits bits in the control. isel will form greviw/gorciw if the result is 7207 // sign extended. 7208 if (isa<ConstantSDNode>(NewOp2)) { 7209 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7210 DAG.getConstant(0x1f, DL, MVT::i64)); 7211 Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 7212 } 7213 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7214 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7215 break; 7216 } 7217 case Intrinsic::riscv_bcompress: 7218 case Intrinsic::riscv_bdecompress: 7219 case Intrinsic::riscv_bfp: 7220 case Intrinsic::riscv_fsl: 7221 case Intrinsic::riscv_fsr: { 7222 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7223 "Unexpected custom legalisation"); 7224 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 7225 break; 7226 } 7227 case Intrinsic::riscv_orc_b: { 7228 // Lower to the GORCI encoding for orc.b with the operand extended. 7229 SDValue NewOp = 7230 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7231 SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp, 7232 DAG.getConstant(7, DL, MVT::i64)); 7233 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7234 return; 7235 } 7236 case Intrinsic::riscv_shfl: 7237 case Intrinsic::riscv_unshfl: { 7238 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7239 "Unexpected custom legalisation"); 7240 SDValue NewOp1 = 7241 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7242 SDValue NewOp2 = 7243 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7244 unsigned Opc = 7245 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 7246 // There is no (UN)SHFLIW. If the control word is a constant, we can use 7247 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 7248 // will be shuffled the same way as the lower 32 bit half, but the two 7249 // halves won't cross. 7250 if (isa<ConstantSDNode>(NewOp2)) { 7251 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7252 DAG.getConstant(0xf, DL, MVT::i64)); 7253 Opc = 7254 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 7255 } 7256 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7257 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7258 break; 7259 } 7260 case Intrinsic::riscv_vmv_x_s: { 7261 EVT VT = N->getValueType(0); 7262 MVT XLenVT = Subtarget.getXLenVT(); 7263 if (VT.bitsLT(XLenVT)) { 7264 // Simple case just extract using vmv.x.s and truncate. 7265 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 7266 Subtarget.getXLenVT(), N->getOperand(1)); 7267 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 7268 return; 7269 } 7270 7271 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 7272 "Unexpected custom legalization"); 7273 7274 // We need to do the move in two steps. 7275 SDValue Vec = N->getOperand(1); 7276 MVT VecVT = Vec.getSimpleValueType(); 7277 7278 // First extract the lower XLEN bits of the element. 7279 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7280 7281 // To extract the upper XLEN bits of the vector element, shift the first 7282 // element right by 32 bits and re-extract the lower XLEN bits. 7283 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7284 SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG); 7285 7286 SDValue ThirtyTwoV = 7287 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 7288 DAG.getConstant(32, DL, XLenVT), VL); 7289 SDValue LShr32 = 7290 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 7291 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7292 7293 Results.push_back( 7294 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7295 break; 7296 } 7297 } 7298 break; 7299 } 7300 case ISD::VECREDUCE_ADD: 7301 case ISD::VECREDUCE_AND: 7302 case ISD::VECREDUCE_OR: 7303 case ISD::VECREDUCE_XOR: 7304 case ISD::VECREDUCE_SMAX: 7305 case ISD::VECREDUCE_UMAX: 7306 case ISD::VECREDUCE_SMIN: 7307 case ISD::VECREDUCE_UMIN: 7308 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 7309 Results.push_back(V); 7310 break; 7311 case ISD::VP_REDUCE_ADD: 7312 case ISD::VP_REDUCE_AND: 7313 case ISD::VP_REDUCE_OR: 7314 case ISD::VP_REDUCE_XOR: 7315 case ISD::VP_REDUCE_SMAX: 7316 case ISD::VP_REDUCE_UMAX: 7317 case ISD::VP_REDUCE_SMIN: 7318 case ISD::VP_REDUCE_UMIN: 7319 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 7320 Results.push_back(V); 7321 break; 7322 case ISD::FLT_ROUNDS_: { 7323 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7324 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7325 Results.push_back(Res.getValue(0)); 7326 Results.push_back(Res.getValue(1)); 7327 break; 7328 } 7329 } 7330 } 7331 7332 // A structure to hold one of the bit-manipulation patterns below. Together, a 7333 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7334 // (or (and (shl x, 1), 0xAAAAAAAA), 7335 // (and (srl x, 1), 0x55555555)) 7336 struct RISCVBitmanipPat { 7337 SDValue Op; 7338 unsigned ShAmt; 7339 bool IsSHL; 7340 7341 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7342 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7343 } 7344 }; 7345 7346 // Matches patterns of the form 7347 // (and (shl x, C2), (C1 << C2)) 7348 // (and (srl x, C2), C1) 7349 // (shl (and x, C1), C2) 7350 // (srl (and x, (C1 << C2)), C2) 7351 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7352 // The expected masks for each shift amount are specified in BitmanipMasks where 7353 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7354 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7355 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7356 // XLen is 64. 7357 static Optional<RISCVBitmanipPat> 7358 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7359 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7360 "Unexpected number of masks"); 7361 Optional<uint64_t> Mask; 7362 // Optionally consume a mask around the shift operation. 7363 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7364 Mask = Op.getConstantOperandVal(1); 7365 Op = Op.getOperand(0); 7366 } 7367 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7368 return None; 7369 bool IsSHL = Op.getOpcode() == ISD::SHL; 7370 7371 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7372 return None; 7373 uint64_t ShAmt = Op.getConstantOperandVal(1); 7374 7375 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7376 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7377 return None; 7378 // If we don't have enough masks for 64 bit, then we must be trying to 7379 // match SHFL so we're only allowed to shift 1/4 of the width. 7380 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7381 return None; 7382 7383 SDValue Src = Op.getOperand(0); 7384 7385 // The expected mask is shifted left when the AND is found around SHL 7386 // patterns. 7387 // ((x >> 1) & 0x55555555) 7388 // ((x << 1) & 0xAAAAAAAA) 7389 bool SHLExpMask = IsSHL; 7390 7391 if (!Mask) { 7392 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7393 // the mask is all ones: consume that now. 7394 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7395 Mask = Src.getConstantOperandVal(1); 7396 Src = Src.getOperand(0); 7397 // The expected mask is now in fact shifted left for SRL, so reverse the 7398 // decision. 7399 // ((x & 0xAAAAAAAA) >> 1) 7400 // ((x & 0x55555555) << 1) 7401 SHLExpMask = !SHLExpMask; 7402 } else { 7403 // Use a default shifted mask of all-ones if there's no AND, truncated 7404 // down to the expected width. This simplifies the logic later on. 7405 Mask = maskTrailingOnes<uint64_t>(Width); 7406 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7407 } 7408 } 7409 7410 unsigned MaskIdx = Log2_32(ShAmt); 7411 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7412 7413 if (SHLExpMask) 7414 ExpMask <<= ShAmt; 7415 7416 if (Mask != ExpMask) 7417 return None; 7418 7419 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7420 } 7421 7422 // Matches any of the following bit-manipulation patterns: 7423 // (and (shl x, 1), (0x55555555 << 1)) 7424 // (and (srl x, 1), 0x55555555) 7425 // (shl (and x, 0x55555555), 1) 7426 // (srl (and x, (0x55555555 << 1)), 1) 7427 // where the shift amount and mask may vary thus: 7428 // [1] = 0x55555555 / 0xAAAAAAAA 7429 // [2] = 0x33333333 / 0xCCCCCCCC 7430 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7431 // [8] = 0x00FF00FF / 0xFF00FF00 7432 // [16] = 0x0000FFFF / 0xFFFFFFFF 7433 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7434 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7435 // These are the unshifted masks which we use to match bit-manipulation 7436 // patterns. They may be shifted left in certain circumstances. 7437 static const uint64_t BitmanipMasks[] = { 7438 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7439 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7440 7441 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7442 } 7443 7444 // Try to fold (<bop> x, (reduction.<bop> vec, start)) 7445 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) { 7446 auto BinOpToRVVReduce = [](unsigned Opc) { 7447 switch (Opc) { 7448 default: 7449 llvm_unreachable("Unhandled binary to transfrom reduction"); 7450 case ISD::ADD: 7451 return RISCVISD::VECREDUCE_ADD_VL; 7452 case ISD::UMAX: 7453 return RISCVISD::VECREDUCE_UMAX_VL; 7454 case ISD::SMAX: 7455 return RISCVISD::VECREDUCE_SMAX_VL; 7456 case ISD::UMIN: 7457 return RISCVISD::VECREDUCE_UMIN_VL; 7458 case ISD::SMIN: 7459 return RISCVISD::VECREDUCE_SMIN_VL; 7460 case ISD::AND: 7461 return RISCVISD::VECREDUCE_AND_VL; 7462 case ISD::OR: 7463 return RISCVISD::VECREDUCE_OR_VL; 7464 case ISD::XOR: 7465 return RISCVISD::VECREDUCE_XOR_VL; 7466 case ISD::FADD: 7467 return RISCVISD::VECREDUCE_FADD_VL; 7468 case ISD::FMAXNUM: 7469 return RISCVISD::VECREDUCE_FMAX_VL; 7470 case ISD::FMINNUM: 7471 return RISCVISD::VECREDUCE_FMIN_VL; 7472 } 7473 }; 7474 7475 auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) { 7476 return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7477 isNullConstant(V.getOperand(1)) && 7478 V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc); 7479 }; 7480 7481 unsigned Opc = N->getOpcode(); 7482 unsigned ReduceIdx; 7483 if (IsReduction(N->getOperand(0), Opc)) 7484 ReduceIdx = 0; 7485 else if (IsReduction(N->getOperand(1), Opc)) 7486 ReduceIdx = 1; 7487 else 7488 return SDValue(); 7489 7490 // Skip if FADD disallows reassociation but the combiner needs. 7491 if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation()) 7492 return SDValue(); 7493 7494 SDValue Extract = N->getOperand(ReduceIdx); 7495 SDValue Reduce = Extract.getOperand(0); 7496 if (!Reduce.hasOneUse()) 7497 return SDValue(); 7498 7499 SDValue ScalarV = Reduce.getOperand(2); 7500 7501 // Make sure that ScalarV is a splat with VL=1. 7502 if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL && 7503 ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL && 7504 ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL) 7505 return SDValue(); 7506 7507 if (!isOneConstant(ScalarV.getOperand(2))) 7508 return SDValue(); 7509 7510 // TODO: Deal with value other than neutral element. 7511 auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) { 7512 if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() && 7513 isNullFPConstant(V)) 7514 return true; 7515 return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(), 7516 N->getFlags()) == V; 7517 }; 7518 7519 // Check the scalar of ScalarV is neutral element 7520 if (!IsRVVNeutralElement(N, ScalarV.getOperand(1))) 7521 return SDValue(); 7522 7523 if (!ScalarV.hasOneUse()) 7524 return SDValue(); 7525 7526 EVT SplatVT = ScalarV.getValueType(); 7527 SDValue NewStart = N->getOperand(1 - ReduceIdx); 7528 unsigned SplatOpc = RISCVISD::VFMV_S_F_VL; 7529 if (SplatVT.isInteger()) { 7530 auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode()); 7531 if (!C || C->isZero() || !isInt<5>(C->getSExtValue())) 7532 SplatOpc = RISCVISD::VMV_S_X_VL; 7533 else 7534 SplatOpc = RISCVISD::VMV_V_X_VL; 7535 } 7536 7537 SDValue NewScalarV = 7538 DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart, 7539 ScalarV.getOperand(2)); 7540 SDValue NewReduce = 7541 DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(), 7542 Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV, 7543 Reduce.getOperand(3), Reduce.getOperand(4)); 7544 return DAG.getNode(Extract.getOpcode(), SDLoc(Extract), 7545 Extract.getValueType(), NewReduce, Extract.getOperand(1)); 7546 } 7547 7548 // Match the following pattern as a GREVI(W) operation 7549 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7550 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7551 const RISCVSubtarget &Subtarget) { 7552 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7553 EVT VT = Op.getValueType(); 7554 7555 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7556 auto LHS = matchGREVIPat(Op.getOperand(0)); 7557 auto RHS = matchGREVIPat(Op.getOperand(1)); 7558 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7559 SDLoc DL(Op); 7560 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7561 DAG.getConstant(LHS->ShAmt, DL, VT)); 7562 } 7563 } 7564 return SDValue(); 7565 } 7566 7567 // Matches any the following pattern as a GORCI(W) operation 7568 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7569 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7570 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7571 // Note that with the variant of 3., 7572 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7573 // the inner pattern will first be matched as GREVI and then the outer 7574 // pattern will be matched to GORC via the first rule above. 7575 // 4. (or (rotl/rotr x, bitwidth/2), x) 7576 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7577 const RISCVSubtarget &Subtarget) { 7578 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7579 EVT VT = Op.getValueType(); 7580 7581 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7582 SDLoc DL(Op); 7583 SDValue Op0 = Op.getOperand(0); 7584 SDValue Op1 = Op.getOperand(1); 7585 7586 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7587 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7588 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7589 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7590 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7591 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7592 if ((Reverse.getOpcode() == ISD::ROTL || 7593 Reverse.getOpcode() == ISD::ROTR) && 7594 Reverse.getOperand(0) == X && 7595 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7596 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7597 if (RotAmt == (VT.getSizeInBits() / 2)) 7598 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7599 DAG.getConstant(RotAmt, DL, VT)); 7600 } 7601 return SDValue(); 7602 }; 7603 7604 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7605 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7606 return V; 7607 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7608 return V; 7609 7610 // OR is commutable so canonicalize its OR operand to the left 7611 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7612 std::swap(Op0, Op1); 7613 if (Op0.getOpcode() != ISD::OR) 7614 return SDValue(); 7615 SDValue OrOp0 = Op0.getOperand(0); 7616 SDValue OrOp1 = Op0.getOperand(1); 7617 auto LHS = matchGREVIPat(OrOp0); 7618 // OR is commutable so swap the operands and try again: x might have been 7619 // on the left 7620 if (!LHS) { 7621 std::swap(OrOp0, OrOp1); 7622 LHS = matchGREVIPat(OrOp0); 7623 } 7624 auto RHS = matchGREVIPat(Op1); 7625 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7626 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7627 DAG.getConstant(LHS->ShAmt, DL, VT)); 7628 } 7629 } 7630 return SDValue(); 7631 } 7632 7633 // Matches any of the following bit-manipulation patterns: 7634 // (and (shl x, 1), (0x22222222 << 1)) 7635 // (and (srl x, 1), 0x22222222) 7636 // (shl (and x, 0x22222222), 1) 7637 // (srl (and x, (0x22222222 << 1)), 1) 7638 // where the shift amount and mask may vary thus: 7639 // [1] = 0x22222222 / 0x44444444 7640 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7641 // [4] = 0x00F000F0 / 0x0F000F00 7642 // [8] = 0x0000FF00 / 0x00FF0000 7643 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7644 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7645 // These are the unshifted masks which we use to match bit-manipulation 7646 // patterns. They may be shifted left in certain circumstances. 7647 static const uint64_t BitmanipMasks[] = { 7648 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7649 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7650 7651 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7652 } 7653 7654 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7655 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7656 const RISCVSubtarget &Subtarget) { 7657 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7658 EVT VT = Op.getValueType(); 7659 7660 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7661 return SDValue(); 7662 7663 SDValue Op0 = Op.getOperand(0); 7664 SDValue Op1 = Op.getOperand(1); 7665 7666 // Or is commutable so canonicalize the second OR to the LHS. 7667 if (Op0.getOpcode() != ISD::OR) 7668 std::swap(Op0, Op1); 7669 if (Op0.getOpcode() != ISD::OR) 7670 return SDValue(); 7671 7672 // We found an inner OR, so our operands are the operands of the inner OR 7673 // and the other operand of the outer OR. 7674 SDValue A = Op0.getOperand(0); 7675 SDValue B = Op0.getOperand(1); 7676 SDValue C = Op1; 7677 7678 auto Match1 = matchSHFLPat(A); 7679 auto Match2 = matchSHFLPat(B); 7680 7681 // If neither matched, we failed. 7682 if (!Match1 && !Match2) 7683 return SDValue(); 7684 7685 // We had at least one match. if one failed, try the remaining C operand. 7686 if (!Match1) { 7687 std::swap(A, C); 7688 Match1 = matchSHFLPat(A); 7689 if (!Match1) 7690 return SDValue(); 7691 } else if (!Match2) { 7692 std::swap(B, C); 7693 Match2 = matchSHFLPat(B); 7694 if (!Match2) 7695 return SDValue(); 7696 } 7697 assert(Match1 && Match2); 7698 7699 // Make sure our matches pair up. 7700 if (!Match1->formsPairWith(*Match2)) 7701 return SDValue(); 7702 7703 // All the remains is to make sure C is an AND with the same input, that masks 7704 // out the bits that are being shuffled. 7705 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7706 C.getOperand(0) != Match1->Op) 7707 return SDValue(); 7708 7709 uint64_t Mask = C.getConstantOperandVal(1); 7710 7711 static const uint64_t BitmanipMasks[] = { 7712 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7713 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7714 }; 7715 7716 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7717 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7718 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7719 7720 if (Mask != ExpMask) 7721 return SDValue(); 7722 7723 SDLoc DL(Op); 7724 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7725 DAG.getConstant(Match1->ShAmt, DL, VT)); 7726 } 7727 7728 // Optimize (add (shl x, c0), (shl y, c1)) -> 7729 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7730 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7731 const RISCVSubtarget &Subtarget) { 7732 // Perform this optimization only in the zba extension. 7733 if (!Subtarget.hasStdExtZba()) 7734 return SDValue(); 7735 7736 // Skip for vector types and larger types. 7737 EVT VT = N->getValueType(0); 7738 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7739 return SDValue(); 7740 7741 // The two operand nodes must be SHL and have no other use. 7742 SDValue N0 = N->getOperand(0); 7743 SDValue N1 = N->getOperand(1); 7744 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7745 !N0->hasOneUse() || !N1->hasOneUse()) 7746 return SDValue(); 7747 7748 // Check c0 and c1. 7749 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7750 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7751 if (!N0C || !N1C) 7752 return SDValue(); 7753 int64_t C0 = N0C->getSExtValue(); 7754 int64_t C1 = N1C->getSExtValue(); 7755 if (C0 <= 0 || C1 <= 0) 7756 return SDValue(); 7757 7758 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7759 int64_t Bits = std::min(C0, C1); 7760 int64_t Diff = std::abs(C0 - C1); 7761 if (Diff != 1 && Diff != 2 && Diff != 3) 7762 return SDValue(); 7763 7764 // Build nodes. 7765 SDLoc DL(N); 7766 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7767 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7768 SDValue NA0 = 7769 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7770 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7771 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7772 } 7773 7774 // Combine 7775 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7776 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7777 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7778 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7779 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7780 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7781 // The grev patterns represents BSWAP. 7782 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7783 // off the grev. 7784 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7785 const RISCVSubtarget &Subtarget) { 7786 bool IsWInstruction = 7787 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7788 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7789 IsWInstruction) && 7790 "Unexpected opcode!"); 7791 SDValue Src = N->getOperand(0); 7792 EVT VT = N->getValueType(0); 7793 SDLoc DL(N); 7794 7795 if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV) 7796 return SDValue(); 7797 7798 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7799 !isa<ConstantSDNode>(Src.getOperand(1))) 7800 return SDValue(); 7801 7802 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7803 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7804 7805 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7806 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7807 unsigned ShAmt1 = N->getConstantOperandVal(1); 7808 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7809 if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7810 return SDValue(); 7811 7812 Src = Src.getOperand(0); 7813 7814 // Toggle bit the MSB of the shift. 7815 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7816 if (CombinedShAmt == 0) 7817 return Src; 7818 7819 SDValue Res = DAG.getNode( 7820 RISCVISD::GREV, DL, VT, Src, 7821 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7822 if (!IsWInstruction) 7823 return Res; 7824 7825 // Sign extend the result to match the behavior of the rotate. This will be 7826 // selected to GREVIW in isel. 7827 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res, 7828 DAG.getValueType(MVT::i32)); 7829 } 7830 7831 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7832 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7833 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7834 // not undo itself, but they are redundant. 7835 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7836 bool IsGORC = N->getOpcode() == RISCVISD::GORC; 7837 assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode"); 7838 SDValue Src = N->getOperand(0); 7839 7840 if (Src.getOpcode() != N->getOpcode()) 7841 return SDValue(); 7842 7843 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7844 !isa<ConstantSDNode>(Src.getOperand(1))) 7845 return SDValue(); 7846 7847 unsigned ShAmt1 = N->getConstantOperandVal(1); 7848 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7849 Src = Src.getOperand(0); 7850 7851 unsigned CombinedShAmt; 7852 if (IsGORC) 7853 CombinedShAmt = ShAmt1 | ShAmt2; 7854 else 7855 CombinedShAmt = ShAmt1 ^ ShAmt2; 7856 7857 if (CombinedShAmt == 0) 7858 return Src; 7859 7860 SDLoc DL(N); 7861 return DAG.getNode( 7862 N->getOpcode(), DL, N->getValueType(0), Src, 7863 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7864 } 7865 7866 // Combine a constant select operand into its use: 7867 // 7868 // (and (select cond, -1, c), x) 7869 // -> (select cond, x, (and x, c)) [AllOnes=1] 7870 // (or (select cond, 0, c), x) 7871 // -> (select cond, x, (or x, c)) [AllOnes=0] 7872 // (xor (select cond, 0, c), x) 7873 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7874 // (add (select cond, 0, c), x) 7875 // -> (select cond, x, (add x, c)) [AllOnes=0] 7876 // (sub x, (select cond, 0, c)) 7877 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7878 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7879 SelectionDAG &DAG, bool AllOnes) { 7880 EVT VT = N->getValueType(0); 7881 7882 // Skip vectors. 7883 if (VT.isVector()) 7884 return SDValue(); 7885 7886 if ((Slct.getOpcode() != ISD::SELECT && 7887 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7888 !Slct.hasOneUse()) 7889 return SDValue(); 7890 7891 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7892 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7893 }; 7894 7895 bool SwapSelectOps; 7896 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7897 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7898 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7899 SDValue NonConstantVal; 7900 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7901 SwapSelectOps = false; 7902 NonConstantVal = FalseVal; 7903 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7904 SwapSelectOps = true; 7905 NonConstantVal = TrueVal; 7906 } else 7907 return SDValue(); 7908 7909 // Slct is now know to be the desired identity constant when CC is true. 7910 TrueVal = OtherOp; 7911 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7912 // Unless SwapSelectOps says the condition should be false. 7913 if (SwapSelectOps) 7914 std::swap(TrueVal, FalseVal); 7915 7916 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7917 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7918 {Slct.getOperand(0), Slct.getOperand(1), 7919 Slct.getOperand(2), TrueVal, FalseVal}); 7920 7921 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7922 {Slct.getOperand(0), TrueVal, FalseVal}); 7923 } 7924 7925 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7926 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7927 bool AllOnes) { 7928 SDValue N0 = N->getOperand(0); 7929 SDValue N1 = N->getOperand(1); 7930 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7931 return Result; 7932 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7933 return Result; 7934 return SDValue(); 7935 } 7936 7937 // Transform (add (mul x, c0), c1) -> 7938 // (add (mul (add x, c1/c0), c0), c1%c0). 7939 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7940 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7941 // to an infinite loop in DAGCombine if transformed. 7942 // Or transform (add (mul x, c0), c1) -> 7943 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7944 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7945 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7946 // lead 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 // (mul (add x, c1/c0), c0). 7954 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7955 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7956 const RISCVSubtarget &Subtarget) { 7957 // Skip for vector types and larger types. 7958 EVT VT = N->getValueType(0); 7959 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7960 return SDValue(); 7961 // The first operand node must be a MUL and has no other use. 7962 SDValue N0 = N->getOperand(0); 7963 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7964 return SDValue(); 7965 // Check if c0 and c1 match above conditions. 7966 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7967 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7968 if (!N0C || !N1C) 7969 return SDValue(); 7970 // If N0C has multiple uses it's possible one of the cases in 7971 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 7972 // in an infinite loop. 7973 if (!N0C->hasOneUse()) 7974 return SDValue(); 7975 int64_t C0 = N0C->getSExtValue(); 7976 int64_t C1 = N1C->getSExtValue(); 7977 int64_t CA, CB; 7978 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7979 return SDValue(); 7980 // Search for proper CA (non-zero) and CB that both are simm12. 7981 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7982 !isInt<12>(C0 * (C1 / C0))) { 7983 CA = C1 / C0; 7984 CB = C1 % C0; 7985 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7986 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7987 CA = C1 / C0 + 1; 7988 CB = C1 % C0 - C0; 7989 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7990 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7991 CA = C1 / C0 - 1; 7992 CB = C1 % C0 + C0; 7993 } else 7994 return SDValue(); 7995 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7996 SDLoc DL(N); 7997 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7998 DAG.getConstant(CA, DL, VT)); 7999 SDValue New1 = 8000 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 8001 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 8002 } 8003 8004 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 8005 const RISCVSubtarget &Subtarget) { 8006 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 8007 return V; 8008 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 8009 return V; 8010 if (SDValue V = combineBinOpToReduce(N, DAG)) 8011 return V; 8012 // fold (add (select lhs, rhs, cc, 0, y), x) -> 8013 // (select lhs, rhs, cc, x, (add x, y)) 8014 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8015 } 8016 8017 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 8018 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 8019 // (select lhs, rhs, cc, x, (sub x, y)) 8020 SDValue N0 = N->getOperand(0); 8021 SDValue N1 = N->getOperand(1); 8022 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 8023 } 8024 8025 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG, 8026 const RISCVSubtarget &Subtarget) { 8027 SDValue N0 = N->getOperand(0); 8028 // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero 8029 // extending X. This is safe since we only need the LSB after the shift and 8030 // shift amounts larger than 31 would produce poison. If we wait until 8031 // type legalization, we'll create RISCVISD::SRLW and we can't recover it 8032 // to use a BEXT instruction. 8033 if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() && 8034 N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) && 8035 N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) && 8036 N0.hasOneUse()) { 8037 SDLoc DL(N); 8038 SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0)); 8039 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1)); 8040 SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1); 8041 SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl, 8042 DAG.getConstant(1, DL, MVT::i64)); 8043 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And); 8044 } 8045 8046 if (SDValue V = combineBinOpToReduce(N, DAG)) 8047 return V; 8048 8049 // fold (and (select lhs, rhs, cc, -1, y), x) -> 8050 // (select lhs, rhs, cc, x, (and x, y)) 8051 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 8052 } 8053 8054 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 8055 const RISCVSubtarget &Subtarget) { 8056 if (Subtarget.hasStdExtZbp()) { 8057 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 8058 return GREV; 8059 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 8060 return GORC; 8061 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 8062 return SHFL; 8063 } 8064 8065 if (SDValue V = combineBinOpToReduce(N, DAG)) 8066 return V; 8067 // fold (or (select cond, 0, y), x) -> 8068 // (select cond, x, (or x, y)) 8069 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8070 } 8071 8072 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 8073 SDValue N0 = N->getOperand(0); 8074 SDValue N1 = N->getOperand(1); 8075 8076 // fold (xor (sllw 1, x), -1) -> (rolw ~1, x) 8077 // NOTE: Assumes ROL being legal means ROLW is legal. 8078 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8079 if (N0.getOpcode() == RISCVISD::SLLW && 8080 isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) && 8081 TLI.isOperationLegal(ISD::ROTL, MVT::i64)) { 8082 SDLoc DL(N); 8083 return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64, 8084 DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1)); 8085 } 8086 8087 if (SDValue V = combineBinOpToReduce(N, DAG)) 8088 return V; 8089 // fold (xor (select cond, 0, y), x) -> 8090 // (select cond, x, (xor x, y)) 8091 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8092 } 8093 8094 static SDValue 8095 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 8096 const RISCVSubtarget &Subtarget) { 8097 SDValue Src = N->getOperand(0); 8098 EVT VT = N->getValueType(0); 8099 8100 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 8101 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8102 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 8103 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 8104 Src.getOperand(0)); 8105 8106 // Fold (i64 (sext_inreg (abs X), i32)) -> 8107 // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits. 8108 // The (sext_inreg (neg X), i32) will be selected to negw by isel. This 8109 // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user 8110 // of the (i32 (abs X)) is a sext or setcc or something else that causes type 8111 // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have 8112 // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg 8113 // may get combined into an earlier operation so we need to use 8114 // ComputeNumSignBits. 8115 // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for 8116 // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so 8117 // we can't assume that X has 33 sign bits. We must check. 8118 if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() && 8119 Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 && 8120 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 && 8121 DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) { 8122 SDLoc DL(N); 8123 SDValue Freeze = DAG.getFreeze(Src.getOperand(0)); 8124 SDValue Neg = 8125 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze); 8126 Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg, 8127 DAG.getValueType(MVT::i32)); 8128 return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg); 8129 } 8130 8131 return SDValue(); 8132 } 8133 8134 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 8135 // vwadd(u).vv/vx or vwsub(u).vv/vx. 8136 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 8137 bool Commute = false) { 8138 assert((N->getOpcode() == RISCVISD::ADD_VL || 8139 N->getOpcode() == RISCVISD::SUB_VL) && 8140 "Unexpected opcode"); 8141 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 8142 SDValue Op0 = N->getOperand(0); 8143 SDValue Op1 = N->getOperand(1); 8144 if (Commute) 8145 std::swap(Op0, Op1); 8146 8147 MVT VT = N->getSimpleValueType(0); 8148 8149 // Determine the narrow size for a widening add/sub. 8150 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8151 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8152 VT.getVectorElementCount()); 8153 8154 SDValue Mask = N->getOperand(2); 8155 SDValue VL = N->getOperand(3); 8156 8157 SDLoc DL(N); 8158 8159 // If the RHS is a sext or zext, we can form a widening op. 8160 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 8161 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 8162 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 8163 unsigned ExtOpc = Op1.getOpcode(); 8164 Op1 = Op1.getOperand(0); 8165 // Re-introduce narrower extends if needed. 8166 if (Op1.getValueType() != NarrowVT) 8167 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8168 8169 unsigned WOpc; 8170 if (ExtOpc == RISCVISD::VSEXT_VL) 8171 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 8172 else 8173 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 8174 8175 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 8176 } 8177 8178 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 8179 // sext/zext? 8180 8181 return SDValue(); 8182 } 8183 8184 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 8185 // vwsub(u).vv/vx. 8186 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 8187 SDValue Op0 = N->getOperand(0); 8188 SDValue Op1 = N->getOperand(1); 8189 SDValue Mask = N->getOperand(2); 8190 SDValue VL = N->getOperand(3); 8191 8192 MVT VT = N->getSimpleValueType(0); 8193 MVT NarrowVT = Op1.getSimpleValueType(); 8194 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 8195 8196 unsigned VOpc; 8197 switch (N->getOpcode()) { 8198 default: llvm_unreachable("Unexpected opcode"); 8199 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 8200 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 8201 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 8202 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 8203 } 8204 8205 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 8206 N->getOpcode() == RISCVISD::VWSUB_W_VL; 8207 8208 SDLoc DL(N); 8209 8210 // If the LHS is a sext or zext, we can narrow this op to the same size as 8211 // the RHS. 8212 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 8213 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 8214 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 8215 unsigned ExtOpc = Op0.getOpcode(); 8216 Op0 = Op0.getOperand(0); 8217 // Re-introduce narrower extends if needed. 8218 if (Op0.getValueType() != NarrowVT) 8219 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8220 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 8221 } 8222 8223 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 8224 N->getOpcode() == RISCVISD::VWADDU_W_VL; 8225 8226 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 8227 // to commute and use a vwadd(u).vx instead. 8228 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 8229 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 8230 Op0 = Op0.getOperand(1); 8231 8232 // See if have enough sign bits or zero bits in the scalar to use a 8233 // widening add/sub by splatting to smaller element size. 8234 unsigned EltBits = VT.getScalarSizeInBits(); 8235 unsigned ScalarBits = Op0.getValueSizeInBits(); 8236 // Make sure we're getting all element bits from the scalar register. 8237 // FIXME: Support implicit sign extension of vmv.v.x? 8238 if (ScalarBits < EltBits) 8239 return SDValue(); 8240 8241 if (IsSigned) { 8242 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 8243 return SDValue(); 8244 } else { 8245 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8246 if (!DAG.MaskedValueIsZero(Op0, Mask)) 8247 return SDValue(); 8248 } 8249 8250 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8251 DAG.getUNDEF(NarrowVT), Op0, VL); 8252 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 8253 } 8254 8255 return SDValue(); 8256 } 8257 8258 // Try to form VWMUL, VWMULU or VWMULSU. 8259 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 8260 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 8261 bool Commute) { 8262 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 8263 SDValue Op0 = N->getOperand(0); 8264 SDValue Op1 = N->getOperand(1); 8265 if (Commute) 8266 std::swap(Op0, Op1); 8267 8268 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 8269 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 8270 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 8271 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 8272 return SDValue(); 8273 8274 SDValue Mask = N->getOperand(2); 8275 SDValue VL = N->getOperand(3); 8276 8277 // Make sure the mask and VL match. 8278 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 8279 return SDValue(); 8280 8281 MVT VT = N->getSimpleValueType(0); 8282 8283 // Determine the narrow size for a widening multiply. 8284 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8285 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8286 VT.getVectorElementCount()); 8287 8288 SDLoc DL(N); 8289 8290 // See if the other operand is the same opcode. 8291 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 8292 if (!Op1.hasOneUse()) 8293 return SDValue(); 8294 8295 // Make sure the mask and VL match. 8296 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 8297 return SDValue(); 8298 8299 Op1 = Op1.getOperand(0); 8300 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 8301 // The operand is a splat of a scalar. 8302 8303 // The pasthru must be undef for tail agnostic 8304 if (!Op1.getOperand(0).isUndef()) 8305 return SDValue(); 8306 // The VL must be the same. 8307 if (Op1.getOperand(2) != VL) 8308 return SDValue(); 8309 8310 // Get the scalar value. 8311 Op1 = Op1.getOperand(1); 8312 8313 // See if have enough sign bits or zero bits in the scalar to use a 8314 // widening multiply by splatting to smaller element size. 8315 unsigned EltBits = VT.getScalarSizeInBits(); 8316 unsigned ScalarBits = Op1.getValueSizeInBits(); 8317 // Make sure we're getting all element bits from the scalar register. 8318 // FIXME: Support implicit sign extension of vmv.v.x? 8319 if (ScalarBits < EltBits) 8320 return SDValue(); 8321 8322 // If the LHS is a sign extend, try to use vwmul. 8323 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 8324 // Can use vwmul. 8325 } else { 8326 // Otherwise try to use vwmulu or vwmulsu. 8327 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8328 if (DAG.MaskedValueIsZero(Op1, Mask)) 8329 IsVWMULSU = IsSignExt; 8330 else 8331 return SDValue(); 8332 } 8333 8334 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8335 DAG.getUNDEF(NarrowVT), Op1, VL); 8336 } else 8337 return SDValue(); 8338 8339 Op0 = Op0.getOperand(0); 8340 8341 // Re-introduce narrower extends if needed. 8342 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 8343 if (Op0.getValueType() != NarrowVT) 8344 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8345 // vwmulsu requires second operand to be zero extended. 8346 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 8347 if (Op1.getValueType() != NarrowVT) 8348 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8349 8350 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 8351 if (!IsVWMULSU) 8352 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 8353 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 8354 } 8355 8356 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 8357 switch (Op.getOpcode()) { 8358 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 8359 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 8360 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 8361 case ISD::FCEIL: return RISCVFPRndMode::RUP; 8362 case ISD::FROUND: return RISCVFPRndMode::RMM; 8363 } 8364 8365 return RISCVFPRndMode::Invalid; 8366 } 8367 8368 // Fold 8369 // (fp_to_int (froundeven X)) -> fcvt X, rne 8370 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 8371 // (fp_to_int (ffloor X)) -> fcvt X, rdn 8372 // (fp_to_int (fceil X)) -> fcvt X, rup 8373 // (fp_to_int (fround X)) -> fcvt X, rmm 8374 static SDValue performFP_TO_INTCombine(SDNode *N, 8375 TargetLowering::DAGCombinerInfo &DCI, 8376 const RISCVSubtarget &Subtarget) { 8377 SelectionDAG &DAG = DCI.DAG; 8378 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8379 MVT XLenVT = Subtarget.getXLenVT(); 8380 8381 // Only handle XLen or i32 types. Other types narrower than XLen will 8382 // eventually be legalized to XLenVT. 8383 EVT VT = N->getValueType(0); 8384 if (VT != MVT::i32 && VT != XLenVT) 8385 return SDValue(); 8386 8387 SDValue Src = N->getOperand(0); 8388 8389 // Ensure the FP type is also legal. 8390 if (!TLI.isTypeLegal(Src.getValueType())) 8391 return SDValue(); 8392 8393 // Don't do this for f16 with Zfhmin and not Zfh. 8394 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8395 return SDValue(); 8396 8397 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8398 if (FRM == RISCVFPRndMode::Invalid) 8399 return SDValue(); 8400 8401 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8402 8403 unsigned Opc; 8404 if (VT == XLenVT) 8405 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8406 else 8407 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8408 8409 SDLoc DL(N); 8410 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 8411 DAG.getTargetConstant(FRM, DL, XLenVT)); 8412 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 8413 } 8414 8415 // Fold 8416 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 8417 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 8418 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8419 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8420 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8421 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8422 TargetLowering::DAGCombinerInfo &DCI, 8423 const RISCVSubtarget &Subtarget) { 8424 SelectionDAG &DAG = DCI.DAG; 8425 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8426 MVT XLenVT = Subtarget.getXLenVT(); 8427 8428 // Only handle XLen types. Other types narrower than XLen will eventually be 8429 // legalized to XLenVT. 8430 EVT DstVT = N->getValueType(0); 8431 if (DstVT != XLenVT) 8432 return SDValue(); 8433 8434 SDValue Src = N->getOperand(0); 8435 8436 // Ensure the FP type is also legal. 8437 if (!TLI.isTypeLegal(Src.getValueType())) 8438 return SDValue(); 8439 8440 // Don't do this for f16 with Zfhmin and not Zfh. 8441 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8442 return SDValue(); 8443 8444 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8445 8446 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8447 if (FRM == RISCVFPRndMode::Invalid) 8448 return SDValue(); 8449 8450 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8451 8452 unsigned Opc; 8453 if (SatVT == DstVT) 8454 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8455 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8456 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8457 else 8458 return SDValue(); 8459 // FIXME: Support other SatVTs by clamping before or after the conversion. 8460 8461 Src = Src.getOperand(0); 8462 8463 SDLoc DL(N); 8464 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8465 DAG.getTargetConstant(FRM, DL, XLenVT)); 8466 8467 // RISCV FP-to-int conversions saturate to the destination register size, but 8468 // don't produce 0 for nan. 8469 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8470 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8471 } 8472 8473 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is 8474 // smaller than XLenVT. 8475 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG, 8476 const RISCVSubtarget &Subtarget) { 8477 assert(Subtarget.hasStdExtZbkb() && "Unexpected extension"); 8478 8479 SDValue Src = N->getOperand(0); 8480 if (Src.getOpcode() != ISD::BSWAP) 8481 return SDValue(); 8482 8483 EVT VT = N->getValueType(0); 8484 if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() || 8485 !isPowerOf2_32(VT.getSizeInBits())) 8486 return SDValue(); 8487 8488 SDLoc DL(N); 8489 return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0), 8490 DAG.getConstant(7, DL, VT)); 8491 } 8492 8493 // Convert from one FMA opcode to another based on whether we are negating the 8494 // multiply result and/or the accumulator. 8495 // NOTE: Only supports RVV operations with VL. 8496 static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc) { 8497 assert((NegMul || NegAcc) && "Not negating anything?"); 8498 8499 // Negating the multiply result changes ADD<->SUB and toggles 'N'. 8500 if (NegMul) { 8501 // clang-format off 8502 switch (Opcode) { 8503 default: llvm_unreachable("Unexpected opcode"); 8504 case RISCVISD::VFMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break; 8505 case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFMADD_VL; break; 8506 case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFMSUB_VL; break; 8507 case RISCVISD::VFMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break; 8508 } 8509 // clang-format on 8510 } 8511 8512 // Negating the accumulator changes ADD<->SUB. 8513 if (NegAcc) { 8514 // clang-format off 8515 switch (Opcode) { 8516 default: llvm_unreachable("Unexpected opcode"); 8517 case RISCVISD::VFMADD_VL: Opcode = RISCVISD::VFMSUB_VL; break; 8518 case RISCVISD::VFMSUB_VL: Opcode = RISCVISD::VFMADD_VL; break; 8519 case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break; 8520 case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break; 8521 } 8522 // clang-format on 8523 } 8524 8525 return Opcode; 8526 } 8527 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8528 DAGCombinerInfo &DCI) const { 8529 SelectionDAG &DAG = DCI.DAG; 8530 8531 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8532 // bits are demanded. N will be added to the Worklist if it was not deleted. 8533 // Caller should return SDValue(N, 0) if this returns true. 8534 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8535 SDValue Op = N->getOperand(OpNo); 8536 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8537 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8538 return false; 8539 8540 if (N->getOpcode() != ISD::DELETED_NODE) 8541 DCI.AddToWorklist(N); 8542 return true; 8543 }; 8544 8545 switch (N->getOpcode()) { 8546 default: 8547 break; 8548 case RISCVISD::SplitF64: { 8549 SDValue Op0 = N->getOperand(0); 8550 // If the input to SplitF64 is just BuildPairF64 then the operation is 8551 // redundant. Instead, use BuildPairF64's operands directly. 8552 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8553 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8554 8555 if (Op0->isUndef()) { 8556 SDValue Lo = DAG.getUNDEF(MVT::i32); 8557 SDValue Hi = DAG.getUNDEF(MVT::i32); 8558 return DCI.CombineTo(N, Lo, Hi); 8559 } 8560 8561 SDLoc DL(N); 8562 8563 // It's cheaper to materialise two 32-bit integers than to load a double 8564 // from the constant pool and transfer it to integer registers through the 8565 // stack. 8566 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8567 APInt V = C->getValueAPF().bitcastToAPInt(); 8568 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8569 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8570 return DCI.CombineTo(N, Lo, Hi); 8571 } 8572 8573 // This is a target-specific version of a DAGCombine performed in 8574 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8575 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8576 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8577 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8578 !Op0.getNode()->hasOneUse()) 8579 break; 8580 SDValue NewSplitF64 = 8581 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8582 Op0.getOperand(0)); 8583 SDValue Lo = NewSplitF64.getValue(0); 8584 SDValue Hi = NewSplitF64.getValue(1); 8585 APInt SignBit = APInt::getSignMask(32); 8586 if (Op0.getOpcode() == ISD::FNEG) { 8587 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8588 DAG.getConstant(SignBit, DL, MVT::i32)); 8589 return DCI.CombineTo(N, Lo, NewHi); 8590 } 8591 assert(Op0.getOpcode() == ISD::FABS); 8592 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8593 DAG.getConstant(~SignBit, DL, MVT::i32)); 8594 return DCI.CombineTo(N, Lo, NewHi); 8595 } 8596 case RISCVISD::SLLW: 8597 case RISCVISD::SRAW: 8598 case RISCVISD::SRLW: { 8599 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8600 if (SimplifyDemandedLowBitsHelper(0, 32) || 8601 SimplifyDemandedLowBitsHelper(1, 5)) 8602 return SDValue(N, 0); 8603 8604 break; 8605 } 8606 case ISD::ROTR: 8607 case ISD::ROTL: 8608 case RISCVISD::RORW: 8609 case RISCVISD::ROLW: { 8610 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8611 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8612 if (SimplifyDemandedLowBitsHelper(0, 32) || 8613 SimplifyDemandedLowBitsHelper(1, 5)) 8614 return SDValue(N, 0); 8615 } 8616 8617 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8618 } 8619 case RISCVISD::CLZW: 8620 case RISCVISD::CTZW: { 8621 // Only the lower 32 bits of the first operand are read 8622 if (SimplifyDemandedLowBitsHelper(0, 32)) 8623 return SDValue(N, 0); 8624 break; 8625 } 8626 case RISCVISD::GREV: 8627 case RISCVISD::GORC: { 8628 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8629 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8630 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8631 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8632 return SDValue(N, 0); 8633 8634 return combineGREVI_GORCI(N, DAG); 8635 } 8636 case RISCVISD::GREVW: 8637 case RISCVISD::GORCW: { 8638 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8639 if (SimplifyDemandedLowBitsHelper(0, 32) || 8640 SimplifyDemandedLowBitsHelper(1, 5)) 8641 return SDValue(N, 0); 8642 8643 break; 8644 } 8645 case RISCVISD::SHFL: 8646 case RISCVISD::UNSHFL: { 8647 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8648 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8649 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8650 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8651 return SDValue(N, 0); 8652 8653 break; 8654 } 8655 case RISCVISD::SHFLW: 8656 case RISCVISD::UNSHFLW: { 8657 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8658 if (SimplifyDemandedLowBitsHelper(0, 32) || 8659 SimplifyDemandedLowBitsHelper(1, 4)) 8660 return SDValue(N, 0); 8661 8662 break; 8663 } 8664 case RISCVISD::BCOMPRESSW: 8665 case RISCVISD::BDECOMPRESSW: { 8666 // Only the lower 32 bits of LHS and RHS are read. 8667 if (SimplifyDemandedLowBitsHelper(0, 32) || 8668 SimplifyDemandedLowBitsHelper(1, 32)) 8669 return SDValue(N, 0); 8670 8671 break; 8672 } 8673 case RISCVISD::FSR: 8674 case RISCVISD::FSL: 8675 case RISCVISD::FSRW: 8676 case RISCVISD::FSLW: { 8677 bool IsWInstruction = 8678 N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW; 8679 unsigned BitWidth = 8680 IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits(); 8681 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8682 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 8683 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1)) 8684 return SDValue(N, 0); 8685 8686 break; 8687 } 8688 case RISCVISD::FMV_X_ANYEXTH: 8689 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8690 SDLoc DL(N); 8691 SDValue Op0 = N->getOperand(0); 8692 MVT VT = N->getSimpleValueType(0); 8693 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8694 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8695 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8696 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8697 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8698 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8699 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8700 assert(Op0.getOperand(0).getValueType() == VT && 8701 "Unexpected value type!"); 8702 return Op0.getOperand(0); 8703 } 8704 8705 // This is a target-specific version of a DAGCombine performed in 8706 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8707 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8708 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8709 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8710 !Op0.getNode()->hasOneUse()) 8711 break; 8712 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8713 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8714 APInt SignBit = APInt::getSignMask(FPBits).sext(VT.getSizeInBits()); 8715 if (Op0.getOpcode() == ISD::FNEG) 8716 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8717 DAG.getConstant(SignBit, DL, VT)); 8718 8719 assert(Op0.getOpcode() == ISD::FABS); 8720 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8721 DAG.getConstant(~SignBit, DL, VT)); 8722 } 8723 case ISD::ADD: 8724 return performADDCombine(N, DAG, Subtarget); 8725 case ISD::SUB: 8726 return performSUBCombine(N, DAG); 8727 case ISD::AND: 8728 return performANDCombine(N, DAG, Subtarget); 8729 case ISD::OR: 8730 return performORCombine(N, DAG, Subtarget); 8731 case ISD::XOR: 8732 return performXORCombine(N, DAG); 8733 case ISD::FADD: 8734 case ISD::UMAX: 8735 case ISD::UMIN: 8736 case ISD::SMAX: 8737 case ISD::SMIN: 8738 case ISD::FMAXNUM: 8739 case ISD::FMINNUM: 8740 return combineBinOpToReduce(N, DAG); 8741 case ISD::SIGN_EXTEND_INREG: 8742 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 8743 case ISD::ZERO_EXTEND: 8744 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8745 // type legalization. This is safe because fp_to_uint produces poison if 8746 // it overflows. 8747 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8748 SDValue Src = N->getOperand(0); 8749 if (Src.getOpcode() == ISD::FP_TO_UINT && 8750 isTypeLegal(Src.getOperand(0).getValueType())) 8751 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8752 Src.getOperand(0)); 8753 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8754 isTypeLegal(Src.getOperand(1).getValueType())) { 8755 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8756 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8757 Src.getOperand(0), Src.getOperand(1)); 8758 DCI.CombineTo(N, Res); 8759 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8760 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8761 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8762 } 8763 } 8764 return SDValue(); 8765 case RISCVISD::SELECT_CC: { 8766 // Transform 8767 SDValue LHS = N->getOperand(0); 8768 SDValue RHS = N->getOperand(1); 8769 SDValue TrueV = N->getOperand(3); 8770 SDValue FalseV = N->getOperand(4); 8771 8772 // If the True and False values are the same, we don't need a select_cc. 8773 if (TrueV == FalseV) 8774 return TrueV; 8775 8776 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8777 if (!ISD::isIntEqualitySetCC(CCVal)) 8778 break; 8779 8780 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8781 // (select_cc X, Y, lt, trueV, falseV) 8782 // Sometimes the setcc is introduced after select_cc has been formed. 8783 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8784 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8785 // If we're looking for eq 0 instead of ne 0, we need to invert the 8786 // condition. 8787 bool Invert = CCVal == ISD::SETEQ; 8788 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8789 if (Invert) 8790 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8791 8792 SDLoc DL(N); 8793 RHS = LHS.getOperand(1); 8794 LHS = LHS.getOperand(0); 8795 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8796 8797 SDValue TargetCC = DAG.getCondCode(CCVal); 8798 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8799 {LHS, RHS, TargetCC, TrueV, FalseV}); 8800 } 8801 8802 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8803 // (select_cc X, Y, eq/ne, trueV, falseV) 8804 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8805 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8806 {LHS.getOperand(0), LHS.getOperand(1), 8807 N->getOperand(2), TrueV, FalseV}); 8808 // (select_cc X, 1, setne, trueV, falseV) -> 8809 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8810 // This can occur when legalizing some floating point comparisons. 8811 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8812 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8813 SDLoc DL(N); 8814 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8815 SDValue TargetCC = DAG.getCondCode(CCVal); 8816 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8817 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8818 {LHS, RHS, TargetCC, TrueV, FalseV}); 8819 } 8820 8821 break; 8822 } 8823 case RISCVISD::BR_CC: { 8824 SDValue LHS = N->getOperand(1); 8825 SDValue RHS = N->getOperand(2); 8826 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8827 if (!ISD::isIntEqualitySetCC(CCVal)) 8828 break; 8829 8830 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8831 // (br_cc X, Y, lt, dest) 8832 // Sometimes the setcc is introduced after br_cc has been formed. 8833 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8834 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8835 // If we're looking for eq 0 instead of ne 0, we need to invert the 8836 // condition. 8837 bool Invert = CCVal == ISD::SETEQ; 8838 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8839 if (Invert) 8840 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8841 8842 SDLoc DL(N); 8843 RHS = LHS.getOperand(1); 8844 LHS = LHS.getOperand(0); 8845 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8846 8847 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8848 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8849 N->getOperand(4)); 8850 } 8851 8852 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8853 // (br_cc X, Y, eq/ne, trueV, falseV) 8854 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8855 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8856 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8857 N->getOperand(3), N->getOperand(4)); 8858 8859 // (br_cc X, 1, setne, br_cc) -> 8860 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8861 // This can occur when legalizing some floating point comparisons. 8862 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8863 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8864 SDLoc DL(N); 8865 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8866 SDValue TargetCC = DAG.getCondCode(CCVal); 8867 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8868 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8869 N->getOperand(0), LHS, RHS, TargetCC, 8870 N->getOperand(4)); 8871 } 8872 break; 8873 } 8874 case ISD::BITREVERSE: 8875 return performBITREVERSECombine(N, DAG, Subtarget); 8876 case ISD::FP_TO_SINT: 8877 case ISD::FP_TO_UINT: 8878 return performFP_TO_INTCombine(N, DCI, Subtarget); 8879 case ISD::FP_TO_SINT_SAT: 8880 case ISD::FP_TO_UINT_SAT: 8881 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8882 case ISD::FCOPYSIGN: { 8883 EVT VT = N->getValueType(0); 8884 if (!VT.isVector()) 8885 break; 8886 // There is a form of VFSGNJ which injects the negated sign of its second 8887 // operand. Try and bubble any FNEG up after the extend/round to produce 8888 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8889 // TRUNC=1. 8890 SDValue In2 = N->getOperand(1); 8891 // Avoid cases where the extend/round has multiple uses, as duplicating 8892 // those is typically more expensive than removing a fneg. 8893 if (!In2.hasOneUse()) 8894 break; 8895 if (In2.getOpcode() != ISD::FP_EXTEND && 8896 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8897 break; 8898 In2 = In2.getOperand(0); 8899 if (In2.getOpcode() != ISD::FNEG) 8900 break; 8901 SDLoc DL(N); 8902 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8903 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8904 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8905 } 8906 case ISD::MGATHER: 8907 case ISD::MSCATTER: 8908 case ISD::VP_GATHER: 8909 case ISD::VP_SCATTER: { 8910 if (!DCI.isBeforeLegalize()) 8911 break; 8912 SDValue Index, ScaleOp; 8913 bool IsIndexScaled = false; 8914 bool IsIndexSigned = false; 8915 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8916 Index = VPGSN->getIndex(); 8917 ScaleOp = VPGSN->getScale(); 8918 IsIndexScaled = VPGSN->isIndexScaled(); 8919 IsIndexSigned = VPGSN->isIndexSigned(); 8920 } else { 8921 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 8922 Index = MGSN->getIndex(); 8923 ScaleOp = MGSN->getScale(); 8924 IsIndexScaled = MGSN->isIndexScaled(); 8925 IsIndexSigned = MGSN->isIndexSigned(); 8926 } 8927 EVT IndexVT = Index.getValueType(); 8928 MVT XLenVT = Subtarget.getXLenVT(); 8929 // RISCV indexed loads only support the "unsigned unscaled" addressing 8930 // mode, so anything else must be manually legalized. 8931 bool NeedsIdxLegalization = 8932 IsIndexScaled || 8933 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 8934 if (!NeedsIdxLegalization) 8935 break; 8936 8937 SDLoc DL(N); 8938 8939 // Any index legalization should first promote to XLenVT, so we don't lose 8940 // bits when scaling. This may create an illegal index type so we let 8941 // LLVM's legalization take care of the splitting. 8942 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 8943 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 8944 IndexVT = IndexVT.changeVectorElementType(XLenVT); 8945 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8946 DL, IndexVT, Index); 8947 } 8948 8949 if (IsIndexScaled) { 8950 // Manually scale the indices. 8951 // TODO: Sanitize the scale operand here? 8952 // TODO: For VP nodes, should we use VP_SHL here? 8953 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 8954 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 8955 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 8956 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 8957 ScaleOp = DAG.getTargetConstant(1, DL, ScaleOp.getValueType()); 8958 } 8959 8960 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_SCALED; 8961 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 8962 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 8963 {VPGN->getChain(), VPGN->getBasePtr(), Index, 8964 ScaleOp, VPGN->getMask(), 8965 VPGN->getVectorLength()}, 8966 VPGN->getMemOperand(), NewIndexTy); 8967 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 8968 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 8969 {VPSN->getChain(), VPSN->getValue(), 8970 VPSN->getBasePtr(), Index, ScaleOp, 8971 VPSN->getMask(), VPSN->getVectorLength()}, 8972 VPSN->getMemOperand(), NewIndexTy); 8973 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 8974 return DAG.getMaskedGather( 8975 N->getVTList(), MGN->getMemoryVT(), DL, 8976 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 8977 MGN->getBasePtr(), Index, ScaleOp}, 8978 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 8979 const auto *MSN = cast<MaskedScatterSDNode>(N); 8980 return DAG.getMaskedScatter( 8981 N->getVTList(), MSN->getMemoryVT(), DL, 8982 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 8983 Index, ScaleOp}, 8984 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 8985 } 8986 case RISCVISD::SRA_VL: 8987 case RISCVISD::SRL_VL: 8988 case RISCVISD::SHL_VL: { 8989 SDValue ShAmt = N->getOperand(1); 8990 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8991 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8992 SDLoc DL(N); 8993 SDValue VL = N->getOperand(3); 8994 EVT VT = N->getValueType(0); 8995 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8996 ShAmt.getOperand(1), VL); 8997 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8998 N->getOperand(2), N->getOperand(3)); 8999 } 9000 break; 9001 } 9002 case ISD::SRA: 9003 case ISD::SRL: 9004 case ISD::SHL: { 9005 SDValue ShAmt = N->getOperand(1); 9006 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 9007 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 9008 SDLoc DL(N); 9009 EVT VT = N->getValueType(0); 9010 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 9011 ShAmt.getOperand(1), 9012 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 9013 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 9014 } 9015 break; 9016 } 9017 case RISCVISD::ADD_VL: 9018 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 9019 return V; 9020 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 9021 case RISCVISD::SUB_VL: 9022 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 9023 case RISCVISD::VWADD_W_VL: 9024 case RISCVISD::VWADDU_W_VL: 9025 case RISCVISD::VWSUB_W_VL: 9026 case RISCVISD::VWSUBU_W_VL: 9027 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 9028 case RISCVISD::MUL_VL: 9029 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 9030 return V; 9031 // Mul is commutative. 9032 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 9033 case RISCVISD::VFMADD_VL: 9034 case RISCVISD::VFNMADD_VL: 9035 case RISCVISD::VFMSUB_VL: 9036 case RISCVISD::VFNMSUB_VL: { 9037 // Fold FNEG_VL into FMA opcodes. 9038 SDValue A = N->getOperand(0); 9039 SDValue B = N->getOperand(1); 9040 SDValue C = N->getOperand(2); 9041 SDValue Mask = N->getOperand(3); 9042 SDValue VL = N->getOperand(4); 9043 9044 auto invertIfNegative = [&Mask, &VL](SDValue &V) { 9045 if (V.getOpcode() == RISCVISD::FNEG_VL && V.getOperand(1) == Mask && 9046 V.getOperand(2) == VL) { 9047 // Return the negated input. 9048 V = V.getOperand(0); 9049 return true; 9050 } 9051 9052 return false; 9053 }; 9054 9055 bool NegA = invertIfNegative(A); 9056 bool NegB = invertIfNegative(B); 9057 bool NegC = invertIfNegative(C); 9058 9059 // If no operands are negated, we're done. 9060 if (!NegA && !NegB && !NegC) 9061 return SDValue(); 9062 9063 unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC); 9064 return DAG.getNode(NewOpcode, SDLoc(N), N->getValueType(0), A, B, C, Mask, 9065 VL); 9066 } 9067 case ISD::STORE: { 9068 auto *Store = cast<StoreSDNode>(N); 9069 SDValue Val = Store->getValue(); 9070 // Combine store of vmv.x.s to vse with VL of 1. 9071 // FIXME: Support FP. 9072 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 9073 SDValue Src = Val.getOperand(0); 9074 EVT VecVT = Src.getValueType(); 9075 EVT MemVT = Store->getMemoryVT(); 9076 // The memory VT and the element type must match. 9077 if (VecVT.getVectorElementType() == MemVT) { 9078 SDLoc DL(N); 9079 MVT MaskVT = getMaskTypeFor(VecVT); 9080 return DAG.getStoreVP( 9081 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 9082 DAG.getConstant(1, DL, MaskVT), 9083 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 9084 Store->getMemOperand(), Store->getAddressingMode(), 9085 Store->isTruncatingStore(), /*IsCompress*/ false); 9086 } 9087 } 9088 9089 break; 9090 } 9091 case ISD::SPLAT_VECTOR: { 9092 EVT VT = N->getValueType(0); 9093 // Only perform this combine on legal MVT types. 9094 if (!isTypeLegal(VT)) 9095 break; 9096 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 9097 DAG, Subtarget)) 9098 return Gather; 9099 break; 9100 } 9101 case RISCVISD::VMV_V_X_VL: { 9102 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 9103 // scalar input. 9104 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 9105 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 9106 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 9107 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 9108 return SDValue(N, 0); 9109 9110 break; 9111 } 9112 case ISD::INTRINSIC_WO_CHAIN: { 9113 unsigned IntNo = N->getConstantOperandVal(0); 9114 switch (IntNo) { 9115 // By default we do not combine any intrinsic. 9116 default: 9117 return SDValue(); 9118 case Intrinsic::riscv_vcpop: 9119 case Intrinsic::riscv_vcpop_mask: 9120 case Intrinsic::riscv_vfirst: 9121 case Intrinsic::riscv_vfirst_mask: { 9122 SDValue VL = N->getOperand(2); 9123 if (IntNo == Intrinsic::riscv_vcpop_mask || 9124 IntNo == Intrinsic::riscv_vfirst_mask) 9125 VL = N->getOperand(3); 9126 if (!isNullConstant(VL)) 9127 return SDValue(); 9128 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 9129 SDLoc DL(N); 9130 EVT VT = N->getValueType(0); 9131 if (IntNo == Intrinsic::riscv_vfirst || 9132 IntNo == Intrinsic::riscv_vfirst_mask) 9133 return DAG.getConstant(-1, DL, VT); 9134 return DAG.getConstant(0, DL, VT); 9135 } 9136 } 9137 } 9138 case ISD::BITCAST: { 9139 assert(Subtarget.useRVVForFixedLengthVectors()); 9140 SDValue N0 = N->getOperand(0); 9141 EVT VT = N->getValueType(0); 9142 EVT SrcVT = N0.getValueType(); 9143 // If this is a bitcast between a MVT::v4i1/v2i1/v1i1 and an illegal integer 9144 // type, widen both sides to avoid a trip through memory. 9145 if ((SrcVT == MVT::v1i1 || SrcVT == MVT::v2i1 || SrcVT == MVT::v4i1) && 9146 VT.isScalarInteger()) { 9147 unsigned NumConcats = 8 / SrcVT.getVectorNumElements(); 9148 SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT)); 9149 Ops[0] = N0; 9150 SDLoc DL(N); 9151 N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i1, Ops); 9152 N0 = DAG.getBitcast(MVT::i8, N0); 9153 return DAG.getNode(ISD::TRUNCATE, DL, VT, N0); 9154 } 9155 9156 return SDValue(); 9157 } 9158 } 9159 9160 return SDValue(); 9161 } 9162 9163 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 9164 const SDNode *N, CombineLevel Level) const { 9165 // The following folds are only desirable if `(OP _, c1 << c2)` can be 9166 // materialised in fewer instructions than `(OP _, c1)`: 9167 // 9168 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 9169 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 9170 SDValue N0 = N->getOperand(0); 9171 EVT Ty = N0.getValueType(); 9172 if (Ty.isScalarInteger() && 9173 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 9174 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 9175 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9176 if (C1 && C2) { 9177 const APInt &C1Int = C1->getAPIntValue(); 9178 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 9179 9180 // We can materialise `c1 << c2` into an add immediate, so it's "free", 9181 // and the combine should happen, to potentially allow further combines 9182 // later. 9183 if (ShiftedC1Int.getMinSignedBits() <= 64 && 9184 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 9185 return true; 9186 9187 // We can materialise `c1` in an add immediate, so it's "free", and the 9188 // combine should be prevented. 9189 if (C1Int.getMinSignedBits() <= 64 && 9190 isLegalAddImmediate(C1Int.getSExtValue())) 9191 return false; 9192 9193 // Neither constant will fit into an immediate, so find materialisation 9194 // costs. 9195 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 9196 Subtarget.getFeatureBits(), 9197 /*CompressionCost*/true); 9198 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 9199 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 9200 /*CompressionCost*/true); 9201 9202 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 9203 // combine should be prevented. 9204 if (C1Cost < ShiftedC1Cost) 9205 return false; 9206 } 9207 } 9208 return true; 9209 } 9210 9211 bool RISCVTargetLowering::targetShrinkDemandedConstant( 9212 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 9213 TargetLoweringOpt &TLO) const { 9214 // Delay this optimization as late as possible. 9215 if (!TLO.LegalOps) 9216 return false; 9217 9218 EVT VT = Op.getValueType(); 9219 if (VT.isVector()) 9220 return false; 9221 9222 // Only handle AND for now. 9223 if (Op.getOpcode() != ISD::AND) 9224 return false; 9225 9226 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 9227 if (!C) 9228 return false; 9229 9230 const APInt &Mask = C->getAPIntValue(); 9231 9232 // Clear all non-demanded bits initially. 9233 APInt ShrunkMask = Mask & DemandedBits; 9234 9235 // Try to make a smaller immediate by setting undemanded bits. 9236 9237 APInt ExpandedMask = Mask | ~DemandedBits; 9238 9239 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 9240 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 9241 }; 9242 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 9243 if (NewMask == Mask) 9244 return true; 9245 SDLoc DL(Op); 9246 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 9247 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 9248 return TLO.CombineTo(Op, NewOp); 9249 }; 9250 9251 // If the shrunk mask fits in sign extended 12 bits, let the target 9252 // independent code apply it. 9253 if (ShrunkMask.isSignedIntN(12)) 9254 return false; 9255 9256 // Preserve (and X, 0xffff) when zext.h is supported. 9257 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 9258 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 9259 if (IsLegalMask(NewMask)) 9260 return UseMask(NewMask); 9261 } 9262 9263 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 9264 if (VT == MVT::i64) { 9265 APInt NewMask = APInt(64, 0xffffffff); 9266 if (IsLegalMask(NewMask)) 9267 return UseMask(NewMask); 9268 } 9269 9270 // For the remaining optimizations, we need to be able to make a negative 9271 // number through a combination of mask and undemanded bits. 9272 if (!ExpandedMask.isNegative()) 9273 return false; 9274 9275 // What is the fewest number of bits we need to represent the negative number. 9276 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 9277 9278 // Try to make a 12 bit negative immediate. If that fails try to make a 32 9279 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 9280 APInt NewMask = ShrunkMask; 9281 if (MinSignedBits <= 12) 9282 NewMask.setBitsFrom(11); 9283 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 9284 NewMask.setBitsFrom(31); 9285 else 9286 return false; 9287 9288 // Check that our new mask is a subset of the demanded mask. 9289 assert(IsLegalMask(NewMask)); 9290 return UseMask(NewMask); 9291 } 9292 9293 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) { 9294 static const uint64_t GREVMasks[] = { 9295 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 9296 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 9297 9298 for (unsigned Stage = 0; Stage != 6; ++Stage) { 9299 unsigned Shift = 1 << Stage; 9300 if (ShAmt & Shift) { 9301 uint64_t Mask = GREVMasks[Stage]; 9302 uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask); 9303 if (IsGORC) 9304 Res |= x; 9305 x = Res; 9306 } 9307 } 9308 9309 return x; 9310 } 9311 9312 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 9313 KnownBits &Known, 9314 const APInt &DemandedElts, 9315 const SelectionDAG &DAG, 9316 unsigned Depth) const { 9317 unsigned BitWidth = Known.getBitWidth(); 9318 unsigned Opc = Op.getOpcode(); 9319 assert((Opc >= ISD::BUILTIN_OP_END || 9320 Opc == ISD::INTRINSIC_WO_CHAIN || 9321 Opc == ISD::INTRINSIC_W_CHAIN || 9322 Opc == ISD::INTRINSIC_VOID) && 9323 "Should use MaskedValueIsZero if you don't know whether Op" 9324 " is a target node!"); 9325 9326 Known.resetAll(); 9327 switch (Opc) { 9328 default: break; 9329 case RISCVISD::SELECT_CC: { 9330 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 9331 // If we don't know any bits, early out. 9332 if (Known.isUnknown()) 9333 break; 9334 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 9335 9336 // Only known if known in both the LHS and RHS. 9337 Known = KnownBits::commonBits(Known, Known2); 9338 break; 9339 } 9340 case RISCVISD::REMUW: { 9341 KnownBits Known2; 9342 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9343 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9344 // We only care about the lower 32 bits. 9345 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 9346 // Restore the original width by sign extending. 9347 Known = Known.sext(BitWidth); 9348 break; 9349 } 9350 case RISCVISD::DIVUW: { 9351 KnownBits Known2; 9352 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9353 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9354 // We only care about the lower 32 bits. 9355 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 9356 // Restore the original width by sign extending. 9357 Known = Known.sext(BitWidth); 9358 break; 9359 } 9360 case RISCVISD::CTZW: { 9361 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9362 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 9363 unsigned LowBits = Log2_32(PossibleTZ) + 1; 9364 Known.Zero.setBitsFrom(LowBits); 9365 break; 9366 } 9367 case RISCVISD::CLZW: { 9368 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9369 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 9370 unsigned LowBits = Log2_32(PossibleLZ) + 1; 9371 Known.Zero.setBitsFrom(LowBits); 9372 break; 9373 } 9374 case RISCVISD::GREV: 9375 case RISCVISD::GORC: { 9376 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 9377 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9378 unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1); 9379 bool IsGORC = Op.getOpcode() == RISCVISD::GORC; 9380 // To compute zeros, we need to invert the value and invert it back after. 9381 Known.Zero = 9382 ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC); 9383 Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC); 9384 } 9385 break; 9386 } 9387 case RISCVISD::READ_VLENB: { 9388 // If we know the minimum VLen from Zvl extensions, we can use that to 9389 // determine the trailing zeros of VLENB. 9390 // FIXME: Limit to 128 bit vectors until we have more testing. 9391 unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8; 9392 if (MinVLenB > 0) 9393 Known.Zero.setLowBits(Log2_32(MinVLenB)); 9394 // We assume VLENB is no more than 65536 / 8 bytes. 9395 Known.Zero.setBitsFrom(14); 9396 break; 9397 } 9398 case ISD::INTRINSIC_W_CHAIN: 9399 case ISD::INTRINSIC_WO_CHAIN: { 9400 unsigned IntNo = 9401 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 9402 switch (IntNo) { 9403 default: 9404 // We can't do anything for most intrinsics. 9405 break; 9406 case Intrinsic::riscv_vsetvli: 9407 case Intrinsic::riscv_vsetvlimax: 9408 case Intrinsic::riscv_vsetvli_opt: 9409 case Intrinsic::riscv_vsetvlimax_opt: 9410 // Assume that VL output is positive and would fit in an int32_t. 9411 // TODO: VLEN might be capped at 16 bits in a future V spec update. 9412 if (BitWidth >= 32) 9413 Known.Zero.setBitsFrom(31); 9414 break; 9415 } 9416 break; 9417 } 9418 } 9419 } 9420 9421 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 9422 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 9423 unsigned Depth) const { 9424 switch (Op.getOpcode()) { 9425 default: 9426 break; 9427 case RISCVISD::SELECT_CC: { 9428 unsigned Tmp = 9429 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 9430 if (Tmp == 1) return 1; // Early out. 9431 unsigned Tmp2 = 9432 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 9433 return std::min(Tmp, Tmp2); 9434 } 9435 case RISCVISD::SLLW: 9436 case RISCVISD::SRAW: 9437 case RISCVISD::SRLW: 9438 case RISCVISD::DIVW: 9439 case RISCVISD::DIVUW: 9440 case RISCVISD::REMUW: 9441 case RISCVISD::ROLW: 9442 case RISCVISD::RORW: 9443 case RISCVISD::GREVW: 9444 case RISCVISD::GORCW: 9445 case RISCVISD::FSLW: 9446 case RISCVISD::FSRW: 9447 case RISCVISD::SHFLW: 9448 case RISCVISD::UNSHFLW: 9449 case RISCVISD::BCOMPRESSW: 9450 case RISCVISD::BDECOMPRESSW: 9451 case RISCVISD::BFPW: 9452 case RISCVISD::FCVT_W_RV64: 9453 case RISCVISD::FCVT_WU_RV64: 9454 case RISCVISD::STRICT_FCVT_W_RV64: 9455 case RISCVISD::STRICT_FCVT_WU_RV64: 9456 // TODO: As the result is sign-extended, this is conservatively correct. A 9457 // more precise answer could be calculated for SRAW depending on known 9458 // bits in the shift amount. 9459 return 33; 9460 case RISCVISD::SHFL: 9461 case RISCVISD::UNSHFL: { 9462 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 9463 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 9464 // will stay within the upper 32 bits. If there were more than 32 sign bits 9465 // before there will be at least 33 sign bits after. 9466 if (Op.getValueType() == MVT::i64 && 9467 isa<ConstantSDNode>(Op.getOperand(1)) && 9468 (Op.getConstantOperandVal(1) & 0x10) == 0) { 9469 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 9470 if (Tmp > 32) 9471 return 33; 9472 } 9473 break; 9474 } 9475 case RISCVISD::VMV_X_S: { 9476 // The number of sign bits of the scalar result is computed by obtaining the 9477 // element type of the input vector operand, subtracting its width from the 9478 // XLEN, and then adding one (sign bit within the element type). If the 9479 // element type is wider than XLen, the least-significant XLEN bits are 9480 // taken. 9481 unsigned XLen = Subtarget.getXLen(); 9482 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 9483 if (EltBits <= XLen) 9484 return XLen - EltBits + 1; 9485 break; 9486 } 9487 } 9488 9489 return 1; 9490 } 9491 9492 const Constant * 9493 RISCVTargetLowering::getTargetConstantFromLoad(LoadSDNode *Ld) const { 9494 assert(Ld && "Unexpected null LoadSDNode"); 9495 if (!ISD::isNormalLoad(Ld)) 9496 return nullptr; 9497 9498 SDValue Ptr = Ld->getBasePtr(); 9499 9500 // Only constant pools with no offset are supported. 9501 auto GetSupportedConstantPool = [](SDValue Ptr) -> ConstantPoolSDNode * { 9502 auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr); 9503 if (!CNode || CNode->isMachineConstantPoolEntry() || 9504 CNode->getOffset() != 0) 9505 return nullptr; 9506 9507 return CNode; 9508 }; 9509 9510 // Simple case, LLA. 9511 if (Ptr.getOpcode() == RISCVISD::LLA) { 9512 auto *CNode = GetSupportedConstantPool(Ptr); 9513 if (!CNode || CNode->getTargetFlags() != 0) 9514 return nullptr; 9515 9516 return CNode->getConstVal(); 9517 } 9518 9519 // Look for a HI and ADD_LO pair. 9520 if (Ptr.getOpcode() != RISCVISD::ADD_LO || 9521 Ptr.getOperand(0).getOpcode() != RISCVISD::HI) 9522 return nullptr; 9523 9524 auto *CNodeLo = GetSupportedConstantPool(Ptr.getOperand(1)); 9525 auto *CNodeHi = GetSupportedConstantPool(Ptr.getOperand(0).getOperand(0)); 9526 9527 if (!CNodeLo || CNodeLo->getTargetFlags() != RISCVII::MO_LO || 9528 !CNodeHi || CNodeHi->getTargetFlags() != RISCVII::MO_HI) 9529 return nullptr; 9530 9531 if (CNodeLo->getConstVal() != CNodeHi->getConstVal()) 9532 return nullptr; 9533 9534 return CNodeLo->getConstVal(); 9535 } 9536 9537 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 9538 MachineBasicBlock *BB) { 9539 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 9540 9541 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 9542 // Should the count have wrapped while it was being read, we need to try 9543 // again. 9544 // ... 9545 // read: 9546 // rdcycleh x3 # load high word of cycle 9547 // rdcycle x2 # load low word of cycle 9548 // rdcycleh x4 # load high word of cycle 9549 // bne x3, x4, read # check if high word reads match, otherwise try again 9550 // ... 9551 9552 MachineFunction &MF = *BB->getParent(); 9553 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9554 MachineFunction::iterator It = ++BB->getIterator(); 9555 9556 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9557 MF.insert(It, LoopMBB); 9558 9559 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9560 MF.insert(It, DoneMBB); 9561 9562 // Transfer the remainder of BB and its successor edges to DoneMBB. 9563 DoneMBB->splice(DoneMBB->begin(), BB, 9564 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9565 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 9566 9567 BB->addSuccessor(LoopMBB); 9568 9569 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9570 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9571 Register LoReg = MI.getOperand(0).getReg(); 9572 Register HiReg = MI.getOperand(1).getReg(); 9573 DebugLoc DL = MI.getDebugLoc(); 9574 9575 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 9576 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 9577 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9578 .addReg(RISCV::X0); 9579 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 9580 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 9581 .addReg(RISCV::X0); 9582 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 9583 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9584 .addReg(RISCV::X0); 9585 9586 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 9587 .addReg(HiReg) 9588 .addReg(ReadAgainReg) 9589 .addMBB(LoopMBB); 9590 9591 LoopMBB->addSuccessor(LoopMBB); 9592 LoopMBB->addSuccessor(DoneMBB); 9593 9594 MI.eraseFromParent(); 9595 9596 return DoneMBB; 9597 } 9598 9599 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9600 MachineBasicBlock *BB) { 9601 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9602 9603 MachineFunction &MF = *BB->getParent(); 9604 DebugLoc DL = MI.getDebugLoc(); 9605 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9606 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9607 Register LoReg = MI.getOperand(0).getReg(); 9608 Register HiReg = MI.getOperand(1).getReg(); 9609 Register SrcReg = MI.getOperand(2).getReg(); 9610 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9611 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9612 9613 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9614 RI); 9615 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9616 MachineMemOperand *MMOLo = 9617 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9618 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9619 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9620 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9621 .addFrameIndex(FI) 9622 .addImm(0) 9623 .addMemOperand(MMOLo); 9624 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9625 .addFrameIndex(FI) 9626 .addImm(4) 9627 .addMemOperand(MMOHi); 9628 MI.eraseFromParent(); // The pseudo instruction is gone now. 9629 return BB; 9630 } 9631 9632 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9633 MachineBasicBlock *BB) { 9634 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9635 "Unexpected instruction"); 9636 9637 MachineFunction &MF = *BB->getParent(); 9638 DebugLoc DL = MI.getDebugLoc(); 9639 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9640 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9641 Register DstReg = MI.getOperand(0).getReg(); 9642 Register LoReg = MI.getOperand(1).getReg(); 9643 Register HiReg = MI.getOperand(2).getReg(); 9644 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9645 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9646 9647 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9648 MachineMemOperand *MMOLo = 9649 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9650 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9651 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9652 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9653 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9654 .addFrameIndex(FI) 9655 .addImm(0) 9656 .addMemOperand(MMOLo); 9657 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9658 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9659 .addFrameIndex(FI) 9660 .addImm(4) 9661 .addMemOperand(MMOHi); 9662 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9663 MI.eraseFromParent(); // The pseudo instruction is gone now. 9664 return BB; 9665 } 9666 9667 static bool isSelectPseudo(MachineInstr &MI) { 9668 switch (MI.getOpcode()) { 9669 default: 9670 return false; 9671 case RISCV::Select_GPR_Using_CC_GPR: 9672 case RISCV::Select_FPR16_Using_CC_GPR: 9673 case RISCV::Select_FPR32_Using_CC_GPR: 9674 case RISCV::Select_FPR64_Using_CC_GPR: 9675 return true; 9676 } 9677 } 9678 9679 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9680 unsigned RelOpcode, unsigned EqOpcode, 9681 const RISCVSubtarget &Subtarget) { 9682 DebugLoc DL = MI.getDebugLoc(); 9683 Register DstReg = MI.getOperand(0).getReg(); 9684 Register Src1Reg = MI.getOperand(1).getReg(); 9685 Register Src2Reg = MI.getOperand(2).getReg(); 9686 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9687 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9688 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9689 9690 // Save the current FFLAGS. 9691 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9692 9693 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9694 .addReg(Src1Reg) 9695 .addReg(Src2Reg); 9696 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9697 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9698 9699 // Restore the FFLAGS. 9700 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9701 .addReg(SavedFFlags, RegState::Kill); 9702 9703 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9704 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9705 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9706 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9707 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9708 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9709 9710 // Erase the pseudoinstruction. 9711 MI.eraseFromParent(); 9712 return BB; 9713 } 9714 9715 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9716 MachineBasicBlock *BB, 9717 const RISCVSubtarget &Subtarget) { 9718 // To "insert" Select_* instructions, we actually have to insert the triangle 9719 // control-flow pattern. The incoming instructions know the destination vreg 9720 // to set, the condition code register to branch on, the true/false values to 9721 // select between, and the condcode to use to select the appropriate branch. 9722 // 9723 // We produce the following control flow: 9724 // HeadMBB 9725 // | \ 9726 // | IfFalseMBB 9727 // | / 9728 // TailMBB 9729 // 9730 // When we find a sequence of selects we attempt to optimize their emission 9731 // by sharing the control flow. Currently we only handle cases where we have 9732 // multiple selects with the exact same condition (same LHS, RHS and CC). 9733 // The selects may be interleaved with other instructions if the other 9734 // instructions meet some requirements we deem safe: 9735 // - They are debug instructions. Otherwise, 9736 // - They do not have side-effects, do not access memory and their inputs do 9737 // not depend on the results of the select pseudo-instructions. 9738 // The TrueV/FalseV operands of the selects cannot depend on the result of 9739 // previous selects in the sequence. 9740 // These conditions could be further relaxed. See the X86 target for a 9741 // related approach and more information. 9742 Register LHS = MI.getOperand(1).getReg(); 9743 Register RHS = MI.getOperand(2).getReg(); 9744 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9745 9746 SmallVector<MachineInstr *, 4> SelectDebugValues; 9747 SmallSet<Register, 4> SelectDests; 9748 SelectDests.insert(MI.getOperand(0).getReg()); 9749 9750 MachineInstr *LastSelectPseudo = &MI; 9751 9752 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9753 SequenceMBBI != E; ++SequenceMBBI) { 9754 if (SequenceMBBI->isDebugInstr()) 9755 continue; 9756 if (isSelectPseudo(*SequenceMBBI)) { 9757 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9758 SequenceMBBI->getOperand(2).getReg() != RHS || 9759 SequenceMBBI->getOperand(3).getImm() != CC || 9760 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9761 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9762 break; 9763 LastSelectPseudo = &*SequenceMBBI; 9764 SequenceMBBI->collectDebugValues(SelectDebugValues); 9765 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9766 } else { 9767 if (SequenceMBBI->hasUnmodeledSideEffects() || 9768 SequenceMBBI->mayLoadOrStore()) 9769 break; 9770 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9771 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9772 })) 9773 break; 9774 } 9775 } 9776 9777 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9778 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9779 DebugLoc DL = MI.getDebugLoc(); 9780 MachineFunction::iterator I = ++BB->getIterator(); 9781 9782 MachineBasicBlock *HeadMBB = BB; 9783 MachineFunction *F = BB->getParent(); 9784 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9785 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9786 9787 F->insert(I, IfFalseMBB); 9788 F->insert(I, TailMBB); 9789 9790 // Transfer debug instructions associated with the selects to TailMBB. 9791 for (MachineInstr *DebugInstr : SelectDebugValues) { 9792 TailMBB->push_back(DebugInstr->removeFromParent()); 9793 } 9794 9795 // Move all instructions after the sequence to TailMBB. 9796 TailMBB->splice(TailMBB->end(), HeadMBB, 9797 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9798 // Update machine-CFG edges by transferring all successors of the current 9799 // block to the new block which will contain the Phi nodes for the selects. 9800 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9801 // Set the successors for HeadMBB. 9802 HeadMBB->addSuccessor(IfFalseMBB); 9803 HeadMBB->addSuccessor(TailMBB); 9804 9805 // Insert appropriate branch. 9806 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9807 .addReg(LHS) 9808 .addReg(RHS) 9809 .addMBB(TailMBB); 9810 9811 // IfFalseMBB just falls through to TailMBB. 9812 IfFalseMBB->addSuccessor(TailMBB); 9813 9814 // Create PHIs for all of the select pseudo-instructions. 9815 auto SelectMBBI = MI.getIterator(); 9816 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9817 auto InsertionPoint = TailMBB->begin(); 9818 while (SelectMBBI != SelectEnd) { 9819 auto Next = std::next(SelectMBBI); 9820 if (isSelectPseudo(*SelectMBBI)) { 9821 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9822 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9823 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9824 .addReg(SelectMBBI->getOperand(4).getReg()) 9825 .addMBB(HeadMBB) 9826 .addReg(SelectMBBI->getOperand(5).getReg()) 9827 .addMBB(IfFalseMBB); 9828 SelectMBBI->eraseFromParent(); 9829 } 9830 SelectMBBI = Next; 9831 } 9832 9833 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9834 return TailMBB; 9835 } 9836 9837 MachineBasicBlock * 9838 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9839 MachineBasicBlock *BB) const { 9840 switch (MI.getOpcode()) { 9841 default: 9842 llvm_unreachable("Unexpected instr type to insert"); 9843 case RISCV::ReadCycleWide: 9844 assert(!Subtarget.is64Bit() && 9845 "ReadCycleWrite is only to be used on riscv32"); 9846 return emitReadCycleWidePseudo(MI, BB); 9847 case RISCV::Select_GPR_Using_CC_GPR: 9848 case RISCV::Select_FPR16_Using_CC_GPR: 9849 case RISCV::Select_FPR32_Using_CC_GPR: 9850 case RISCV::Select_FPR64_Using_CC_GPR: 9851 return emitSelectPseudo(MI, BB, Subtarget); 9852 case RISCV::BuildPairF64Pseudo: 9853 return emitBuildPairF64Pseudo(MI, BB); 9854 case RISCV::SplitF64Pseudo: 9855 return emitSplitF64Pseudo(MI, BB); 9856 case RISCV::PseudoQuietFLE_H: 9857 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9858 case RISCV::PseudoQuietFLT_H: 9859 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9860 case RISCV::PseudoQuietFLE_S: 9861 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9862 case RISCV::PseudoQuietFLT_S: 9863 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9864 case RISCV::PseudoQuietFLE_D: 9865 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9866 case RISCV::PseudoQuietFLT_D: 9867 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9868 } 9869 } 9870 9871 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9872 SDNode *Node) const { 9873 // Add FRM dependency to any instructions with dynamic rounding mode. 9874 unsigned Opc = MI.getOpcode(); 9875 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9876 if (Idx < 0) 9877 return; 9878 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9879 return; 9880 // If the instruction already reads FRM, don't add another read. 9881 if (MI.readsRegister(RISCV::FRM)) 9882 return; 9883 MI.addOperand( 9884 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9885 } 9886 9887 // Calling Convention Implementation. 9888 // The expectations for frontend ABI lowering vary from target to target. 9889 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 9890 // details, but this is a longer term goal. For now, we simply try to keep the 9891 // role of the frontend as simple and well-defined as possible. The rules can 9892 // be summarised as: 9893 // * Never split up large scalar arguments. We handle them here. 9894 // * If a hardfloat calling convention is being used, and the struct may be 9895 // passed in a pair of registers (fp+fp, int+fp), and both registers are 9896 // available, then pass as two separate arguments. If either the GPRs or FPRs 9897 // are exhausted, then pass according to the rule below. 9898 // * If a struct could never be passed in registers or directly in a stack 9899 // slot (as it is larger than 2*XLEN and the floating point rules don't 9900 // apply), then pass it using a pointer with the byval attribute. 9901 // * If a struct is less than 2*XLEN, then coerce to either a two-element 9902 // word-sized array or a 2*XLEN scalar (depending on alignment). 9903 // * The frontend can determine whether a struct is returned by reference or 9904 // not based on its size and fields. If it will be returned by reference, the 9905 // frontend must modify the prototype so a pointer with the sret annotation is 9906 // passed as the first argument. This is not necessary for large scalar 9907 // returns. 9908 // * Struct return values and varargs should be coerced to structs containing 9909 // register-size fields in the same situations they would be for fixed 9910 // arguments. 9911 9912 static const MCPhysReg ArgGPRs[] = { 9913 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 9914 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 9915 }; 9916 static const MCPhysReg ArgFPR16s[] = { 9917 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 9918 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 9919 }; 9920 static const MCPhysReg ArgFPR32s[] = { 9921 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 9922 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 9923 }; 9924 static const MCPhysReg ArgFPR64s[] = { 9925 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 9926 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 9927 }; 9928 // This is an interim calling convention and it may be changed in the future. 9929 static const MCPhysReg ArgVRs[] = { 9930 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 9931 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 9932 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 9933 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 9934 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 9935 RISCV::V20M2, RISCV::V22M2}; 9936 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 9937 RISCV::V20M4}; 9938 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 9939 9940 // Pass a 2*XLEN argument that has been split into two XLEN values through 9941 // registers or the stack as necessary. 9942 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 9943 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 9944 MVT ValVT2, MVT LocVT2, 9945 ISD::ArgFlagsTy ArgFlags2) { 9946 unsigned XLenInBytes = XLen / 8; 9947 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9948 // At least one half can be passed via register. 9949 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 9950 VA1.getLocVT(), CCValAssign::Full)); 9951 } else { 9952 // Both halves must be passed on the stack, with proper alignment. 9953 Align StackAlign = 9954 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 9955 State.addLoc( 9956 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 9957 State.AllocateStack(XLenInBytes, StackAlign), 9958 VA1.getLocVT(), CCValAssign::Full)); 9959 State.addLoc(CCValAssign::getMem( 9960 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9961 LocVT2, CCValAssign::Full)); 9962 return false; 9963 } 9964 9965 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9966 // The second half can also be passed via register. 9967 State.addLoc( 9968 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 9969 } else { 9970 // The second half is passed via the stack, without additional alignment. 9971 State.addLoc(CCValAssign::getMem( 9972 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9973 LocVT2, CCValAssign::Full)); 9974 } 9975 9976 return false; 9977 } 9978 9979 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 9980 Optional<unsigned> FirstMaskArgument, 9981 CCState &State, const RISCVTargetLowering &TLI) { 9982 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 9983 if (RC == &RISCV::VRRegClass) { 9984 // Assign the first mask argument to V0. 9985 // This is an interim calling convention and it may be changed in the 9986 // future. 9987 if (FirstMaskArgument && ValNo == *FirstMaskArgument) 9988 return State.AllocateReg(RISCV::V0); 9989 return State.AllocateReg(ArgVRs); 9990 } 9991 if (RC == &RISCV::VRM2RegClass) 9992 return State.AllocateReg(ArgVRM2s); 9993 if (RC == &RISCV::VRM4RegClass) 9994 return State.AllocateReg(ArgVRM4s); 9995 if (RC == &RISCV::VRM8RegClass) 9996 return State.AllocateReg(ArgVRM8s); 9997 llvm_unreachable("Unhandled register class for ValueType"); 9998 } 9999 10000 // Implements the RISC-V calling convention. Returns true upon failure. 10001 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 10002 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 10003 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 10004 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 10005 Optional<unsigned> FirstMaskArgument) { 10006 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 10007 assert(XLen == 32 || XLen == 64); 10008 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 10009 10010 // Any return value split in to more than two values can't be returned 10011 // directly. Vectors are returned via the available vector registers. 10012 if (!LocVT.isVector() && IsRet && ValNo > 1) 10013 return true; 10014 10015 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 10016 // variadic argument, or if no F16/F32 argument registers are available. 10017 bool UseGPRForF16_F32 = true; 10018 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 10019 // variadic argument, or if no F64 argument registers are available. 10020 bool UseGPRForF64 = true; 10021 10022 switch (ABI) { 10023 default: 10024 llvm_unreachable("Unexpected ABI"); 10025 case RISCVABI::ABI_ILP32: 10026 case RISCVABI::ABI_LP64: 10027 break; 10028 case RISCVABI::ABI_ILP32F: 10029 case RISCVABI::ABI_LP64F: 10030 UseGPRForF16_F32 = !IsFixed; 10031 break; 10032 case RISCVABI::ABI_ILP32D: 10033 case RISCVABI::ABI_LP64D: 10034 UseGPRForF16_F32 = !IsFixed; 10035 UseGPRForF64 = !IsFixed; 10036 break; 10037 } 10038 10039 // FPR16, FPR32, and FPR64 alias each other. 10040 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 10041 UseGPRForF16_F32 = true; 10042 UseGPRForF64 = true; 10043 } 10044 10045 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 10046 // similar local variables rather than directly checking against the target 10047 // ABI. 10048 10049 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 10050 LocVT = XLenVT; 10051 LocInfo = CCValAssign::BCvt; 10052 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 10053 LocVT = MVT::i64; 10054 LocInfo = CCValAssign::BCvt; 10055 } 10056 10057 // If this is a variadic argument, the RISC-V calling convention requires 10058 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 10059 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 10060 // be used regardless of whether the original argument was split during 10061 // legalisation or not. The argument will not be passed by registers if the 10062 // original type is larger than 2*XLEN, so the register alignment rule does 10063 // not apply. 10064 unsigned TwoXLenInBytes = (2 * XLen) / 8; 10065 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 10066 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 10067 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 10068 // Skip 'odd' register if necessary. 10069 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 10070 State.AllocateReg(ArgGPRs); 10071 } 10072 10073 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 10074 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 10075 State.getPendingArgFlags(); 10076 10077 assert(PendingLocs.size() == PendingArgFlags.size() && 10078 "PendingLocs and PendingArgFlags out of sync"); 10079 10080 // Handle passing f64 on RV32D with a soft float ABI or when floating point 10081 // registers are exhausted. 10082 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 10083 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 10084 "Can't lower f64 if it is split"); 10085 // Depending on available argument GPRS, f64 may be passed in a pair of 10086 // GPRs, split between a GPR and the stack, or passed completely on the 10087 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 10088 // cases. 10089 Register Reg = State.AllocateReg(ArgGPRs); 10090 LocVT = MVT::i32; 10091 if (!Reg) { 10092 unsigned StackOffset = State.AllocateStack(8, Align(8)); 10093 State.addLoc( 10094 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10095 return false; 10096 } 10097 if (!State.AllocateReg(ArgGPRs)) 10098 State.AllocateStack(4, Align(4)); 10099 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10100 return false; 10101 } 10102 10103 // Fixed-length vectors are located in the corresponding scalable-vector 10104 // container types. 10105 if (ValVT.isFixedLengthVector()) 10106 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10107 10108 // Split arguments might be passed indirectly, so keep track of the pending 10109 // values. Split vectors are passed via a mix of registers and indirectly, so 10110 // treat them as we would any other argument. 10111 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 10112 LocVT = XLenVT; 10113 LocInfo = CCValAssign::Indirect; 10114 PendingLocs.push_back( 10115 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 10116 PendingArgFlags.push_back(ArgFlags); 10117 if (!ArgFlags.isSplitEnd()) { 10118 return false; 10119 } 10120 } 10121 10122 // If the split argument only had two elements, it should be passed directly 10123 // in registers or on the stack. 10124 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 10125 PendingLocs.size() <= 2) { 10126 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 10127 // Apply the normal calling convention rules to the first half of the 10128 // split argument. 10129 CCValAssign VA = PendingLocs[0]; 10130 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 10131 PendingLocs.clear(); 10132 PendingArgFlags.clear(); 10133 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 10134 ArgFlags); 10135 } 10136 10137 // Allocate to a register if possible, or else a stack slot. 10138 Register Reg; 10139 unsigned StoreSizeBytes = XLen / 8; 10140 Align StackAlign = Align(XLen / 8); 10141 10142 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 10143 Reg = State.AllocateReg(ArgFPR16s); 10144 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 10145 Reg = State.AllocateReg(ArgFPR32s); 10146 else if (ValVT == MVT::f64 && !UseGPRForF64) 10147 Reg = State.AllocateReg(ArgFPR64s); 10148 else if (ValVT.isVector()) { 10149 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 10150 if (!Reg) { 10151 // For return values, the vector must be passed fully via registers or 10152 // via the stack. 10153 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 10154 // but we're using all of them. 10155 if (IsRet) 10156 return true; 10157 // Try using a GPR to pass the address 10158 if ((Reg = State.AllocateReg(ArgGPRs))) { 10159 LocVT = XLenVT; 10160 LocInfo = CCValAssign::Indirect; 10161 } else if (ValVT.isScalableVector()) { 10162 LocVT = XLenVT; 10163 LocInfo = CCValAssign::Indirect; 10164 } else { 10165 // Pass fixed-length vectors on the stack. 10166 LocVT = ValVT; 10167 StoreSizeBytes = ValVT.getStoreSize(); 10168 // Align vectors to their element sizes, being careful for vXi1 10169 // vectors. 10170 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10171 } 10172 } 10173 } else { 10174 Reg = State.AllocateReg(ArgGPRs); 10175 } 10176 10177 unsigned StackOffset = 10178 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 10179 10180 // If we reach this point and PendingLocs is non-empty, we must be at the 10181 // end of a split argument that must be passed indirectly. 10182 if (!PendingLocs.empty()) { 10183 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 10184 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 10185 10186 for (auto &It : PendingLocs) { 10187 if (Reg) 10188 It.convertToReg(Reg); 10189 else 10190 It.convertToMem(StackOffset); 10191 State.addLoc(It); 10192 } 10193 PendingLocs.clear(); 10194 PendingArgFlags.clear(); 10195 return false; 10196 } 10197 10198 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 10199 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 10200 "Expected an XLenVT or vector types at this stage"); 10201 10202 if (Reg) { 10203 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10204 return false; 10205 } 10206 10207 // When a floating-point value is passed on the stack, no bit-conversion is 10208 // needed. 10209 if (ValVT.isFloatingPoint()) { 10210 LocVT = ValVT; 10211 LocInfo = CCValAssign::Full; 10212 } 10213 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10214 return false; 10215 } 10216 10217 template <typename ArgTy> 10218 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 10219 for (const auto &ArgIdx : enumerate(Args)) { 10220 MVT ArgVT = ArgIdx.value().VT; 10221 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 10222 return ArgIdx.index(); 10223 } 10224 return None; 10225 } 10226 10227 void RISCVTargetLowering::analyzeInputArgs( 10228 MachineFunction &MF, CCState &CCInfo, 10229 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 10230 RISCVCCAssignFn Fn) const { 10231 unsigned NumArgs = Ins.size(); 10232 FunctionType *FType = MF.getFunction().getFunctionType(); 10233 10234 Optional<unsigned> FirstMaskArgument; 10235 if (Subtarget.hasVInstructions()) 10236 FirstMaskArgument = preAssignMask(Ins); 10237 10238 for (unsigned i = 0; i != NumArgs; ++i) { 10239 MVT ArgVT = Ins[i].VT; 10240 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 10241 10242 Type *ArgTy = nullptr; 10243 if (IsRet) 10244 ArgTy = FType->getReturnType(); 10245 else if (Ins[i].isOrigArg()) 10246 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 10247 10248 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10249 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10250 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 10251 FirstMaskArgument)) { 10252 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 10253 << EVT(ArgVT).getEVTString() << '\n'); 10254 llvm_unreachable(nullptr); 10255 } 10256 } 10257 } 10258 10259 void RISCVTargetLowering::analyzeOutputArgs( 10260 MachineFunction &MF, CCState &CCInfo, 10261 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 10262 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 10263 unsigned NumArgs = Outs.size(); 10264 10265 Optional<unsigned> FirstMaskArgument; 10266 if (Subtarget.hasVInstructions()) 10267 FirstMaskArgument = preAssignMask(Outs); 10268 10269 for (unsigned i = 0; i != NumArgs; i++) { 10270 MVT ArgVT = Outs[i].VT; 10271 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10272 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 10273 10274 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10275 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10276 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 10277 FirstMaskArgument)) { 10278 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 10279 << EVT(ArgVT).getEVTString() << "\n"); 10280 llvm_unreachable(nullptr); 10281 } 10282 } 10283 } 10284 10285 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 10286 // values. 10287 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 10288 const CCValAssign &VA, const SDLoc &DL, 10289 const RISCVSubtarget &Subtarget) { 10290 switch (VA.getLocInfo()) { 10291 default: 10292 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10293 case CCValAssign::Full: 10294 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 10295 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 10296 break; 10297 case CCValAssign::BCvt: 10298 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10299 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 10300 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10301 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 10302 else 10303 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 10304 break; 10305 } 10306 return Val; 10307 } 10308 10309 // The caller is responsible for loading the full value if the argument is 10310 // passed with CCValAssign::Indirect. 10311 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 10312 const CCValAssign &VA, const SDLoc &DL, 10313 const RISCVTargetLowering &TLI) { 10314 MachineFunction &MF = DAG.getMachineFunction(); 10315 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10316 EVT LocVT = VA.getLocVT(); 10317 SDValue Val; 10318 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 10319 Register VReg = RegInfo.createVirtualRegister(RC); 10320 RegInfo.addLiveIn(VA.getLocReg(), VReg); 10321 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 10322 10323 if (VA.getLocInfo() == CCValAssign::Indirect) 10324 return Val; 10325 10326 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 10327 } 10328 10329 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 10330 const CCValAssign &VA, const SDLoc &DL, 10331 const RISCVSubtarget &Subtarget) { 10332 EVT LocVT = VA.getLocVT(); 10333 10334 switch (VA.getLocInfo()) { 10335 default: 10336 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10337 case CCValAssign::Full: 10338 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 10339 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 10340 break; 10341 case CCValAssign::BCvt: 10342 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10343 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 10344 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10345 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 10346 else 10347 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 10348 break; 10349 } 10350 return Val; 10351 } 10352 10353 // The caller is responsible for loading the full value if the argument is 10354 // passed with CCValAssign::Indirect. 10355 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 10356 const CCValAssign &VA, const SDLoc &DL) { 10357 MachineFunction &MF = DAG.getMachineFunction(); 10358 MachineFrameInfo &MFI = MF.getFrameInfo(); 10359 EVT LocVT = VA.getLocVT(); 10360 EVT ValVT = VA.getValVT(); 10361 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 10362 if (ValVT.isScalableVector()) { 10363 // When the value is a scalable vector, we save the pointer which points to 10364 // the scalable vector value in the stack. The ValVT will be the pointer 10365 // type, instead of the scalable vector type. 10366 ValVT = LocVT; 10367 } 10368 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 10369 /*IsImmutable=*/true); 10370 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 10371 SDValue Val; 10372 10373 ISD::LoadExtType ExtType; 10374 switch (VA.getLocInfo()) { 10375 default: 10376 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10377 case CCValAssign::Full: 10378 case CCValAssign::Indirect: 10379 case CCValAssign::BCvt: 10380 ExtType = ISD::NON_EXTLOAD; 10381 break; 10382 } 10383 Val = DAG.getExtLoad( 10384 ExtType, DL, LocVT, Chain, FIN, 10385 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 10386 return Val; 10387 } 10388 10389 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 10390 const CCValAssign &VA, const SDLoc &DL) { 10391 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 10392 "Unexpected VA"); 10393 MachineFunction &MF = DAG.getMachineFunction(); 10394 MachineFrameInfo &MFI = MF.getFrameInfo(); 10395 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10396 10397 if (VA.isMemLoc()) { 10398 // f64 is passed on the stack. 10399 int FI = 10400 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 10401 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10402 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 10403 MachinePointerInfo::getFixedStack(MF, FI)); 10404 } 10405 10406 assert(VA.isRegLoc() && "Expected register VA assignment"); 10407 10408 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10409 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 10410 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 10411 SDValue Hi; 10412 if (VA.getLocReg() == RISCV::X17) { 10413 // Second half of f64 is passed on the stack. 10414 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 10415 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10416 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 10417 MachinePointerInfo::getFixedStack(MF, FI)); 10418 } else { 10419 // Second half of f64 is passed in another GPR. 10420 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10421 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 10422 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 10423 } 10424 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 10425 } 10426 10427 // FastCC has less than 1% performance improvement for some particular 10428 // benchmark. But theoretically, it may has benenfit for some cases. 10429 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 10430 unsigned ValNo, MVT ValVT, MVT LocVT, 10431 CCValAssign::LocInfo LocInfo, 10432 ISD::ArgFlagsTy ArgFlags, CCState &State, 10433 bool IsFixed, bool IsRet, Type *OrigTy, 10434 const RISCVTargetLowering &TLI, 10435 Optional<unsigned> FirstMaskArgument) { 10436 10437 // X5 and X6 might be used for save-restore libcall. 10438 static const MCPhysReg GPRList[] = { 10439 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 10440 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 10441 RISCV::X29, RISCV::X30, RISCV::X31}; 10442 10443 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10444 if (unsigned Reg = State.AllocateReg(GPRList)) { 10445 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10446 return false; 10447 } 10448 } 10449 10450 if (LocVT == MVT::f16) { 10451 static const MCPhysReg FPR16List[] = { 10452 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 10453 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 10454 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 10455 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 10456 if (unsigned Reg = State.AllocateReg(FPR16List)) { 10457 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10458 return false; 10459 } 10460 } 10461 10462 if (LocVT == MVT::f32) { 10463 static const MCPhysReg FPR32List[] = { 10464 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 10465 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 10466 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 10467 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 10468 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10469 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10470 return false; 10471 } 10472 } 10473 10474 if (LocVT == MVT::f64) { 10475 static const MCPhysReg FPR64List[] = { 10476 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 10477 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 10478 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 10479 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 10480 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10481 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10482 return false; 10483 } 10484 } 10485 10486 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 10487 unsigned Offset4 = State.AllocateStack(4, Align(4)); 10488 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 10489 return false; 10490 } 10491 10492 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 10493 unsigned Offset5 = State.AllocateStack(8, Align(8)); 10494 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 10495 return false; 10496 } 10497 10498 if (LocVT.isVector()) { 10499 if (unsigned Reg = 10500 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 10501 // Fixed-length vectors are located in the corresponding scalable-vector 10502 // container types. 10503 if (ValVT.isFixedLengthVector()) 10504 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10505 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10506 } else { 10507 // Try and pass the address via a "fast" GPR. 10508 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 10509 LocInfo = CCValAssign::Indirect; 10510 LocVT = TLI.getSubtarget().getXLenVT(); 10511 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 10512 } else if (ValVT.isFixedLengthVector()) { 10513 auto StackAlign = 10514 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10515 unsigned StackOffset = 10516 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 10517 State.addLoc( 10518 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10519 } else { 10520 // Can't pass scalable vectors on the stack. 10521 return true; 10522 } 10523 } 10524 10525 return false; 10526 } 10527 10528 return true; // CC didn't match. 10529 } 10530 10531 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 10532 CCValAssign::LocInfo LocInfo, 10533 ISD::ArgFlagsTy ArgFlags, CCState &State) { 10534 10535 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10536 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 10537 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 10538 static const MCPhysReg GPRList[] = { 10539 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 10540 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 10541 if (unsigned Reg = State.AllocateReg(GPRList)) { 10542 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10543 return false; 10544 } 10545 } 10546 10547 if (LocVT == MVT::f32) { 10548 // Pass in STG registers: F1, ..., F6 10549 // fs0 ... fs5 10550 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 10551 RISCV::F18_F, RISCV::F19_F, 10552 RISCV::F20_F, RISCV::F21_F}; 10553 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10554 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10555 return false; 10556 } 10557 } 10558 10559 if (LocVT == MVT::f64) { 10560 // Pass in STG registers: D1, ..., D6 10561 // fs6 ... fs11 10562 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 10563 RISCV::F24_D, RISCV::F25_D, 10564 RISCV::F26_D, RISCV::F27_D}; 10565 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10566 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10567 return false; 10568 } 10569 } 10570 10571 report_fatal_error("No registers left in GHC calling convention"); 10572 return true; 10573 } 10574 10575 // Transform physical registers into virtual registers. 10576 SDValue RISCVTargetLowering::LowerFormalArguments( 10577 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 10578 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 10579 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 10580 10581 MachineFunction &MF = DAG.getMachineFunction(); 10582 10583 switch (CallConv) { 10584 default: 10585 report_fatal_error("Unsupported calling convention"); 10586 case CallingConv::C: 10587 case CallingConv::Fast: 10588 break; 10589 case CallingConv::GHC: 10590 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10591 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10592 report_fatal_error( 10593 "GHC calling convention requires the F and D instruction set extensions"); 10594 } 10595 10596 const Function &Func = MF.getFunction(); 10597 if (Func.hasFnAttribute("interrupt")) { 10598 if (!Func.arg_empty()) 10599 report_fatal_error( 10600 "Functions with the interrupt attribute cannot have arguments!"); 10601 10602 StringRef Kind = 10603 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10604 10605 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10606 report_fatal_error( 10607 "Function interrupt attribute argument not supported!"); 10608 } 10609 10610 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10611 MVT XLenVT = Subtarget.getXLenVT(); 10612 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10613 // Used with vargs to acumulate store chains. 10614 std::vector<SDValue> OutChains; 10615 10616 // Assign locations to all of the incoming arguments. 10617 SmallVector<CCValAssign, 16> ArgLocs; 10618 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10619 10620 if (CallConv == CallingConv::GHC) 10621 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10622 else 10623 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10624 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10625 : CC_RISCV); 10626 10627 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10628 CCValAssign &VA = ArgLocs[i]; 10629 SDValue ArgValue; 10630 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10631 // case. 10632 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10633 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10634 else if (VA.isRegLoc()) 10635 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10636 else 10637 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10638 10639 if (VA.getLocInfo() == CCValAssign::Indirect) { 10640 // If the original argument was split and passed by reference (e.g. i128 10641 // on RV32), we need to load all parts of it here (using the same 10642 // address). Vectors may be partly split to registers and partly to the 10643 // stack, in which case the base address is partly offset and subsequent 10644 // stores are relative to that. 10645 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10646 MachinePointerInfo())); 10647 unsigned ArgIndex = Ins[i].OrigArgIndex; 10648 unsigned ArgPartOffset = Ins[i].PartOffset; 10649 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10650 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10651 CCValAssign &PartVA = ArgLocs[i + 1]; 10652 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10653 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10654 if (PartVA.getValVT().isScalableVector()) 10655 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10656 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10657 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10658 MachinePointerInfo())); 10659 ++i; 10660 } 10661 continue; 10662 } 10663 InVals.push_back(ArgValue); 10664 } 10665 10666 if (IsVarArg) { 10667 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10668 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10669 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10670 MachineFrameInfo &MFI = MF.getFrameInfo(); 10671 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10672 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10673 10674 // Offset of the first variable argument from stack pointer, and size of 10675 // the vararg save area. For now, the varargs save area is either zero or 10676 // large enough to hold a0-a7. 10677 int VaArgOffset, VarArgsSaveSize; 10678 10679 // If all registers are allocated, then all varargs must be passed on the 10680 // stack and we don't need to save any argregs. 10681 if (ArgRegs.size() == Idx) { 10682 VaArgOffset = CCInfo.getNextStackOffset(); 10683 VarArgsSaveSize = 0; 10684 } else { 10685 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10686 VaArgOffset = -VarArgsSaveSize; 10687 } 10688 10689 // Record the frame index of the first variable argument 10690 // which is a value necessary to VASTART. 10691 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10692 RVFI->setVarArgsFrameIndex(FI); 10693 10694 // If saving an odd number of registers then create an extra stack slot to 10695 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10696 // offsets to even-numbered registered remain 2*XLEN-aligned. 10697 if (Idx % 2) { 10698 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10699 VarArgsSaveSize += XLenInBytes; 10700 } 10701 10702 // Copy the integer registers that may have been used for passing varargs 10703 // to the vararg save area. 10704 for (unsigned I = Idx; I < ArgRegs.size(); 10705 ++I, VaArgOffset += XLenInBytes) { 10706 const Register Reg = RegInfo.createVirtualRegister(RC); 10707 RegInfo.addLiveIn(ArgRegs[I], Reg); 10708 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10709 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10710 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10711 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10712 MachinePointerInfo::getFixedStack(MF, FI)); 10713 cast<StoreSDNode>(Store.getNode()) 10714 ->getMemOperand() 10715 ->setValue((Value *)nullptr); 10716 OutChains.push_back(Store); 10717 } 10718 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10719 } 10720 10721 // All stores are grouped in one node to allow the matching between 10722 // the size of Ins and InVals. This only happens for vararg functions. 10723 if (!OutChains.empty()) { 10724 OutChains.push_back(Chain); 10725 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10726 } 10727 10728 return Chain; 10729 } 10730 10731 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10732 /// for tail call optimization. 10733 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10734 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10735 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10736 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10737 10738 auto &Callee = CLI.Callee; 10739 auto CalleeCC = CLI.CallConv; 10740 auto &Outs = CLI.Outs; 10741 auto &Caller = MF.getFunction(); 10742 auto CallerCC = Caller.getCallingConv(); 10743 10744 // Exception-handling functions need a special set of instructions to 10745 // indicate a return to the hardware. Tail-calling another function would 10746 // probably break this. 10747 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10748 // should be expanded as new function attributes are introduced. 10749 if (Caller.hasFnAttribute("interrupt")) 10750 return false; 10751 10752 // Do not tail call opt if the stack is used to pass parameters. 10753 if (CCInfo.getNextStackOffset() != 0) 10754 return false; 10755 10756 // Do not tail call opt if any parameters need to be passed indirectly. 10757 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10758 // passed indirectly. So the address of the value will be passed in a 10759 // register, or if not available, then the address is put on the stack. In 10760 // order to pass indirectly, space on the stack often needs to be allocated 10761 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10762 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10763 // are passed CCValAssign::Indirect. 10764 for (auto &VA : ArgLocs) 10765 if (VA.getLocInfo() == CCValAssign::Indirect) 10766 return false; 10767 10768 // Do not tail call opt if either caller or callee uses struct return 10769 // semantics. 10770 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10771 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10772 if (IsCallerStructRet || IsCalleeStructRet) 10773 return false; 10774 10775 // Externally-defined functions with weak linkage should not be 10776 // tail-called. The behaviour of branch instructions in this situation (as 10777 // used for tail calls) is implementation-defined, so we cannot rely on the 10778 // linker replacing the tail call with a return. 10779 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10780 const GlobalValue *GV = G->getGlobal(); 10781 if (GV->hasExternalWeakLinkage()) 10782 return false; 10783 } 10784 10785 // The callee has to preserve all registers the caller needs to preserve. 10786 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10787 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10788 if (CalleeCC != CallerCC) { 10789 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10790 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10791 return false; 10792 } 10793 10794 // Byval parameters hand the function a pointer directly into the stack area 10795 // we want to reuse during a tail call. Working around this *is* possible 10796 // but less efficient and uglier in LowerCall. 10797 for (auto &Arg : Outs) 10798 if (Arg.Flags.isByVal()) 10799 return false; 10800 10801 return true; 10802 } 10803 10804 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10805 return DAG.getDataLayout().getPrefTypeAlign( 10806 VT.getTypeForEVT(*DAG.getContext())); 10807 } 10808 10809 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10810 // and output parameter nodes. 10811 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10812 SmallVectorImpl<SDValue> &InVals) const { 10813 SelectionDAG &DAG = CLI.DAG; 10814 SDLoc &DL = CLI.DL; 10815 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10816 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10817 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10818 SDValue Chain = CLI.Chain; 10819 SDValue Callee = CLI.Callee; 10820 bool &IsTailCall = CLI.IsTailCall; 10821 CallingConv::ID CallConv = CLI.CallConv; 10822 bool IsVarArg = CLI.IsVarArg; 10823 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10824 MVT XLenVT = Subtarget.getXLenVT(); 10825 10826 MachineFunction &MF = DAG.getMachineFunction(); 10827 10828 // Analyze the operands of the call, assigning locations to each operand. 10829 SmallVector<CCValAssign, 16> ArgLocs; 10830 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10831 10832 if (CallConv == CallingConv::GHC) 10833 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10834 else 10835 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10836 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10837 : CC_RISCV); 10838 10839 // Check if it's really possible to do a tail call. 10840 if (IsTailCall) 10841 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10842 10843 if (IsTailCall) 10844 ++NumTailCalls; 10845 else if (CLI.CB && CLI.CB->isMustTailCall()) 10846 report_fatal_error("failed to perform tail call elimination on a call " 10847 "site marked musttail"); 10848 10849 // Get a count of how many bytes are to be pushed on the stack. 10850 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10851 10852 // Create local copies for byval args 10853 SmallVector<SDValue, 8> ByValArgs; 10854 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10855 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10856 if (!Flags.isByVal()) 10857 continue; 10858 10859 SDValue Arg = OutVals[i]; 10860 unsigned Size = Flags.getByValSize(); 10861 Align Alignment = Flags.getNonZeroByValAlign(); 10862 10863 int FI = 10864 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10865 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10866 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10867 10868 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10869 /*IsVolatile=*/false, 10870 /*AlwaysInline=*/false, IsTailCall, 10871 MachinePointerInfo(), MachinePointerInfo()); 10872 ByValArgs.push_back(FIPtr); 10873 } 10874 10875 if (!IsTailCall) 10876 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10877 10878 // Copy argument values to their designated locations. 10879 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10880 SmallVector<SDValue, 8> MemOpChains; 10881 SDValue StackPtr; 10882 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10883 CCValAssign &VA = ArgLocs[i]; 10884 SDValue ArgValue = OutVals[i]; 10885 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10886 10887 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10888 bool IsF64OnRV32DSoftABI = 10889 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 10890 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 10891 SDValue SplitF64 = DAG.getNode( 10892 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 10893 SDValue Lo = SplitF64.getValue(0); 10894 SDValue Hi = SplitF64.getValue(1); 10895 10896 Register RegLo = VA.getLocReg(); 10897 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 10898 10899 if (RegLo == RISCV::X17) { 10900 // Second half of f64 is passed on the stack. 10901 // Work out the address of the stack slot. 10902 if (!StackPtr.getNode()) 10903 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10904 // Emit the store. 10905 MemOpChains.push_back( 10906 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 10907 } else { 10908 // Second half of f64 is passed in another GPR. 10909 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10910 Register RegHigh = RegLo + 1; 10911 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 10912 } 10913 continue; 10914 } 10915 10916 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 10917 // as any other MemLoc. 10918 10919 // Promote the value if needed. 10920 // For now, only handle fully promoted and indirect arguments. 10921 if (VA.getLocInfo() == CCValAssign::Indirect) { 10922 // Store the argument in a stack slot and pass its address. 10923 Align StackAlign = 10924 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 10925 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 10926 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 10927 // If the original argument was split (e.g. i128), we need 10928 // to store the required parts of it here (and pass just one address). 10929 // Vectors may be partly split to registers and partly to the stack, in 10930 // which case the base address is partly offset and subsequent stores are 10931 // relative to that. 10932 unsigned ArgIndex = Outs[i].OrigArgIndex; 10933 unsigned ArgPartOffset = Outs[i].PartOffset; 10934 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10935 // Calculate the total size to store. We don't have access to what we're 10936 // actually storing other than performing the loop and collecting the 10937 // info. 10938 SmallVector<std::pair<SDValue, SDValue>> Parts; 10939 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 10940 SDValue PartValue = OutVals[i + 1]; 10941 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 10942 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10943 EVT PartVT = PartValue.getValueType(); 10944 if (PartVT.isScalableVector()) 10945 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10946 StoredSize += PartVT.getStoreSize(); 10947 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 10948 Parts.push_back(std::make_pair(PartValue, Offset)); 10949 ++i; 10950 } 10951 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 10952 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 10953 MemOpChains.push_back( 10954 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 10955 MachinePointerInfo::getFixedStack(MF, FI))); 10956 for (const auto &Part : Parts) { 10957 SDValue PartValue = Part.first; 10958 SDValue PartOffset = Part.second; 10959 SDValue Address = 10960 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 10961 MemOpChains.push_back( 10962 DAG.getStore(Chain, DL, PartValue, Address, 10963 MachinePointerInfo::getFixedStack(MF, FI))); 10964 } 10965 ArgValue = SpillSlot; 10966 } else { 10967 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 10968 } 10969 10970 // Use local copy if it is a byval arg. 10971 if (Flags.isByVal()) 10972 ArgValue = ByValArgs[j++]; 10973 10974 if (VA.isRegLoc()) { 10975 // Queue up the argument copies and emit them at the end. 10976 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 10977 } else { 10978 assert(VA.isMemLoc() && "Argument not register or memory"); 10979 assert(!IsTailCall && "Tail call not allowed if stack is used " 10980 "for passing parameters"); 10981 10982 // Work out the address of the stack slot. 10983 if (!StackPtr.getNode()) 10984 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10985 SDValue Address = 10986 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 10987 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 10988 10989 // Emit the store. 10990 MemOpChains.push_back( 10991 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 10992 } 10993 } 10994 10995 // Join the stores, which are independent of one another. 10996 if (!MemOpChains.empty()) 10997 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 10998 10999 SDValue Glue; 11000 11001 // Build a sequence of copy-to-reg nodes, chained and glued together. 11002 for (auto &Reg : RegsToPass) { 11003 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 11004 Glue = Chain.getValue(1); 11005 } 11006 11007 // Validate that none of the argument registers have been marked as 11008 // reserved, if so report an error. Do the same for the return address if this 11009 // is not a tailcall. 11010 validateCCReservedRegs(RegsToPass, MF); 11011 if (!IsTailCall && 11012 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 11013 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11014 MF.getFunction(), 11015 "Return address register required, but has been reserved."}); 11016 11017 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 11018 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 11019 // split it and then direct call can be matched by PseudoCALL. 11020 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 11021 const GlobalValue *GV = S->getGlobal(); 11022 11023 unsigned OpFlags = RISCVII::MO_CALL; 11024 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 11025 OpFlags = RISCVII::MO_PLT; 11026 11027 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 11028 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 11029 unsigned OpFlags = RISCVII::MO_CALL; 11030 11031 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 11032 nullptr)) 11033 OpFlags = RISCVII::MO_PLT; 11034 11035 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 11036 } 11037 11038 // The first call operand is the chain and the second is the target address. 11039 SmallVector<SDValue, 8> Ops; 11040 Ops.push_back(Chain); 11041 Ops.push_back(Callee); 11042 11043 // Add argument registers to the end of the list so that they are 11044 // known live into the call. 11045 for (auto &Reg : RegsToPass) 11046 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 11047 11048 if (!IsTailCall) { 11049 // Add a register mask operand representing the call-preserved registers. 11050 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11051 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 11052 assert(Mask && "Missing call preserved mask for calling convention"); 11053 Ops.push_back(DAG.getRegisterMask(Mask)); 11054 } 11055 11056 // Glue the call to the argument copies, if any. 11057 if (Glue.getNode()) 11058 Ops.push_back(Glue); 11059 11060 // Emit the call. 11061 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 11062 11063 if (IsTailCall) { 11064 MF.getFrameInfo().setHasTailCall(); 11065 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 11066 } 11067 11068 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 11069 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 11070 Glue = Chain.getValue(1); 11071 11072 // Mark the end of the call, which is glued to the call itself. 11073 Chain = DAG.getCALLSEQ_END(Chain, 11074 DAG.getConstant(NumBytes, DL, PtrVT, true), 11075 DAG.getConstant(0, DL, PtrVT, true), 11076 Glue, DL); 11077 Glue = Chain.getValue(1); 11078 11079 // Assign locations to each value returned by this call. 11080 SmallVector<CCValAssign, 16> RVLocs; 11081 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 11082 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 11083 11084 // Copy all of the result registers out of their specified physreg. 11085 for (auto &VA : RVLocs) { 11086 // Copy the value out 11087 SDValue RetValue = 11088 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 11089 // Glue the RetValue to the end of the call sequence 11090 Chain = RetValue.getValue(1); 11091 Glue = RetValue.getValue(2); 11092 11093 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 11094 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 11095 SDValue RetValue2 = 11096 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 11097 Chain = RetValue2.getValue(1); 11098 Glue = RetValue2.getValue(2); 11099 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 11100 RetValue2); 11101 } 11102 11103 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 11104 11105 InVals.push_back(RetValue); 11106 } 11107 11108 return Chain; 11109 } 11110 11111 bool RISCVTargetLowering::CanLowerReturn( 11112 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 11113 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 11114 SmallVector<CCValAssign, 16> RVLocs; 11115 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 11116 11117 Optional<unsigned> FirstMaskArgument; 11118 if (Subtarget.hasVInstructions()) 11119 FirstMaskArgument = preAssignMask(Outs); 11120 11121 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 11122 MVT VT = Outs[i].VT; 11123 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 11124 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 11125 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 11126 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 11127 *this, FirstMaskArgument)) 11128 return false; 11129 } 11130 return true; 11131 } 11132 11133 SDValue 11134 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 11135 bool IsVarArg, 11136 const SmallVectorImpl<ISD::OutputArg> &Outs, 11137 const SmallVectorImpl<SDValue> &OutVals, 11138 const SDLoc &DL, SelectionDAG &DAG) const { 11139 const MachineFunction &MF = DAG.getMachineFunction(); 11140 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 11141 11142 // Stores the assignment of the return value to a location. 11143 SmallVector<CCValAssign, 16> RVLocs; 11144 11145 // Info about the registers and stack slot. 11146 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 11147 *DAG.getContext()); 11148 11149 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 11150 nullptr, CC_RISCV); 11151 11152 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 11153 report_fatal_error("GHC functions return void only"); 11154 11155 SDValue Glue; 11156 SmallVector<SDValue, 4> RetOps(1, Chain); 11157 11158 // Copy the result values into the output registers. 11159 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 11160 SDValue Val = OutVals[i]; 11161 CCValAssign &VA = RVLocs[i]; 11162 assert(VA.isRegLoc() && "Can only return in registers!"); 11163 11164 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 11165 // Handle returning f64 on RV32D with a soft float ABI. 11166 assert(VA.isRegLoc() && "Expected return via registers"); 11167 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 11168 DAG.getVTList(MVT::i32, MVT::i32), Val); 11169 SDValue Lo = SplitF64.getValue(0); 11170 SDValue Hi = SplitF64.getValue(1); 11171 Register RegLo = VA.getLocReg(); 11172 assert(RegLo < RISCV::X31 && "Invalid register pair"); 11173 Register RegHi = RegLo + 1; 11174 11175 if (STI.isRegisterReservedByUser(RegLo) || 11176 STI.isRegisterReservedByUser(RegHi)) 11177 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11178 MF.getFunction(), 11179 "Return value register required, but has been reserved."}); 11180 11181 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 11182 Glue = Chain.getValue(1); 11183 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 11184 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 11185 Glue = Chain.getValue(1); 11186 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 11187 } else { 11188 // Handle a 'normal' return. 11189 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 11190 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 11191 11192 if (STI.isRegisterReservedByUser(VA.getLocReg())) 11193 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11194 MF.getFunction(), 11195 "Return value register required, but has been reserved."}); 11196 11197 // Guarantee that all emitted copies are stuck together. 11198 Glue = Chain.getValue(1); 11199 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 11200 } 11201 } 11202 11203 RetOps[0] = Chain; // Update chain. 11204 11205 // Add the glue node if we have it. 11206 if (Glue.getNode()) { 11207 RetOps.push_back(Glue); 11208 } 11209 11210 unsigned RetOpc = RISCVISD::RET_FLAG; 11211 // Interrupt service routines use different return instructions. 11212 const Function &Func = DAG.getMachineFunction().getFunction(); 11213 if (Func.hasFnAttribute("interrupt")) { 11214 if (!Func.getReturnType()->isVoidTy()) 11215 report_fatal_error( 11216 "Functions with the interrupt attribute must have void return type!"); 11217 11218 MachineFunction &MF = DAG.getMachineFunction(); 11219 StringRef Kind = 11220 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 11221 11222 if (Kind == "user") 11223 RetOpc = RISCVISD::URET_FLAG; 11224 else if (Kind == "supervisor") 11225 RetOpc = RISCVISD::SRET_FLAG; 11226 else 11227 RetOpc = RISCVISD::MRET_FLAG; 11228 } 11229 11230 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 11231 } 11232 11233 void RISCVTargetLowering::validateCCReservedRegs( 11234 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 11235 MachineFunction &MF) const { 11236 const Function &F = MF.getFunction(); 11237 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 11238 11239 if (llvm::any_of(Regs, [&STI](auto Reg) { 11240 return STI.isRegisterReservedByUser(Reg.first); 11241 })) 11242 F.getContext().diagnose(DiagnosticInfoUnsupported{ 11243 F, "Argument register required, but has been reserved."}); 11244 } 11245 11246 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 11247 return CI->isTailCall(); 11248 } 11249 11250 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 11251 #define NODE_NAME_CASE(NODE) \ 11252 case RISCVISD::NODE: \ 11253 return "RISCVISD::" #NODE; 11254 // clang-format off 11255 switch ((RISCVISD::NodeType)Opcode) { 11256 case RISCVISD::FIRST_NUMBER: 11257 break; 11258 NODE_NAME_CASE(RET_FLAG) 11259 NODE_NAME_CASE(URET_FLAG) 11260 NODE_NAME_CASE(SRET_FLAG) 11261 NODE_NAME_CASE(MRET_FLAG) 11262 NODE_NAME_CASE(CALL) 11263 NODE_NAME_CASE(SELECT_CC) 11264 NODE_NAME_CASE(BR_CC) 11265 NODE_NAME_CASE(BuildPairF64) 11266 NODE_NAME_CASE(SplitF64) 11267 NODE_NAME_CASE(TAIL) 11268 NODE_NAME_CASE(ADD_LO) 11269 NODE_NAME_CASE(HI) 11270 NODE_NAME_CASE(LLA) 11271 NODE_NAME_CASE(ADD_TPREL) 11272 NODE_NAME_CASE(LA) 11273 NODE_NAME_CASE(LA_TLS_IE) 11274 NODE_NAME_CASE(LA_TLS_GD) 11275 NODE_NAME_CASE(MULHSU) 11276 NODE_NAME_CASE(SLLW) 11277 NODE_NAME_CASE(SRAW) 11278 NODE_NAME_CASE(SRLW) 11279 NODE_NAME_CASE(DIVW) 11280 NODE_NAME_CASE(DIVUW) 11281 NODE_NAME_CASE(REMUW) 11282 NODE_NAME_CASE(ROLW) 11283 NODE_NAME_CASE(RORW) 11284 NODE_NAME_CASE(CLZW) 11285 NODE_NAME_CASE(CTZW) 11286 NODE_NAME_CASE(FSLW) 11287 NODE_NAME_CASE(FSRW) 11288 NODE_NAME_CASE(FSL) 11289 NODE_NAME_CASE(FSR) 11290 NODE_NAME_CASE(FMV_H_X) 11291 NODE_NAME_CASE(FMV_X_ANYEXTH) 11292 NODE_NAME_CASE(FMV_X_SIGNEXTH) 11293 NODE_NAME_CASE(FMV_W_X_RV64) 11294 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 11295 NODE_NAME_CASE(FCVT_X) 11296 NODE_NAME_CASE(FCVT_XU) 11297 NODE_NAME_CASE(FCVT_W_RV64) 11298 NODE_NAME_CASE(FCVT_WU_RV64) 11299 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 11300 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 11301 NODE_NAME_CASE(READ_CYCLE_WIDE) 11302 NODE_NAME_CASE(GREV) 11303 NODE_NAME_CASE(GREVW) 11304 NODE_NAME_CASE(GORC) 11305 NODE_NAME_CASE(GORCW) 11306 NODE_NAME_CASE(SHFL) 11307 NODE_NAME_CASE(SHFLW) 11308 NODE_NAME_CASE(UNSHFL) 11309 NODE_NAME_CASE(UNSHFLW) 11310 NODE_NAME_CASE(BFP) 11311 NODE_NAME_CASE(BFPW) 11312 NODE_NAME_CASE(BCOMPRESS) 11313 NODE_NAME_CASE(BCOMPRESSW) 11314 NODE_NAME_CASE(BDECOMPRESS) 11315 NODE_NAME_CASE(BDECOMPRESSW) 11316 NODE_NAME_CASE(VMV_V_X_VL) 11317 NODE_NAME_CASE(VFMV_V_F_VL) 11318 NODE_NAME_CASE(VMV_X_S) 11319 NODE_NAME_CASE(VMV_S_X_VL) 11320 NODE_NAME_CASE(VFMV_S_F_VL) 11321 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 11322 NODE_NAME_CASE(READ_VLENB) 11323 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 11324 NODE_NAME_CASE(VSLIDEUP_VL) 11325 NODE_NAME_CASE(VSLIDE1UP_VL) 11326 NODE_NAME_CASE(VSLIDEDOWN_VL) 11327 NODE_NAME_CASE(VSLIDE1DOWN_VL) 11328 NODE_NAME_CASE(VID_VL) 11329 NODE_NAME_CASE(VFNCVT_ROD_VL) 11330 NODE_NAME_CASE(VECREDUCE_ADD_VL) 11331 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 11332 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 11333 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 11334 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 11335 NODE_NAME_CASE(VECREDUCE_AND_VL) 11336 NODE_NAME_CASE(VECREDUCE_OR_VL) 11337 NODE_NAME_CASE(VECREDUCE_XOR_VL) 11338 NODE_NAME_CASE(VECREDUCE_FADD_VL) 11339 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 11340 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 11341 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 11342 NODE_NAME_CASE(ADD_VL) 11343 NODE_NAME_CASE(AND_VL) 11344 NODE_NAME_CASE(MUL_VL) 11345 NODE_NAME_CASE(OR_VL) 11346 NODE_NAME_CASE(SDIV_VL) 11347 NODE_NAME_CASE(SHL_VL) 11348 NODE_NAME_CASE(SREM_VL) 11349 NODE_NAME_CASE(SRA_VL) 11350 NODE_NAME_CASE(SRL_VL) 11351 NODE_NAME_CASE(SUB_VL) 11352 NODE_NAME_CASE(UDIV_VL) 11353 NODE_NAME_CASE(UREM_VL) 11354 NODE_NAME_CASE(XOR_VL) 11355 NODE_NAME_CASE(SADDSAT_VL) 11356 NODE_NAME_CASE(UADDSAT_VL) 11357 NODE_NAME_CASE(SSUBSAT_VL) 11358 NODE_NAME_CASE(USUBSAT_VL) 11359 NODE_NAME_CASE(FADD_VL) 11360 NODE_NAME_CASE(FSUB_VL) 11361 NODE_NAME_CASE(FMUL_VL) 11362 NODE_NAME_CASE(FDIV_VL) 11363 NODE_NAME_CASE(FNEG_VL) 11364 NODE_NAME_CASE(FABS_VL) 11365 NODE_NAME_CASE(FSQRT_VL) 11366 NODE_NAME_CASE(VFMADD_VL) 11367 NODE_NAME_CASE(VFNMADD_VL) 11368 NODE_NAME_CASE(VFMSUB_VL) 11369 NODE_NAME_CASE(VFNMSUB_VL) 11370 NODE_NAME_CASE(FCOPYSIGN_VL) 11371 NODE_NAME_CASE(SMIN_VL) 11372 NODE_NAME_CASE(SMAX_VL) 11373 NODE_NAME_CASE(UMIN_VL) 11374 NODE_NAME_CASE(UMAX_VL) 11375 NODE_NAME_CASE(FMINNUM_VL) 11376 NODE_NAME_CASE(FMAXNUM_VL) 11377 NODE_NAME_CASE(MULHS_VL) 11378 NODE_NAME_CASE(MULHU_VL) 11379 NODE_NAME_CASE(FP_TO_SINT_VL) 11380 NODE_NAME_CASE(FP_TO_UINT_VL) 11381 NODE_NAME_CASE(SINT_TO_FP_VL) 11382 NODE_NAME_CASE(UINT_TO_FP_VL) 11383 NODE_NAME_CASE(FP_EXTEND_VL) 11384 NODE_NAME_CASE(FP_ROUND_VL) 11385 NODE_NAME_CASE(VWMUL_VL) 11386 NODE_NAME_CASE(VWMULU_VL) 11387 NODE_NAME_CASE(VWMULSU_VL) 11388 NODE_NAME_CASE(VWADD_VL) 11389 NODE_NAME_CASE(VWADDU_VL) 11390 NODE_NAME_CASE(VWSUB_VL) 11391 NODE_NAME_CASE(VWSUBU_VL) 11392 NODE_NAME_CASE(VWADD_W_VL) 11393 NODE_NAME_CASE(VWADDU_W_VL) 11394 NODE_NAME_CASE(VWSUB_W_VL) 11395 NODE_NAME_CASE(VWSUBU_W_VL) 11396 NODE_NAME_CASE(SETCC_VL) 11397 NODE_NAME_CASE(VSELECT_VL) 11398 NODE_NAME_CASE(VP_MERGE_VL) 11399 NODE_NAME_CASE(VMAND_VL) 11400 NODE_NAME_CASE(VMOR_VL) 11401 NODE_NAME_CASE(VMXOR_VL) 11402 NODE_NAME_CASE(VMCLR_VL) 11403 NODE_NAME_CASE(VMSET_VL) 11404 NODE_NAME_CASE(VRGATHER_VX_VL) 11405 NODE_NAME_CASE(VRGATHER_VV_VL) 11406 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 11407 NODE_NAME_CASE(VSEXT_VL) 11408 NODE_NAME_CASE(VZEXT_VL) 11409 NODE_NAME_CASE(VCPOP_VL) 11410 NODE_NAME_CASE(READ_CSR) 11411 NODE_NAME_CASE(WRITE_CSR) 11412 NODE_NAME_CASE(SWAP_CSR) 11413 } 11414 // clang-format on 11415 return nullptr; 11416 #undef NODE_NAME_CASE 11417 } 11418 11419 /// getConstraintType - Given a constraint letter, return the type of 11420 /// constraint it is for this target. 11421 RISCVTargetLowering::ConstraintType 11422 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 11423 if (Constraint.size() == 1) { 11424 switch (Constraint[0]) { 11425 default: 11426 break; 11427 case 'f': 11428 return C_RegisterClass; 11429 case 'I': 11430 case 'J': 11431 case 'K': 11432 return C_Immediate; 11433 case 'A': 11434 return C_Memory; 11435 case 'S': // A symbolic address 11436 return C_Other; 11437 } 11438 } else { 11439 if (Constraint == "vr" || Constraint == "vm") 11440 return C_RegisterClass; 11441 } 11442 return TargetLowering::getConstraintType(Constraint); 11443 } 11444 11445 std::pair<unsigned, const TargetRegisterClass *> 11446 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11447 StringRef Constraint, 11448 MVT VT) const { 11449 // First, see if this is a constraint that directly corresponds to a 11450 // RISCV register class. 11451 if (Constraint.size() == 1) { 11452 switch (Constraint[0]) { 11453 case 'r': 11454 // TODO: Support fixed vectors up to XLen for P extension? 11455 if (VT.isVector()) 11456 break; 11457 return std::make_pair(0U, &RISCV::GPRRegClass); 11458 case 'f': 11459 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 11460 return std::make_pair(0U, &RISCV::FPR16RegClass); 11461 if (Subtarget.hasStdExtF() && VT == MVT::f32) 11462 return std::make_pair(0U, &RISCV::FPR32RegClass); 11463 if (Subtarget.hasStdExtD() && VT == MVT::f64) 11464 return std::make_pair(0U, &RISCV::FPR64RegClass); 11465 break; 11466 default: 11467 break; 11468 } 11469 } else if (Constraint == "vr") { 11470 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 11471 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11472 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 11473 return std::make_pair(0U, RC); 11474 } 11475 } else if (Constraint == "vm") { 11476 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 11477 return std::make_pair(0U, &RISCV::VMV0RegClass); 11478 } 11479 11480 // Clang will correctly decode the usage of register name aliases into their 11481 // official names. However, other frontends like `rustc` do not. This allows 11482 // users of these frontends to use the ABI names for registers in LLVM-style 11483 // register constraints. 11484 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 11485 .Case("{zero}", RISCV::X0) 11486 .Case("{ra}", RISCV::X1) 11487 .Case("{sp}", RISCV::X2) 11488 .Case("{gp}", RISCV::X3) 11489 .Case("{tp}", RISCV::X4) 11490 .Case("{t0}", RISCV::X5) 11491 .Case("{t1}", RISCV::X6) 11492 .Case("{t2}", RISCV::X7) 11493 .Cases("{s0}", "{fp}", RISCV::X8) 11494 .Case("{s1}", RISCV::X9) 11495 .Case("{a0}", RISCV::X10) 11496 .Case("{a1}", RISCV::X11) 11497 .Case("{a2}", RISCV::X12) 11498 .Case("{a3}", RISCV::X13) 11499 .Case("{a4}", RISCV::X14) 11500 .Case("{a5}", RISCV::X15) 11501 .Case("{a6}", RISCV::X16) 11502 .Case("{a7}", RISCV::X17) 11503 .Case("{s2}", RISCV::X18) 11504 .Case("{s3}", RISCV::X19) 11505 .Case("{s4}", RISCV::X20) 11506 .Case("{s5}", RISCV::X21) 11507 .Case("{s6}", RISCV::X22) 11508 .Case("{s7}", RISCV::X23) 11509 .Case("{s8}", RISCV::X24) 11510 .Case("{s9}", RISCV::X25) 11511 .Case("{s10}", RISCV::X26) 11512 .Case("{s11}", RISCV::X27) 11513 .Case("{t3}", RISCV::X28) 11514 .Case("{t4}", RISCV::X29) 11515 .Case("{t5}", RISCV::X30) 11516 .Case("{t6}", RISCV::X31) 11517 .Default(RISCV::NoRegister); 11518 if (XRegFromAlias != RISCV::NoRegister) 11519 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 11520 11521 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 11522 // TableGen record rather than the AsmName to choose registers for InlineAsm 11523 // constraints, plus we want to match those names to the widest floating point 11524 // register type available, manually select floating point registers here. 11525 // 11526 // The second case is the ABI name of the register, so that frontends can also 11527 // use the ABI names in register constraint lists. 11528 if (Subtarget.hasStdExtF()) { 11529 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 11530 .Cases("{f0}", "{ft0}", RISCV::F0_F) 11531 .Cases("{f1}", "{ft1}", RISCV::F1_F) 11532 .Cases("{f2}", "{ft2}", RISCV::F2_F) 11533 .Cases("{f3}", "{ft3}", RISCV::F3_F) 11534 .Cases("{f4}", "{ft4}", RISCV::F4_F) 11535 .Cases("{f5}", "{ft5}", RISCV::F5_F) 11536 .Cases("{f6}", "{ft6}", RISCV::F6_F) 11537 .Cases("{f7}", "{ft7}", RISCV::F7_F) 11538 .Cases("{f8}", "{fs0}", RISCV::F8_F) 11539 .Cases("{f9}", "{fs1}", RISCV::F9_F) 11540 .Cases("{f10}", "{fa0}", RISCV::F10_F) 11541 .Cases("{f11}", "{fa1}", RISCV::F11_F) 11542 .Cases("{f12}", "{fa2}", RISCV::F12_F) 11543 .Cases("{f13}", "{fa3}", RISCV::F13_F) 11544 .Cases("{f14}", "{fa4}", RISCV::F14_F) 11545 .Cases("{f15}", "{fa5}", RISCV::F15_F) 11546 .Cases("{f16}", "{fa6}", RISCV::F16_F) 11547 .Cases("{f17}", "{fa7}", RISCV::F17_F) 11548 .Cases("{f18}", "{fs2}", RISCV::F18_F) 11549 .Cases("{f19}", "{fs3}", RISCV::F19_F) 11550 .Cases("{f20}", "{fs4}", RISCV::F20_F) 11551 .Cases("{f21}", "{fs5}", RISCV::F21_F) 11552 .Cases("{f22}", "{fs6}", RISCV::F22_F) 11553 .Cases("{f23}", "{fs7}", RISCV::F23_F) 11554 .Cases("{f24}", "{fs8}", RISCV::F24_F) 11555 .Cases("{f25}", "{fs9}", RISCV::F25_F) 11556 .Cases("{f26}", "{fs10}", RISCV::F26_F) 11557 .Cases("{f27}", "{fs11}", RISCV::F27_F) 11558 .Cases("{f28}", "{ft8}", RISCV::F28_F) 11559 .Cases("{f29}", "{ft9}", RISCV::F29_F) 11560 .Cases("{f30}", "{ft10}", RISCV::F30_F) 11561 .Cases("{f31}", "{ft11}", RISCV::F31_F) 11562 .Default(RISCV::NoRegister); 11563 if (FReg != RISCV::NoRegister) { 11564 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 11565 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 11566 unsigned RegNo = FReg - RISCV::F0_F; 11567 unsigned DReg = RISCV::F0_D + RegNo; 11568 return std::make_pair(DReg, &RISCV::FPR64RegClass); 11569 } 11570 if (VT == MVT::f32 || VT == MVT::Other) 11571 return std::make_pair(FReg, &RISCV::FPR32RegClass); 11572 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 11573 unsigned RegNo = FReg - RISCV::F0_F; 11574 unsigned HReg = RISCV::F0_H + RegNo; 11575 return std::make_pair(HReg, &RISCV::FPR16RegClass); 11576 } 11577 } 11578 } 11579 11580 if (Subtarget.hasVInstructions()) { 11581 Register VReg = StringSwitch<Register>(Constraint.lower()) 11582 .Case("{v0}", RISCV::V0) 11583 .Case("{v1}", RISCV::V1) 11584 .Case("{v2}", RISCV::V2) 11585 .Case("{v3}", RISCV::V3) 11586 .Case("{v4}", RISCV::V4) 11587 .Case("{v5}", RISCV::V5) 11588 .Case("{v6}", RISCV::V6) 11589 .Case("{v7}", RISCV::V7) 11590 .Case("{v8}", RISCV::V8) 11591 .Case("{v9}", RISCV::V9) 11592 .Case("{v10}", RISCV::V10) 11593 .Case("{v11}", RISCV::V11) 11594 .Case("{v12}", RISCV::V12) 11595 .Case("{v13}", RISCV::V13) 11596 .Case("{v14}", RISCV::V14) 11597 .Case("{v15}", RISCV::V15) 11598 .Case("{v16}", RISCV::V16) 11599 .Case("{v17}", RISCV::V17) 11600 .Case("{v18}", RISCV::V18) 11601 .Case("{v19}", RISCV::V19) 11602 .Case("{v20}", RISCV::V20) 11603 .Case("{v21}", RISCV::V21) 11604 .Case("{v22}", RISCV::V22) 11605 .Case("{v23}", RISCV::V23) 11606 .Case("{v24}", RISCV::V24) 11607 .Case("{v25}", RISCV::V25) 11608 .Case("{v26}", RISCV::V26) 11609 .Case("{v27}", RISCV::V27) 11610 .Case("{v28}", RISCV::V28) 11611 .Case("{v29}", RISCV::V29) 11612 .Case("{v30}", RISCV::V30) 11613 .Case("{v31}", RISCV::V31) 11614 .Default(RISCV::NoRegister); 11615 if (VReg != RISCV::NoRegister) { 11616 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11617 return std::make_pair(VReg, &RISCV::VMRegClass); 11618 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11619 return std::make_pair(VReg, &RISCV::VRRegClass); 11620 for (const auto *RC : 11621 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11622 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11623 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11624 return std::make_pair(VReg, RC); 11625 } 11626 } 11627 } 11628 } 11629 11630 std::pair<Register, const TargetRegisterClass *> Res = 11631 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11632 11633 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11634 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11635 // Subtarget into account. 11636 if (Res.second == &RISCV::GPRF16RegClass || 11637 Res.second == &RISCV::GPRF32RegClass || 11638 Res.second == &RISCV::GPRF64RegClass) 11639 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11640 11641 return Res; 11642 } 11643 11644 unsigned 11645 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11646 // Currently only support length 1 constraints. 11647 if (ConstraintCode.size() == 1) { 11648 switch (ConstraintCode[0]) { 11649 case 'A': 11650 return InlineAsm::Constraint_A; 11651 default: 11652 break; 11653 } 11654 } 11655 11656 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11657 } 11658 11659 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11660 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11661 SelectionDAG &DAG) const { 11662 // Currently only support length 1 constraints. 11663 if (Constraint.length() == 1) { 11664 switch (Constraint[0]) { 11665 case 'I': 11666 // Validate & create a 12-bit signed immediate operand. 11667 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11668 uint64_t CVal = C->getSExtValue(); 11669 if (isInt<12>(CVal)) 11670 Ops.push_back( 11671 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11672 } 11673 return; 11674 case 'J': 11675 // Validate & create an integer zero operand. 11676 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11677 if (C->getZExtValue() == 0) 11678 Ops.push_back( 11679 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11680 return; 11681 case 'K': 11682 // Validate & create a 5-bit unsigned immediate operand. 11683 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11684 uint64_t CVal = C->getZExtValue(); 11685 if (isUInt<5>(CVal)) 11686 Ops.push_back( 11687 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11688 } 11689 return; 11690 case 'S': 11691 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11692 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11693 GA->getValueType(0))); 11694 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11695 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11696 BA->getValueType(0))); 11697 } 11698 return; 11699 default: 11700 break; 11701 } 11702 } 11703 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11704 } 11705 11706 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11707 Instruction *Inst, 11708 AtomicOrdering Ord) const { 11709 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 11710 return Builder.CreateFence(Ord); 11711 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 11712 return Builder.CreateFence(AtomicOrdering::Release); 11713 return nullptr; 11714 } 11715 11716 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11717 Instruction *Inst, 11718 AtomicOrdering Ord) const { 11719 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11720 return Builder.CreateFence(AtomicOrdering::Acquire); 11721 return nullptr; 11722 } 11723 11724 TargetLowering::AtomicExpansionKind 11725 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11726 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11727 // point operations can't be used in an lr/sc sequence without breaking the 11728 // forward-progress guarantee. 11729 if (AI->isFloatingPointOperation()) 11730 return AtomicExpansionKind::CmpXChg; 11731 11732 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11733 if (Size == 8 || Size == 16) 11734 return AtomicExpansionKind::MaskedIntrinsic; 11735 return AtomicExpansionKind::None; 11736 } 11737 11738 static Intrinsic::ID 11739 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11740 if (XLen == 32) { 11741 switch (BinOp) { 11742 default: 11743 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11744 case AtomicRMWInst::Xchg: 11745 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11746 case AtomicRMWInst::Add: 11747 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11748 case AtomicRMWInst::Sub: 11749 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11750 case AtomicRMWInst::Nand: 11751 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11752 case AtomicRMWInst::Max: 11753 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11754 case AtomicRMWInst::Min: 11755 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11756 case AtomicRMWInst::UMax: 11757 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11758 case AtomicRMWInst::UMin: 11759 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11760 } 11761 } 11762 11763 if (XLen == 64) { 11764 switch (BinOp) { 11765 default: 11766 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11767 case AtomicRMWInst::Xchg: 11768 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11769 case AtomicRMWInst::Add: 11770 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11771 case AtomicRMWInst::Sub: 11772 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11773 case AtomicRMWInst::Nand: 11774 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11775 case AtomicRMWInst::Max: 11776 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11777 case AtomicRMWInst::Min: 11778 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11779 case AtomicRMWInst::UMax: 11780 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11781 case AtomicRMWInst::UMin: 11782 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11783 } 11784 } 11785 11786 llvm_unreachable("Unexpected XLen\n"); 11787 } 11788 11789 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11790 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11791 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11792 unsigned XLen = Subtarget.getXLen(); 11793 Value *Ordering = 11794 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11795 Type *Tys[] = {AlignedAddr->getType()}; 11796 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11797 AI->getModule(), 11798 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11799 11800 if (XLen == 64) { 11801 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11802 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11803 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11804 } 11805 11806 Value *Result; 11807 11808 // Must pass the shift amount needed to sign extend the loaded value prior 11809 // to performing a signed comparison for min/max. ShiftAmt is the number of 11810 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11811 // is the number of bits to left+right shift the value in order to 11812 // sign-extend. 11813 if (AI->getOperation() == AtomicRMWInst::Min || 11814 AI->getOperation() == AtomicRMWInst::Max) { 11815 const DataLayout &DL = AI->getModule()->getDataLayout(); 11816 unsigned ValWidth = 11817 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11818 Value *SextShamt = 11819 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11820 Result = Builder.CreateCall(LrwOpScwLoop, 11821 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11822 } else { 11823 Result = 11824 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11825 } 11826 11827 if (XLen == 64) 11828 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11829 return Result; 11830 } 11831 11832 TargetLowering::AtomicExpansionKind 11833 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11834 AtomicCmpXchgInst *CI) const { 11835 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11836 if (Size == 8 || Size == 16) 11837 return AtomicExpansionKind::MaskedIntrinsic; 11838 return AtomicExpansionKind::None; 11839 } 11840 11841 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11842 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11843 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11844 unsigned XLen = Subtarget.getXLen(); 11845 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11846 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11847 if (XLen == 64) { 11848 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11849 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11850 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11851 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11852 } 11853 Type *Tys[] = {AlignedAddr->getType()}; 11854 Function *MaskedCmpXchg = 11855 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11856 Value *Result = Builder.CreateCall( 11857 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11858 if (XLen == 64) 11859 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11860 return Result; 11861 } 11862 11863 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT, 11864 EVT DataVT) const { 11865 return false; 11866 } 11867 11868 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11869 EVT VT) const { 11870 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11871 return false; 11872 11873 switch (FPVT.getSimpleVT().SimpleTy) { 11874 case MVT::f16: 11875 return Subtarget.hasStdExtZfh(); 11876 case MVT::f32: 11877 return Subtarget.hasStdExtF(); 11878 case MVT::f64: 11879 return Subtarget.hasStdExtD(); 11880 default: 11881 return false; 11882 } 11883 } 11884 11885 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11886 // If we are using the small code model, we can reduce size of jump table 11887 // entry to 4 bytes. 11888 if (Subtarget.is64Bit() && !isPositionIndependent() && 11889 getTargetMachine().getCodeModel() == CodeModel::Small) { 11890 return MachineJumpTableInfo::EK_Custom32; 11891 } 11892 return TargetLowering::getJumpTableEncoding(); 11893 } 11894 11895 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 11896 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 11897 unsigned uid, MCContext &Ctx) const { 11898 assert(Subtarget.is64Bit() && !isPositionIndependent() && 11899 getTargetMachine().getCodeModel() == CodeModel::Small); 11900 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 11901 } 11902 11903 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 11904 EVT VT) const { 11905 VT = VT.getScalarType(); 11906 11907 if (!VT.isSimple()) 11908 return false; 11909 11910 switch (VT.getSimpleVT().SimpleTy) { 11911 case MVT::f16: 11912 return Subtarget.hasStdExtZfh(); 11913 case MVT::f32: 11914 return Subtarget.hasStdExtF(); 11915 case MVT::f64: 11916 return Subtarget.hasStdExtD(); 11917 default: 11918 break; 11919 } 11920 11921 return false; 11922 } 11923 11924 Register RISCVTargetLowering::getExceptionPointerRegister( 11925 const Constant *PersonalityFn) const { 11926 return RISCV::X10; 11927 } 11928 11929 Register RISCVTargetLowering::getExceptionSelectorRegister( 11930 const Constant *PersonalityFn) const { 11931 return RISCV::X11; 11932 } 11933 11934 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 11935 // Return false to suppress the unnecessary extensions if the LibCall 11936 // arguments or return value is f32 type for LP64 ABI. 11937 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 11938 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 11939 return false; 11940 11941 return true; 11942 } 11943 11944 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 11945 if (Subtarget.is64Bit() && Type == MVT::i32) 11946 return true; 11947 11948 return IsSigned; 11949 } 11950 11951 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 11952 SDValue C) const { 11953 // Check integral scalar types. 11954 if (VT.isScalarInteger()) { 11955 // Omit the optimization if the sub target has the M extension and the data 11956 // size exceeds XLen. 11957 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 11958 return false; 11959 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 11960 // Break the MUL to a SLLI and an ADD/SUB. 11961 const APInt &Imm = ConstNode->getAPIntValue(); 11962 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 11963 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 11964 return true; 11965 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 11966 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 11967 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 11968 (Imm - 8).isPowerOf2())) 11969 return true; 11970 // Omit the following optimization if the sub target has the M extension 11971 // and the data size >= XLen. 11972 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 11973 return false; 11974 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 11975 // a pair of LUI/ADDI. 11976 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 11977 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 11978 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 11979 (1 - ImmS).isPowerOf2()) 11980 return true; 11981 } 11982 } 11983 } 11984 11985 return false; 11986 } 11987 11988 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 11989 SDValue ConstNode) const { 11990 // Let the DAGCombiner decide for vectors. 11991 EVT VT = AddNode.getValueType(); 11992 if (VT.isVector()) 11993 return true; 11994 11995 // Let the DAGCombiner decide for larger types. 11996 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 11997 return true; 11998 11999 // It is worse if c1 is simm12 while c1*c2 is not. 12000 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 12001 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 12002 const APInt &C1 = C1Node->getAPIntValue(); 12003 const APInt &C2 = C2Node->getAPIntValue(); 12004 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 12005 return false; 12006 12007 // Default to true and let the DAGCombiner decide. 12008 return true; 12009 } 12010 12011 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 12012 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 12013 bool *Fast) const { 12014 if (!VT.isVector()) { 12015 if (Fast) 12016 *Fast = false; 12017 return Subtarget.enableUnalignedScalarMem(); 12018 } 12019 12020 // All vector implementations must support element alignment 12021 EVT ElemVT = VT.getVectorElementType(); 12022 if (Alignment >= ElemVT.getStoreSize()) { 12023 if (Fast) 12024 *Fast = true; 12025 return true; 12026 } 12027 12028 return false; 12029 } 12030 12031 bool RISCVTargetLowering::splitValueIntoRegisterParts( 12032 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 12033 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 12034 bool IsABIRegCopy = CC.has_value(); 12035 EVT ValueVT = Val.getValueType(); 12036 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 12037 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 12038 // and cast to f32. 12039 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 12040 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 12041 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 12042 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 12043 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 12044 Parts[0] = Val; 12045 return true; 12046 } 12047 12048 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 12049 LLVMContext &Context = *DAG.getContext(); 12050 EVT ValueEltVT = ValueVT.getVectorElementType(); 12051 EVT PartEltVT = PartVT.getVectorElementType(); 12052 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 12053 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 12054 if (PartVTBitSize % ValueVTBitSize == 0) { 12055 assert(PartVTBitSize >= ValueVTBitSize); 12056 // If the element types are different, bitcast to the same element type of 12057 // PartVT first. 12058 // Give an example here, we want copy a <vscale x 1 x i8> value to 12059 // <vscale x 4 x i16>. 12060 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 12061 // subvector, then we can bitcast to <vscale x 4 x i16>. 12062 if (ValueEltVT != PartEltVT) { 12063 if (PartVTBitSize > ValueVTBitSize) { 12064 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 12065 assert(Count != 0 && "The number of element should not be zero."); 12066 EVT SameEltTypeVT = 12067 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 12068 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 12069 DAG.getUNDEF(SameEltTypeVT), Val, 12070 DAG.getVectorIdxConstant(0, DL)); 12071 } 12072 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 12073 } else { 12074 Val = 12075 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 12076 Val, DAG.getVectorIdxConstant(0, DL)); 12077 } 12078 Parts[0] = Val; 12079 return true; 12080 } 12081 } 12082 return false; 12083 } 12084 12085 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 12086 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 12087 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 12088 bool IsABIRegCopy = CC.has_value(); 12089 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 12090 SDValue Val = Parts[0]; 12091 12092 // Cast the f32 to i32, truncate to i16, and cast back to f16. 12093 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 12094 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 12095 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 12096 return Val; 12097 } 12098 12099 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 12100 LLVMContext &Context = *DAG.getContext(); 12101 SDValue Val = Parts[0]; 12102 EVT ValueEltVT = ValueVT.getVectorElementType(); 12103 EVT PartEltVT = PartVT.getVectorElementType(); 12104 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 12105 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 12106 if (PartVTBitSize % ValueVTBitSize == 0) { 12107 assert(PartVTBitSize >= ValueVTBitSize); 12108 EVT SameEltTypeVT = ValueVT; 12109 // If the element types are different, convert it to the same element type 12110 // of PartVT. 12111 // Give an example here, we want copy a <vscale x 1 x i8> value from 12112 // <vscale x 4 x i16>. 12113 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 12114 // then we can extract <vscale x 1 x i8>. 12115 if (ValueEltVT != PartEltVT) { 12116 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 12117 assert(Count != 0 && "The number of element should not be zero."); 12118 SameEltTypeVT = 12119 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 12120 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 12121 } 12122 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 12123 DAG.getVectorIdxConstant(0, DL)); 12124 return Val; 12125 } 12126 } 12127 return SDValue(); 12128 } 12129 12130 SDValue 12131 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 12132 SelectionDAG &DAG, 12133 SmallVectorImpl<SDNode *> &Created) const { 12134 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 12135 if (isIntDivCheap(N->getValueType(0), Attr)) 12136 return SDValue(N, 0); // Lower SDIV as SDIV 12137 12138 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 12139 "Unexpected divisor!"); 12140 12141 // Conditional move is needed, so do the transformation iff Zbt is enabled. 12142 if (!Subtarget.hasStdExtZbt()) 12143 return SDValue(); 12144 12145 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 12146 // Besides, more critical path instructions will be generated when dividing 12147 // by 2. So we keep using the original DAGs for these cases. 12148 unsigned Lg2 = Divisor.countTrailingZeros(); 12149 if (Lg2 == 1 || Lg2 >= 12) 12150 return SDValue(); 12151 12152 // fold (sdiv X, pow2) 12153 EVT VT = N->getValueType(0); 12154 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 12155 return SDValue(); 12156 12157 SDLoc DL(N); 12158 SDValue N0 = N->getOperand(0); 12159 SDValue Zero = DAG.getConstant(0, DL, VT); 12160 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 12161 12162 // Add (N0 < 0) ? Pow2 - 1 : 0; 12163 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 12164 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 12165 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 12166 12167 Created.push_back(Cmp.getNode()); 12168 Created.push_back(Add.getNode()); 12169 Created.push_back(Sel.getNode()); 12170 12171 // Divide by pow2. 12172 SDValue SRA = 12173 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 12174 12175 // If we're dividing by a positive value, we're done. Otherwise, we must 12176 // negate the result. 12177 if (Divisor.isNonNegative()) 12178 return SRA; 12179 12180 Created.push_back(SRA.getNode()); 12181 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 12182 } 12183 12184 #define GET_REGISTER_MATCHER 12185 #include "RISCVGenAsmMatcher.inc" 12186 12187 Register 12188 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 12189 const MachineFunction &MF) const { 12190 Register Reg = MatchRegisterAltName(RegName); 12191 if (Reg == RISCV::NoRegister) 12192 Reg = MatchRegisterName(RegName); 12193 if (Reg == RISCV::NoRegister) 12194 report_fatal_error( 12195 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 12196 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 12197 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 12198 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 12199 StringRef(RegName) + "\".")); 12200 return Reg; 12201 } 12202 12203 namespace llvm { 12204 namespace RISCVVIntrinsicsTable { 12205 12206 #define GET_RISCVVIntrinsicsTable_IMPL 12207 #include "RISCVGenSearchableTables.inc" 12208 12209 } // namespace RISCVVIntrinsicsTable 12210 12211 } // namespace llvm 12212