1 //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation --------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the interfaces that RISCV uses to lower LLVM code into a 10 // selection DAG. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "RISCVISelLowering.h" 15 #include "MCTargetDesc/RISCVMatInt.h" 16 #include "RISCV.h" 17 #include "RISCVMachineFunctionInfo.h" 18 #include "RISCVRegisterInfo.h" 19 #include "RISCVSubtarget.h" 20 #include "RISCVTargetMachine.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/MemoryLocation.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineFunction.h" 26 #include "llvm/CodeGen/MachineInstrBuilder.h" 27 #include "llvm/CodeGen/MachineJumpTableInfo.h" 28 #include "llvm/CodeGen/MachineRegisterInfo.h" 29 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 30 #include "llvm/CodeGen/ValueTypes.h" 31 #include "llvm/IR/DiagnosticInfo.h" 32 #include "llvm/IR/DiagnosticPrinter.h" 33 #include "llvm/IR/IRBuilder.h" 34 #include "llvm/IR/IntrinsicsRISCV.h" 35 #include "llvm/IR/PatternMatch.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/Support/ErrorHandling.h" 38 #include "llvm/Support/KnownBits.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/raw_ostream.h" 41 42 using namespace llvm; 43 44 #define DEBUG_TYPE "riscv-lower" 45 46 STATISTIC(NumTailCalls, "Number of tail calls"); 47 48 RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM, 49 const RISCVSubtarget &STI) 50 : TargetLowering(TM), Subtarget(STI) { 51 52 if (Subtarget.isRV32E()) 53 report_fatal_error("Codegen not yet implemented for RV32E"); 54 55 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 56 assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI"); 57 58 if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) && 59 !Subtarget.hasStdExtF()) { 60 errs() << "Hard-float 'f' ABI can't be used for a target that " 61 "doesn't support the F instruction set extension (ignoring " 62 "target-abi)\n"; 63 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 64 } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) && 65 !Subtarget.hasStdExtD()) { 66 errs() << "Hard-float 'd' ABI can't be used for a target that " 67 "doesn't support the D instruction set extension (ignoring " 68 "target-abi)\n"; 69 ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32; 70 } 71 72 switch (ABI) { 73 default: 74 report_fatal_error("Don't know how to lower this ABI"); 75 case RISCVABI::ABI_ILP32: 76 case RISCVABI::ABI_ILP32F: 77 case RISCVABI::ABI_ILP32D: 78 case RISCVABI::ABI_LP64: 79 case RISCVABI::ABI_LP64F: 80 case RISCVABI::ABI_LP64D: 81 break; 82 } 83 84 MVT XLenVT = Subtarget.getXLenVT(); 85 86 // Set up the register classes. 87 addRegisterClass(XLenVT, &RISCV::GPRRegClass); 88 89 if (Subtarget.hasStdExtZfh()) 90 addRegisterClass(MVT::f16, &RISCV::FPR16RegClass); 91 if (Subtarget.hasStdExtF()) 92 addRegisterClass(MVT::f32, &RISCV::FPR32RegClass); 93 if (Subtarget.hasStdExtD()) 94 addRegisterClass(MVT::f64, &RISCV::FPR64RegClass); 95 96 static const MVT::SimpleValueType BoolVecVTs[] = { 97 MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1, 98 MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1}; 99 static const MVT::SimpleValueType IntVecVTs[] = { 100 MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8, 101 MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16, 102 MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32, 103 MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64, 104 MVT::nxv4i64, MVT::nxv8i64}; 105 static const MVT::SimpleValueType F16VecVTs[] = { 106 MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16, 107 MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16}; 108 static const MVT::SimpleValueType F32VecVTs[] = { 109 MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32}; 110 static const MVT::SimpleValueType F64VecVTs[] = { 111 MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64}; 112 113 if (Subtarget.hasVInstructions()) { 114 auto addRegClassForRVV = [this](MVT VT) { 115 // Disable the smallest fractional LMUL types if ELEN is less than 116 // RVVBitsPerBlock. 117 unsigned MinElts = RISCV::RVVBitsPerBlock / Subtarget.getELEN(); 118 if (VT.getVectorMinNumElements() < MinElts) 119 return; 120 121 unsigned Size = VT.getSizeInBits().getKnownMinValue(); 122 const TargetRegisterClass *RC; 123 if (Size <= RISCV::RVVBitsPerBlock) 124 RC = &RISCV::VRRegClass; 125 else if (Size == 2 * RISCV::RVVBitsPerBlock) 126 RC = &RISCV::VRM2RegClass; 127 else if (Size == 4 * RISCV::RVVBitsPerBlock) 128 RC = &RISCV::VRM4RegClass; 129 else if (Size == 8 * RISCV::RVVBitsPerBlock) 130 RC = &RISCV::VRM8RegClass; 131 else 132 llvm_unreachable("Unexpected size"); 133 134 addRegisterClass(VT, RC); 135 }; 136 137 for (MVT VT : BoolVecVTs) 138 addRegClassForRVV(VT); 139 for (MVT VT : IntVecVTs) { 140 if (VT.getVectorElementType() == MVT::i64 && 141 !Subtarget.hasVInstructionsI64()) 142 continue; 143 addRegClassForRVV(VT); 144 } 145 146 if (Subtarget.hasVInstructionsF16()) 147 for (MVT VT : F16VecVTs) 148 addRegClassForRVV(VT); 149 150 if (Subtarget.hasVInstructionsF32()) 151 for (MVT VT : F32VecVTs) 152 addRegClassForRVV(VT); 153 154 if (Subtarget.hasVInstructionsF64()) 155 for (MVT VT : F64VecVTs) 156 addRegClassForRVV(VT); 157 158 if (Subtarget.useRVVForFixedLengthVectors()) { 159 auto addRegClassForFixedVectors = [this](MVT VT) { 160 MVT ContainerVT = getContainerForFixedLengthVector(VT); 161 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 162 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 163 addRegisterClass(VT, TRI.getRegClass(RCID)); 164 }; 165 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 166 if (useRVVForFixedLengthVectorVT(VT)) 167 addRegClassForFixedVectors(VT); 168 169 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 170 if (useRVVForFixedLengthVectorVT(VT)) 171 addRegClassForFixedVectors(VT); 172 } 173 } 174 175 // Compute derived properties from the register classes. 176 computeRegisterProperties(STI.getRegisterInfo()); 177 178 setStackPointerRegisterToSaveRestore(RISCV::X2); 179 180 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, XLenVT, 181 MVT::i1, Promote); 182 183 // TODO: add all necessary setOperationAction calls. 184 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 185 186 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 187 setOperationAction(ISD::BR_CC, XLenVT, Expand); 188 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 189 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 190 191 setOperationAction({ISD::STACKSAVE, ISD::STACKRESTORE}, MVT::Other, Expand); 192 193 setOperationAction(ISD::VASTART, MVT::Other, Custom); 194 setOperationAction({ISD::VAARG, ISD::VACOPY, ISD::VAEND}, MVT::Other, Expand); 195 196 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 197 198 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 199 200 if (!Subtarget.hasStdExtZbb()) 201 setOperationAction(ISD::SIGN_EXTEND_INREG, {MVT::i8, MVT::i16}, Expand); 202 203 if (Subtarget.is64Bit()) { 204 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 205 206 setOperationAction({ISD::ADD, ISD::SUB, ISD::SHL, ISD::SRA, ISD::SRL}, 207 MVT::i32, Custom); 208 209 setOperationAction({ISD::UADDO, ISD::USUBO, ISD::UADDSAT, ISD::USUBSAT}, 210 MVT::i32, Custom); 211 } else { 212 setLibcallName( 213 {RTLIB::SHL_I128, RTLIB::SRL_I128, RTLIB::SRA_I128, RTLIB::MUL_I128}, 214 nullptr); 215 setLibcallName(RTLIB::MULO_I64, nullptr); 216 } 217 218 if (!Subtarget.hasStdExtM()) { 219 setOperationAction({ISD::MUL, ISD::MULHS, ISD::MULHU, ISD::SDIV, ISD::UDIV, 220 ISD::SREM, ISD::UREM}, 221 XLenVT, Expand); 222 } else { 223 if (Subtarget.is64Bit()) { 224 setOperationAction(ISD::MUL, {MVT::i32, MVT::i128}, Custom); 225 226 setOperationAction({ISD::SDIV, ISD::UDIV, ISD::UREM}, 227 {MVT::i8, MVT::i16, MVT::i32}, Custom); 228 } else { 229 setOperationAction(ISD::MUL, MVT::i64, Custom); 230 } 231 } 232 233 setOperationAction( 234 {ISD::SDIVREM, ISD::UDIVREM, ISD::SMUL_LOHI, ISD::UMUL_LOHI}, XLenVT, 235 Expand); 236 237 setOperationAction({ISD::SHL_PARTS, ISD::SRL_PARTS, ISD::SRA_PARTS}, XLenVT, 238 Custom); 239 240 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 241 Subtarget.hasStdExtZbkb()) { 242 if (Subtarget.is64Bit()) 243 setOperationAction({ISD::ROTL, ISD::ROTR}, MVT::i32, Custom); 244 } else { 245 setOperationAction({ISD::ROTL, ISD::ROTR}, XLenVT, Expand); 246 } 247 248 if (Subtarget.hasStdExtZbp()) { 249 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 250 // more combining. 251 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, XLenVT, Custom); 252 253 // BSWAP i8 doesn't exist. 254 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 255 256 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i16, Custom); 257 258 if (Subtarget.is64Bit()) 259 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i32, Custom); 260 } else { 261 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 262 // pattern match it directly in isel. 263 setOperationAction(ISD::BSWAP, XLenVT, 264 (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) 265 ? Legal 266 : Expand); 267 // Zbkb can use rev8+brev8 to implement bitreverse. 268 setOperationAction(ISD::BITREVERSE, XLenVT, 269 Subtarget.hasStdExtZbkb() ? Custom : Expand); 270 } 271 272 if (Subtarget.hasStdExtZbb()) { 273 setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, XLenVT, 274 Legal); 275 276 if (Subtarget.is64Bit()) 277 setOperationAction( 278 {ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF}, 279 MVT::i32, Custom); 280 } else { 281 setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP}, XLenVT, Expand); 282 283 if (Subtarget.is64Bit()) 284 setOperationAction(ISD::ABS, MVT::i32, Custom); 285 } 286 287 if (Subtarget.hasStdExtZbt()) { 288 setOperationAction({ISD::FSHL, ISD::FSHR}, XLenVT, Custom); 289 setOperationAction(ISD::SELECT, XLenVT, Legal); 290 291 if (Subtarget.is64Bit()) 292 setOperationAction({ISD::FSHL, ISD::FSHR}, MVT::i32, Custom); 293 } else { 294 setOperationAction(ISD::SELECT, XLenVT, Custom); 295 } 296 297 static constexpr ISD::NodeType FPLegalNodeTypes[] = { 298 ISD::FMINNUM, ISD::FMAXNUM, ISD::LRINT, 299 ISD::LLRINT, ISD::LROUND, ISD::LLROUND, 300 ISD::STRICT_LRINT, ISD::STRICT_LLRINT, ISD::STRICT_LROUND, 301 ISD::STRICT_LLROUND, ISD::STRICT_FMA, ISD::STRICT_FADD, 302 ISD::STRICT_FSUB, ISD::STRICT_FMUL, ISD::STRICT_FDIV, 303 ISD::STRICT_FSQRT, ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS}; 304 305 static const ISD::CondCode FPCCToExpand[] = { 306 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 307 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 308 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 309 310 static const ISD::NodeType FPOpToExpand[] = { 311 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 312 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 313 314 if (Subtarget.hasStdExtZfh()) 315 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 316 317 if (Subtarget.hasStdExtZfh()) { 318 for (auto NT : FPLegalNodeTypes) 319 setOperationAction(NT, MVT::f16, Legal); 320 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 321 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 322 setCondCodeAction(FPCCToExpand, MVT::f16, Expand); 323 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 324 setOperationAction(ISD::SELECT, MVT::f16, Custom); 325 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 326 327 setOperationAction({ISD::FREM, ISD::FCEIL, ISD::FFLOOR, ISD::FNEARBYINT, 328 ISD::FRINT, ISD::FROUND, ISD::FROUNDEVEN, ISD::FTRUNC, 329 ISD::FPOW, ISD::FPOWI, ISD::FCOS, ISD::FSIN, 330 ISD::FSINCOS, ISD::FEXP, ISD::FEXP2, ISD::FLOG, 331 ISD::FLOG2, ISD::FLOG10}, 332 MVT::f16, Promote); 333 334 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 335 // complete support for all operations in LegalizeDAG. 336 337 // We need to custom promote this. 338 if (Subtarget.is64Bit()) 339 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 340 } 341 342 if (Subtarget.hasStdExtF()) { 343 for (auto NT : FPLegalNodeTypes) 344 setOperationAction(NT, MVT::f32, Legal); 345 setCondCodeAction(FPCCToExpand, MVT::f32, Expand); 346 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 347 setOperationAction(ISD::SELECT, MVT::f32, Custom); 348 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 349 for (auto Op : FPOpToExpand) 350 setOperationAction(Op, MVT::f32, Expand); 351 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 352 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 353 } 354 355 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 356 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 357 358 if (Subtarget.hasStdExtD()) { 359 for (auto NT : FPLegalNodeTypes) 360 setOperationAction(NT, MVT::f64, Legal); 361 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 362 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 363 setCondCodeAction(FPCCToExpand, MVT::f64, Expand); 364 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 365 setOperationAction(ISD::SELECT, MVT::f64, Custom); 366 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 367 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 368 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 369 for (auto Op : FPOpToExpand) 370 setOperationAction(Op, MVT::f64, Expand); 371 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 372 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 373 } 374 375 if (Subtarget.is64Bit()) 376 setOperationAction({ISD::FP_TO_UINT, ISD::FP_TO_SINT, 377 ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT}, 378 MVT::i32, Custom); 379 380 if (Subtarget.hasStdExtF()) { 381 setOperationAction({ISD::FP_TO_UINT_SAT, ISD::FP_TO_SINT_SAT}, XLenVT, 382 Custom); 383 384 setOperationAction({ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT, 385 ISD::STRICT_UINT_TO_FP, ISD::STRICT_SINT_TO_FP}, 386 XLenVT, Legal); 387 388 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 389 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 390 } 391 392 setOperationAction({ISD::GlobalAddress, ISD::BlockAddress, ISD::ConstantPool, 393 ISD::JumpTable}, 394 XLenVT, Custom); 395 396 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 397 398 if (Subtarget.is64Bit()) 399 setOperationAction(ISD::Constant, MVT::i64, Custom); 400 401 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 402 // Unfortunately this can't be determined just from the ISA naming string. 403 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 404 Subtarget.is64Bit() ? Legal : Custom); 405 406 setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Legal); 407 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 408 if (Subtarget.is64Bit()) 409 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 410 411 if (Subtarget.hasStdExtA()) { 412 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 413 setMinCmpXchgSizeInBits(32); 414 } else { 415 setMaxAtomicSizeInBitsSupported(0); 416 } 417 418 setBooleanContents(ZeroOrOneBooleanContent); 419 420 if (Subtarget.hasVInstructions()) { 421 setBooleanVectorContents(ZeroOrOneBooleanContent); 422 423 setOperationAction(ISD::VSCALE, XLenVT, Custom); 424 425 // RVV intrinsics may have illegal operands. 426 // We also need to custom legalize vmv.x.s. 427 setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN}, 428 {MVT::i8, MVT::i16}, Custom); 429 if (Subtarget.is64Bit()) 430 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 431 else 432 setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN}, 433 MVT::i64, Custom); 434 435 setOperationAction({ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID}, 436 MVT::Other, Custom); 437 438 static const unsigned IntegerVPOps[] = { 439 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 440 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 441 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 442 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 443 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 444 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 445 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 446 ISD::VP_MERGE, ISD::VP_SELECT, ISD::VP_FPTOSI, 447 ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_SIGN_EXTEND, 448 ISD::VP_ZERO_EXTEND, ISD::VP_TRUNCATE}; 449 450 static const unsigned FloatingPointVPOps[] = { 451 ISD::VP_FADD, ISD::VP_FSUB, 452 ISD::VP_FMUL, ISD::VP_FDIV, 453 ISD::VP_FNEG, ISD::VP_FMA, 454 ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 455 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, 456 ISD::VP_MERGE, ISD::VP_SELECT, 457 ISD::VP_SITOFP, ISD::VP_UITOFP, 458 ISD::VP_SETCC, ISD::VP_FP_ROUND, 459 ISD::VP_FP_EXTEND}; 460 461 if (!Subtarget.is64Bit()) { 462 // We must custom-lower certain vXi64 operations on RV32 due to the vector 463 // element type being illegal. 464 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 465 MVT::i64, Custom); 466 467 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, 468 ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR, 469 ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 470 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}, 471 MVT::i64, Custom); 472 473 setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 474 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, 475 ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN, 476 ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN}, 477 MVT::i64, Custom); 478 } 479 480 for (MVT VT : BoolVecVTs) { 481 if (!isTypeLegal(VT)) 482 continue; 483 484 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 485 486 // Mask VTs are custom-expanded into a series of standard nodes 487 setOperationAction({ISD::TRUNCATE, ISD::CONCAT_VECTORS, 488 ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 489 VT, Custom); 490 491 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 492 Custom); 493 494 setOperationAction(ISD::SELECT, VT, Custom); 495 setOperationAction( 496 {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT, 497 Expand); 498 499 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom); 500 501 setOperationAction( 502 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 503 Custom); 504 505 setOperationAction( 506 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 507 Custom); 508 509 // RVV has native int->float & float->int conversions where the 510 // element type sizes are within one power-of-two of each other. Any 511 // wider distances between type sizes have to be lowered as sequences 512 // which progressively narrow the gap in stages. 513 setOperationAction( 514 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 515 VT, Custom); 516 517 // Expand all extending loads to types larger than this, and truncating 518 // stores from types larger than this. 519 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 520 setTruncStoreAction(OtherVT, VT, Expand); 521 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 522 VT, Expand); 523 } 524 525 setOperationAction( 526 {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_TRUNCATE, ISD::VP_SETCC}, VT, 527 Custom); 528 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 529 530 setOperationPromotedToType( 531 ISD::VECTOR_SPLICE, VT, 532 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount())); 533 } 534 535 for (MVT VT : IntVecVTs) { 536 if (!isTypeLegal(VT)) 537 continue; 538 539 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 540 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 541 542 // Vectors implement MULHS/MULHU. 543 setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand); 544 545 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 546 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) 547 setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand); 548 549 setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT, 550 Legal); 551 552 setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand); 553 554 setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP, ISD::BSWAP}, VT, 555 Expand); 556 557 setOperationAction(ISD::BSWAP, VT, Expand); 558 559 // Custom-lower extensions and truncations from/to mask types. 560 setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, 561 VT, Custom); 562 563 // RVV has native int->float & float->int conversions where the 564 // element type sizes are within one power-of-two of each other. Any 565 // wider distances between type sizes have to be lowered as sequences 566 // which progressively narrow the gap in stages. 567 setOperationAction( 568 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 569 VT, Custom); 570 571 setOperationAction( 572 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal); 573 574 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 575 // nodes which truncate by one power of two at a time. 576 setOperationAction(ISD::TRUNCATE, VT, Custom); 577 578 // Custom-lower insert/extract operations to simplify patterns. 579 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 580 Custom); 581 582 // Custom-lower reduction operations to set up the corresponding custom 583 // nodes' operands. 584 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, 585 ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR, 586 ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 587 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}, 588 VT, Custom); 589 590 setOperationAction(IntegerVPOps, VT, Custom); 591 592 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 593 594 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 595 VT, Custom); 596 597 setOperationAction( 598 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 599 Custom); 600 601 setOperationAction( 602 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 603 VT, Custom); 604 605 setOperationAction(ISD::SELECT, VT, Custom); 606 setOperationAction(ISD::SELECT_CC, VT, Expand); 607 608 setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom); 609 610 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 611 setTruncStoreAction(VT, OtherVT, Expand); 612 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 613 VT, Expand); 614 } 615 616 // Splice 617 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 618 619 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 620 // type that can represent the value exactly. 621 if (VT.getVectorElementType() != MVT::i64) { 622 MVT FloatEltVT = 623 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 624 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 625 if (isTypeLegal(FloatVT)) { 626 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 627 Custom); 628 } 629 } 630 } 631 632 // Expand various CCs to best match the RVV ISA, which natively supports UNE 633 // but no other unordered comparisons, and supports all ordered comparisons 634 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 635 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 636 // and we pattern-match those back to the "original", swapping operands once 637 // more. This way we catch both operations and both "vf" and "fv" forms with 638 // fewer patterns. 639 static const ISD::CondCode VFPCCToExpand[] = { 640 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 641 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 642 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 643 }; 644 645 // Sets common operation actions on RVV floating-point vector types. 646 const auto SetCommonVFPActions = [&](MVT VT) { 647 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 648 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 649 // sizes are within one power-of-two of each other. Therefore conversions 650 // between vXf16 and vXf64 must be lowered as sequences which convert via 651 // vXf32. 652 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 653 // Custom-lower insert/extract operations to simplify patterns. 654 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 655 Custom); 656 // Expand various condition codes (explained above). 657 setCondCodeAction(VFPCCToExpand, VT, Expand); 658 659 setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal); 660 661 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 662 VT, Custom); 663 664 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 665 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 666 VT, Custom); 667 668 // Expand FP operations that need libcalls. 669 setOperationAction(ISD::FREM, VT, Expand); 670 setOperationAction(ISD::FPOW, VT, Expand); 671 setOperationAction(ISD::FCOS, VT, Expand); 672 setOperationAction(ISD::FSIN, VT, Expand); 673 setOperationAction(ISD::FSINCOS, VT, Expand); 674 setOperationAction(ISD::FEXP, VT, Expand); 675 setOperationAction(ISD::FEXP2, VT, Expand); 676 setOperationAction(ISD::FLOG, VT, Expand); 677 setOperationAction(ISD::FLOG2, VT, Expand); 678 setOperationAction(ISD::FLOG10, VT, Expand); 679 setOperationAction(ISD::FRINT, VT, Expand); 680 setOperationAction(ISD::FNEARBYINT, VT, Expand); 681 682 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 683 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 684 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 685 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 686 687 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 688 689 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 690 691 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 692 VT, Custom); 693 694 setOperationAction( 695 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 696 Custom); 697 698 setOperationAction(ISD::SELECT, VT, Custom); 699 setOperationAction(ISD::SELECT_CC, VT, Expand); 700 701 setOperationAction( 702 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 703 VT, Custom); 704 705 setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom); 706 707 setOperationAction(FloatingPointVPOps, VT, Custom); 708 }; 709 710 // Sets common extload/truncstore actions on RVV floating-point vector 711 // types. 712 const auto SetCommonVFPExtLoadTruncStoreActions = 713 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 714 for (auto SmallVT : SmallerVTs) { 715 setTruncStoreAction(VT, SmallVT, Expand); 716 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 717 } 718 }; 719 720 if (Subtarget.hasVInstructionsF16()) { 721 for (MVT VT : F16VecVTs) { 722 if (!isTypeLegal(VT)) 723 continue; 724 SetCommonVFPActions(VT); 725 } 726 } 727 728 if (Subtarget.hasVInstructionsF32()) { 729 for (MVT VT : F32VecVTs) { 730 if (!isTypeLegal(VT)) 731 continue; 732 SetCommonVFPActions(VT); 733 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 734 } 735 } 736 737 if (Subtarget.hasVInstructionsF64()) { 738 for (MVT VT : F64VecVTs) { 739 if (!isTypeLegal(VT)) 740 continue; 741 SetCommonVFPActions(VT); 742 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 743 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 744 } 745 } 746 747 if (Subtarget.useRVVForFixedLengthVectors()) { 748 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 749 if (!useRVVForFixedLengthVectorVT(VT)) 750 continue; 751 752 // By default everything must be expanded. 753 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 754 setOperationAction(Op, VT, Expand); 755 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 756 setTruncStoreAction(VT, OtherVT, Expand); 757 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, 758 OtherVT, VT, Expand); 759 } 760 761 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 762 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 763 Custom); 764 765 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT, 766 Custom); 767 768 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 769 VT, Custom); 770 771 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 772 773 setOperationAction(ISD::SETCC, VT, Custom); 774 775 setOperationAction(ISD::SELECT, VT, Custom); 776 777 setOperationAction(ISD::TRUNCATE, VT, Custom); 778 779 setOperationAction(ISD::BITCAST, VT, Custom); 780 781 setOperationAction( 782 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 783 Custom); 784 785 setOperationAction( 786 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 787 Custom); 788 789 setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, 790 ISD::FP_TO_UINT}, 791 VT, Custom); 792 793 // Operations below are different for between masks and other vectors. 794 if (VT.getVectorElementType() == MVT::i1) { 795 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND, 796 ISD::OR, ISD::XOR}, 797 VT, Custom); 798 799 setOperationAction( 800 {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_TRUNCATE}, 801 VT, Custom); 802 continue; 803 } 804 805 // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to 806 // it before type legalization for i64 vectors on RV32. It will then be 807 // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle. 808 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 809 // improvements first. 810 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 811 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 812 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 813 } 814 815 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 816 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 817 818 setOperationAction( 819 {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom); 820 821 setOperationAction( 822 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 823 Custom); 824 825 setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR, 826 ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV, 827 ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL}, 828 VT, Custom); 829 830 setOperationAction( 831 {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom); 832 833 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 834 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) 835 setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom); 836 837 setOperationAction( 838 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, 839 Custom); 840 841 setOperationAction(ISD::VSELECT, VT, Custom); 842 setOperationAction(ISD::SELECT_CC, VT, Expand); 843 844 setOperationAction( 845 {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom); 846 847 // Custom-lower reduction operations to set up the corresponding custom 848 // nodes' operands. 849 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX, 850 ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX, 851 ISD::VECREDUCE_UMIN}, 852 VT, Custom); 853 854 setOperationAction(IntegerVPOps, VT, Custom); 855 856 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 857 // type that can represent the value exactly. 858 if (VT.getVectorElementType() != MVT::i64) { 859 MVT FloatEltVT = 860 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 861 EVT FloatVT = 862 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 863 if (isTypeLegal(FloatVT)) 864 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 865 Custom); 866 } 867 } 868 869 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 870 if (!useRVVForFixedLengthVectorVT(VT)) 871 continue; 872 873 // By default everything must be expanded. 874 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 875 setOperationAction(Op, VT, Expand); 876 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 877 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 878 setTruncStoreAction(VT, OtherVT, Expand); 879 } 880 881 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 882 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 883 Custom); 884 885 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS, 886 ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT, 887 ISD::EXTRACT_VECTOR_ELT}, 888 VT, Custom); 889 890 setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE, 891 ISD::MGATHER, ISD::MSCATTER}, 892 VT, Custom); 893 894 setOperationAction( 895 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 896 Custom); 897 898 setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV, 899 ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT, 900 ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM}, 901 VT, Custom); 902 903 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 904 905 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 906 VT, Custom); 907 908 for (auto CC : VFPCCToExpand) 909 setCondCodeAction(CC, VT, Expand); 910 911 setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom); 912 setOperationAction(ISD::SELECT_CC, VT, Expand); 913 914 setOperationAction(ISD::BITCAST, VT, Custom); 915 916 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 917 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 918 VT, Custom); 919 920 setOperationAction(FloatingPointVPOps, VT, Custom); 921 } 922 923 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 924 setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64}, 925 Custom); 926 if (Subtarget.hasStdExtZfh()) 927 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 928 if (Subtarget.hasStdExtF()) 929 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 930 if (Subtarget.hasStdExtD()) 931 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 932 } 933 } 934 935 // Function alignments. 936 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 937 setMinFunctionAlignment(FunctionAlignment); 938 setPrefFunctionAlignment(FunctionAlignment); 939 940 setMinimumJumpTableEntries(5); 941 942 // Jumps are expensive, compared to logic 943 setJumpIsExpensive(); 944 945 setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND, 946 ISD::OR, ISD::XOR}); 947 if (Subtarget.is64Bit()) 948 setTargetDAGCombine(ISD::SRA); 949 950 if (Subtarget.hasStdExtF()) 951 setTargetDAGCombine({ISD::FADD, ISD::FMAXNUM, ISD::FMINNUM}); 952 953 if (Subtarget.hasStdExtZbp()) 954 setTargetDAGCombine({ISD::ROTL, ISD::ROTR}); 955 956 if (Subtarget.hasStdExtZbb()) 957 setTargetDAGCombine({ISD::UMAX, ISD::UMIN, ISD::SMAX, ISD::SMIN}); 958 959 if (Subtarget.hasStdExtZbkb()) 960 setTargetDAGCombine(ISD::BITREVERSE); 961 if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb()) 962 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 963 if (Subtarget.hasStdExtF()) 964 setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT, 965 ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}); 966 if (Subtarget.hasVInstructions()) 967 setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER, 968 ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL, 969 ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR}); 970 if (Subtarget.useRVVForFixedLengthVectors()) 971 setTargetDAGCombine(ISD::BITCAST); 972 973 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 974 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 975 } 976 977 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 978 LLVMContext &Context, 979 EVT VT) const { 980 if (!VT.isVector()) 981 return getPointerTy(DL); 982 if (Subtarget.hasVInstructions() && 983 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 984 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 985 return VT.changeVectorElementTypeToInteger(); 986 } 987 988 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 989 return Subtarget.getXLenVT(); 990 } 991 992 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 993 const CallInst &I, 994 MachineFunction &MF, 995 unsigned Intrinsic) const { 996 auto &DL = I.getModule()->getDataLayout(); 997 switch (Intrinsic) { 998 default: 999 return false; 1000 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 1001 case Intrinsic::riscv_masked_atomicrmw_add_i32: 1002 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 1003 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1004 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1005 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1006 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1007 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1008 case Intrinsic::riscv_masked_cmpxchg_i32: 1009 Info.opc = ISD::INTRINSIC_W_CHAIN; 1010 Info.memVT = MVT::i32; 1011 Info.ptrVal = I.getArgOperand(0); 1012 Info.offset = 0; 1013 Info.align = Align(4); 1014 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1015 MachineMemOperand::MOVolatile; 1016 return true; 1017 case Intrinsic::riscv_masked_strided_load: 1018 Info.opc = ISD::INTRINSIC_W_CHAIN; 1019 Info.ptrVal = I.getArgOperand(1); 1020 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1021 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1022 Info.size = MemoryLocation::UnknownSize; 1023 Info.flags |= MachineMemOperand::MOLoad; 1024 return true; 1025 case Intrinsic::riscv_masked_strided_store: 1026 Info.opc = ISD::INTRINSIC_VOID; 1027 Info.ptrVal = I.getArgOperand(1); 1028 Info.memVT = 1029 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1030 Info.align = Align( 1031 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1032 8); 1033 Info.size = MemoryLocation::UnknownSize; 1034 Info.flags |= MachineMemOperand::MOStore; 1035 return true; 1036 case Intrinsic::riscv_seg2_load: 1037 case Intrinsic::riscv_seg3_load: 1038 case Intrinsic::riscv_seg4_load: 1039 case Intrinsic::riscv_seg5_load: 1040 case Intrinsic::riscv_seg6_load: 1041 case Intrinsic::riscv_seg7_load: 1042 case Intrinsic::riscv_seg8_load: 1043 Info.opc = ISD::INTRINSIC_W_CHAIN; 1044 Info.ptrVal = I.getArgOperand(0); 1045 Info.memVT = 1046 getValueType(DL, I.getType()->getStructElementType(0)->getScalarType()); 1047 Info.align = 1048 Align(DL.getTypeSizeInBits( 1049 I.getType()->getStructElementType(0)->getScalarType()) / 1050 8); 1051 Info.size = MemoryLocation::UnknownSize; 1052 Info.flags |= MachineMemOperand::MOLoad; 1053 return true; 1054 } 1055 } 1056 1057 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1058 const AddrMode &AM, Type *Ty, 1059 unsigned AS, 1060 Instruction *I) const { 1061 // No global is ever allowed as a base. 1062 if (AM.BaseGV) 1063 return false; 1064 1065 // RVV instructions only support register addressing. 1066 if (Subtarget.hasVInstructions() && isa<VectorType>(Ty)) 1067 return AM.HasBaseReg && AM.Scale == 0 && !AM.BaseOffs; 1068 1069 // Require a 12-bit signed offset. 1070 if (!isInt<12>(AM.BaseOffs)) 1071 return false; 1072 1073 switch (AM.Scale) { 1074 case 0: // "r+i" or just "i", depending on HasBaseReg. 1075 break; 1076 case 1: 1077 if (!AM.HasBaseReg) // allow "r+i". 1078 break; 1079 return false; // disallow "r+r" or "r+r+i". 1080 default: 1081 return false; 1082 } 1083 1084 return true; 1085 } 1086 1087 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1088 return isInt<12>(Imm); 1089 } 1090 1091 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1092 return isInt<12>(Imm); 1093 } 1094 1095 // On RV32, 64-bit integers are split into their high and low parts and held 1096 // in two different registers, so the trunc is free since the low register can 1097 // just be used. 1098 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1099 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1100 return false; 1101 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1102 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1103 return (SrcBits == 64 && DestBits == 32); 1104 } 1105 1106 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1107 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1108 !SrcVT.isInteger() || !DstVT.isInteger()) 1109 return false; 1110 unsigned SrcBits = SrcVT.getSizeInBits(); 1111 unsigned DestBits = DstVT.getSizeInBits(); 1112 return (SrcBits == 64 && DestBits == 32); 1113 } 1114 1115 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1116 // Zexts are free if they can be combined with a load. 1117 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1118 // poorly with type legalization of compares preferring sext. 1119 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1120 EVT MemVT = LD->getMemoryVT(); 1121 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1122 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1123 LD->getExtensionType() == ISD::ZEXTLOAD)) 1124 return true; 1125 } 1126 1127 return TargetLowering::isZExtFree(Val, VT2); 1128 } 1129 1130 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1131 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1132 } 1133 1134 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const { 1135 return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32); 1136 } 1137 1138 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1139 return Subtarget.hasStdExtZbb(); 1140 } 1141 1142 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1143 return Subtarget.hasStdExtZbb(); 1144 } 1145 1146 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1147 EVT VT = Y.getValueType(); 1148 1149 // FIXME: Support vectors once we have tests. 1150 if (VT.isVector()) 1151 return false; 1152 1153 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1154 Subtarget.hasStdExtZbkb()) && 1155 !isa<ConstantSDNode>(Y); 1156 } 1157 1158 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const { 1159 // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position. 1160 auto *C = dyn_cast<ConstantSDNode>(Y); 1161 return C && C->getAPIntValue().ule(10); 1162 } 1163 1164 bool RISCVTargetLowering:: 1165 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 1166 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y, 1167 unsigned OldShiftOpcode, unsigned NewShiftOpcode, 1168 SelectionDAG &DAG) const { 1169 // One interesting pattern that we'd want to form is 'bit extract': 1170 // ((1 >> Y) & 1) ==/!= 0 1171 // But we also need to be careful not to try to reverse that fold. 1172 1173 // Is this '((1 >> Y) & 1)'? 1174 if (XC && OldShiftOpcode == ISD::SRL && XC->isOne()) 1175 return false; // Keep the 'bit extract' pattern. 1176 1177 // Will this be '((1 >> Y) & 1)' after the transform? 1178 if (NewShiftOpcode == ISD::SRL && CC->isOne()) 1179 return true; // Do form the 'bit extract' pattern. 1180 1181 // If 'X' is a constant, and we transform, then we will immediately 1182 // try to undo the fold, thus causing endless combine loop. 1183 // So only do the transform if X is not a constant. This matches the default 1184 // implementation of this function. 1185 return !XC; 1186 } 1187 1188 /// Check if sinking \p I's operands to I's basic block is profitable, because 1189 /// the operands can be folded into a target instruction, e.g. 1190 /// splats of scalars can fold into vector instructions. 1191 bool RISCVTargetLowering::shouldSinkOperands( 1192 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1193 using namespace llvm::PatternMatch; 1194 1195 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1196 return false; 1197 1198 auto IsSinker = [&](Instruction *I, int Operand) { 1199 switch (I->getOpcode()) { 1200 case Instruction::Add: 1201 case Instruction::Sub: 1202 case Instruction::Mul: 1203 case Instruction::And: 1204 case Instruction::Or: 1205 case Instruction::Xor: 1206 case Instruction::FAdd: 1207 case Instruction::FSub: 1208 case Instruction::FMul: 1209 case Instruction::FDiv: 1210 case Instruction::ICmp: 1211 case Instruction::FCmp: 1212 return true; 1213 case Instruction::Shl: 1214 case Instruction::LShr: 1215 case Instruction::AShr: 1216 case Instruction::UDiv: 1217 case Instruction::SDiv: 1218 case Instruction::URem: 1219 case Instruction::SRem: 1220 return Operand == 1; 1221 case Instruction::Call: 1222 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1223 switch (II->getIntrinsicID()) { 1224 case Intrinsic::fma: 1225 case Intrinsic::vp_fma: 1226 return Operand == 0 || Operand == 1; 1227 // FIXME: Our patterns can only match vx/vf instructions when the splat 1228 // it on the RHS, because TableGen doesn't recognize our VP operations 1229 // as commutative. 1230 case Intrinsic::vp_add: 1231 case Intrinsic::vp_mul: 1232 case Intrinsic::vp_and: 1233 case Intrinsic::vp_or: 1234 case Intrinsic::vp_xor: 1235 case Intrinsic::vp_fadd: 1236 case Intrinsic::vp_fmul: 1237 case Intrinsic::vp_shl: 1238 case Intrinsic::vp_lshr: 1239 case Intrinsic::vp_ashr: 1240 case Intrinsic::vp_udiv: 1241 case Intrinsic::vp_sdiv: 1242 case Intrinsic::vp_urem: 1243 case Intrinsic::vp_srem: 1244 return Operand == 1; 1245 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1246 // explicit patterns for both LHS and RHS (as 'vr' versions). 1247 case Intrinsic::vp_sub: 1248 case Intrinsic::vp_fsub: 1249 case Intrinsic::vp_fdiv: 1250 return Operand == 0 || Operand == 1; 1251 default: 1252 return false; 1253 } 1254 } 1255 return false; 1256 default: 1257 return false; 1258 } 1259 }; 1260 1261 for (auto OpIdx : enumerate(I->operands())) { 1262 if (!IsSinker(I, OpIdx.index())) 1263 continue; 1264 1265 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1266 // Make sure we are not already sinking this operand 1267 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1268 continue; 1269 1270 // We are looking for a splat that can be sunk. 1271 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1272 m_Undef(), m_ZeroMask()))) 1273 continue; 1274 1275 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1276 // and vector registers 1277 for (Use &U : Op->uses()) { 1278 Instruction *Insn = cast<Instruction>(U.getUser()); 1279 if (!IsSinker(Insn, U.getOperandNo())) 1280 return false; 1281 } 1282 1283 Ops.push_back(&Op->getOperandUse(0)); 1284 Ops.push_back(&OpIdx.value()); 1285 } 1286 return true; 1287 } 1288 1289 bool RISCVTargetLowering::isOffsetFoldingLegal( 1290 const GlobalAddressSDNode *GA) const { 1291 // In order to maximise the opportunity for common subexpression elimination, 1292 // keep a separate ADD node for the global address offset instead of folding 1293 // it in the global address node. Later peephole optimisations may choose to 1294 // fold it back in when profitable. 1295 return false; 1296 } 1297 1298 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1299 bool ForCodeSize) const { 1300 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1301 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1302 return false; 1303 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1304 return false; 1305 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1306 return false; 1307 return Imm.isZero(); 1308 } 1309 1310 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1311 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1312 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1313 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1314 } 1315 1316 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1317 CallingConv::ID CC, 1318 EVT VT) const { 1319 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1320 // We might still end up using a GPR but that will be decided based on ABI. 1321 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1322 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1323 return MVT::f32; 1324 1325 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1326 } 1327 1328 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1329 CallingConv::ID CC, 1330 EVT VT) const { 1331 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1332 // We might still end up using a GPR but that will be decided based on ABI. 1333 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1334 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1335 return 1; 1336 1337 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1338 } 1339 1340 // Changes the condition code and swaps operands if necessary, so the SetCC 1341 // operation matches one of the comparisons supported directly by branches 1342 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1343 // with 1/-1. 1344 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1345 ISD::CondCode &CC, SelectionDAG &DAG) { 1346 // Convert X > -1 to X >= 0. 1347 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1348 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1349 CC = ISD::SETGE; 1350 return; 1351 } 1352 // Convert X < 1 to 0 >= X. 1353 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1354 RHS = LHS; 1355 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1356 CC = ISD::SETGE; 1357 return; 1358 } 1359 1360 switch (CC) { 1361 default: 1362 break; 1363 case ISD::SETGT: 1364 case ISD::SETLE: 1365 case ISD::SETUGT: 1366 case ISD::SETULE: 1367 CC = ISD::getSetCCSwappedOperands(CC); 1368 std::swap(LHS, RHS); 1369 break; 1370 } 1371 } 1372 1373 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1374 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1375 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1376 if (VT.getVectorElementType() == MVT::i1) 1377 KnownSize *= 8; 1378 1379 switch (KnownSize) { 1380 default: 1381 llvm_unreachable("Invalid LMUL."); 1382 case 8: 1383 return RISCVII::VLMUL::LMUL_F8; 1384 case 16: 1385 return RISCVII::VLMUL::LMUL_F4; 1386 case 32: 1387 return RISCVII::VLMUL::LMUL_F2; 1388 case 64: 1389 return RISCVII::VLMUL::LMUL_1; 1390 case 128: 1391 return RISCVII::VLMUL::LMUL_2; 1392 case 256: 1393 return RISCVII::VLMUL::LMUL_4; 1394 case 512: 1395 return RISCVII::VLMUL::LMUL_8; 1396 } 1397 } 1398 1399 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1400 switch (LMul) { 1401 default: 1402 llvm_unreachable("Invalid LMUL."); 1403 case RISCVII::VLMUL::LMUL_F8: 1404 case RISCVII::VLMUL::LMUL_F4: 1405 case RISCVII::VLMUL::LMUL_F2: 1406 case RISCVII::VLMUL::LMUL_1: 1407 return RISCV::VRRegClassID; 1408 case RISCVII::VLMUL::LMUL_2: 1409 return RISCV::VRM2RegClassID; 1410 case RISCVII::VLMUL::LMUL_4: 1411 return RISCV::VRM4RegClassID; 1412 case RISCVII::VLMUL::LMUL_8: 1413 return RISCV::VRM8RegClassID; 1414 } 1415 } 1416 1417 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1418 RISCVII::VLMUL LMUL = getLMUL(VT); 1419 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1420 LMUL == RISCVII::VLMUL::LMUL_F4 || 1421 LMUL == RISCVII::VLMUL::LMUL_F2 || 1422 LMUL == RISCVII::VLMUL::LMUL_1) { 1423 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1424 "Unexpected subreg numbering"); 1425 return RISCV::sub_vrm1_0 + Index; 1426 } 1427 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1428 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1429 "Unexpected subreg numbering"); 1430 return RISCV::sub_vrm2_0 + Index; 1431 } 1432 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1433 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1434 "Unexpected subreg numbering"); 1435 return RISCV::sub_vrm4_0 + Index; 1436 } 1437 llvm_unreachable("Invalid vector type."); 1438 } 1439 1440 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1441 if (VT.getVectorElementType() == MVT::i1) 1442 return RISCV::VRRegClassID; 1443 return getRegClassIDForLMUL(getLMUL(VT)); 1444 } 1445 1446 // Attempt to decompose a subvector insert/extract between VecVT and 1447 // SubVecVT via subregister indices. Returns the subregister index that 1448 // can perform the subvector insert/extract with the given element index, as 1449 // well as the index corresponding to any leftover subvectors that must be 1450 // further inserted/extracted within the register class for SubVecVT. 1451 std::pair<unsigned, unsigned> 1452 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1453 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1454 const RISCVRegisterInfo *TRI) { 1455 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1456 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1457 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1458 "Register classes not ordered"); 1459 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1460 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1461 // Try to compose a subregister index that takes us from the incoming 1462 // LMUL>1 register class down to the outgoing one. At each step we half 1463 // the LMUL: 1464 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1465 // Note that this is not guaranteed to find a subregister index, such as 1466 // when we are extracting from one VR type to another. 1467 unsigned SubRegIdx = RISCV::NoSubRegister; 1468 for (const unsigned RCID : 1469 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1470 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1471 VecVT = VecVT.getHalfNumVectorElementsVT(); 1472 bool IsHi = 1473 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1474 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1475 getSubregIndexByMVT(VecVT, IsHi)); 1476 if (IsHi) 1477 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1478 } 1479 return {SubRegIdx, InsertExtractIdx}; 1480 } 1481 1482 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1483 // stores for those types. 1484 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1485 return !Subtarget.useRVVForFixedLengthVectors() || 1486 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1487 } 1488 1489 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1490 if (ScalarTy->isPointerTy()) 1491 return true; 1492 1493 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1494 ScalarTy->isIntegerTy(32)) 1495 return true; 1496 1497 if (ScalarTy->isIntegerTy(64)) 1498 return Subtarget.hasVInstructionsI64(); 1499 1500 if (ScalarTy->isHalfTy()) 1501 return Subtarget.hasVInstructionsF16(); 1502 if (ScalarTy->isFloatTy()) 1503 return Subtarget.hasVInstructionsF32(); 1504 if (ScalarTy->isDoubleTy()) 1505 return Subtarget.hasVInstructionsF64(); 1506 1507 return false; 1508 } 1509 1510 static SDValue getVLOperand(SDValue Op) { 1511 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1512 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1513 "Unexpected opcode"); 1514 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1515 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1516 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1517 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1518 if (!II) 1519 return SDValue(); 1520 return Op.getOperand(II->VLOperand + 1 + HasChain); 1521 } 1522 1523 static bool useRVVForFixedLengthVectorVT(MVT VT, 1524 const RISCVSubtarget &Subtarget) { 1525 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1526 if (!Subtarget.useRVVForFixedLengthVectors()) 1527 return false; 1528 1529 // We only support a set of vector types with a consistent maximum fixed size 1530 // across all supported vector element types to avoid legalization issues. 1531 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1532 // fixed-length vector type we support is 1024 bytes. 1533 if (VT.getFixedSizeInBits() > 1024 * 8) 1534 return false; 1535 1536 unsigned MinVLen = Subtarget.getRealMinVLen(); 1537 1538 MVT EltVT = VT.getVectorElementType(); 1539 1540 // Don't use RVV for vectors we cannot scalarize if required. 1541 switch (EltVT.SimpleTy) { 1542 // i1 is supported but has different rules. 1543 default: 1544 return false; 1545 case MVT::i1: 1546 // Masks can only use a single register. 1547 if (VT.getVectorNumElements() > MinVLen) 1548 return false; 1549 MinVLen /= 8; 1550 break; 1551 case MVT::i8: 1552 case MVT::i16: 1553 case MVT::i32: 1554 break; 1555 case MVT::i64: 1556 if (!Subtarget.hasVInstructionsI64()) 1557 return false; 1558 break; 1559 case MVT::f16: 1560 if (!Subtarget.hasVInstructionsF16()) 1561 return false; 1562 break; 1563 case MVT::f32: 1564 if (!Subtarget.hasVInstructionsF32()) 1565 return false; 1566 break; 1567 case MVT::f64: 1568 if (!Subtarget.hasVInstructionsF64()) 1569 return false; 1570 break; 1571 } 1572 1573 // Reject elements larger than ELEN. 1574 if (EltVT.getSizeInBits() > Subtarget.getELEN()) 1575 return false; 1576 1577 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1578 // Don't use RVV for types that don't fit. 1579 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1580 return false; 1581 1582 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1583 // the base fixed length RVV support in place. 1584 if (!VT.isPow2VectorType()) 1585 return false; 1586 1587 return true; 1588 } 1589 1590 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1591 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1592 } 1593 1594 // Return the largest legal scalable vector type that matches VT's element type. 1595 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1596 const RISCVSubtarget &Subtarget) { 1597 // This may be called before legal types are setup. 1598 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1599 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1600 "Expected legal fixed length vector!"); 1601 1602 unsigned MinVLen = Subtarget.getRealMinVLen(); 1603 unsigned MaxELen = Subtarget.getELEN(); 1604 1605 MVT EltVT = VT.getVectorElementType(); 1606 switch (EltVT.SimpleTy) { 1607 default: 1608 llvm_unreachable("unexpected element type for RVV container"); 1609 case MVT::i1: 1610 case MVT::i8: 1611 case MVT::i16: 1612 case MVT::i32: 1613 case MVT::i64: 1614 case MVT::f16: 1615 case MVT::f32: 1616 case MVT::f64: { 1617 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1618 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1619 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1620 unsigned NumElts = 1621 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1622 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1623 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1624 return MVT::getScalableVectorVT(EltVT, NumElts); 1625 } 1626 } 1627 } 1628 1629 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1630 const RISCVSubtarget &Subtarget) { 1631 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1632 Subtarget); 1633 } 1634 1635 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1636 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1637 } 1638 1639 // Grow V to consume an entire RVV register. 1640 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1641 const RISCVSubtarget &Subtarget) { 1642 assert(VT.isScalableVector() && 1643 "Expected to convert into a scalable vector!"); 1644 assert(V.getValueType().isFixedLengthVector() && 1645 "Expected a fixed length vector operand!"); 1646 SDLoc DL(V); 1647 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1648 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1649 } 1650 1651 // Shrink V so it's just big enough to maintain a VT's worth of data. 1652 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1653 const RISCVSubtarget &Subtarget) { 1654 assert(VT.isFixedLengthVector() && 1655 "Expected to convert into a fixed length vector!"); 1656 assert(V.getValueType().isScalableVector() && 1657 "Expected a scalable vector operand!"); 1658 SDLoc DL(V); 1659 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1660 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1661 } 1662 1663 /// Return the type of the mask type suitable for masking the provided 1664 /// vector type. This is simply an i1 element type vector of the same 1665 /// (possibly scalable) length. 1666 static MVT getMaskTypeFor(EVT VecVT) { 1667 assert(VecVT.isVector()); 1668 ElementCount EC = VecVT.getVectorElementCount(); 1669 return MVT::getVectorVT(MVT::i1, EC); 1670 } 1671 1672 /// Creates an all ones mask suitable for masking a vector of type VecTy with 1673 /// vector length VL. . 1674 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL, 1675 SelectionDAG &DAG) { 1676 MVT MaskVT = getMaskTypeFor(VecVT); 1677 return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1678 } 1679 1680 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1681 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1682 // the vector type that it is contained in. 1683 static std::pair<SDValue, SDValue> 1684 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1685 const RISCVSubtarget &Subtarget) { 1686 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1687 MVT XLenVT = Subtarget.getXLenVT(); 1688 SDValue VL = VecVT.isFixedLengthVector() 1689 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1690 : DAG.getRegister(RISCV::X0, XLenVT); 1691 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 1692 return {Mask, VL}; 1693 } 1694 1695 // As above but assuming the given type is a scalable vector type. 1696 static std::pair<SDValue, SDValue> 1697 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1698 const RISCVSubtarget &Subtarget) { 1699 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1700 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1701 } 1702 1703 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1704 // of either is (currently) supported. This can get us into an infinite loop 1705 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1706 // as a ..., etc. 1707 // Until either (or both) of these can reliably lower any node, reporting that 1708 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1709 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1710 // which is not desirable. 1711 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1712 EVT VT, unsigned DefinedValues) const { 1713 return false; 1714 } 1715 1716 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1717 const RISCVSubtarget &Subtarget) { 1718 // RISCV FP-to-int conversions saturate to the destination register size, but 1719 // don't produce 0 for nan. We can use a conversion instruction and fix the 1720 // nan case with a compare and a select. 1721 SDValue Src = Op.getOperand(0); 1722 1723 EVT DstVT = Op.getValueType(); 1724 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1725 1726 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1727 unsigned Opc; 1728 if (SatVT == DstVT) 1729 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1730 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1731 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1732 else 1733 return SDValue(); 1734 // FIXME: Support other SatVTs by clamping before or after the conversion. 1735 1736 SDLoc DL(Op); 1737 SDValue FpToInt = DAG.getNode( 1738 Opc, DL, DstVT, Src, 1739 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1740 1741 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1742 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1743 } 1744 1745 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1746 // and back. Taking care to avoid converting values that are nan or already 1747 // correct. 1748 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1749 // have FRM dependencies modeled yet. 1750 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1751 MVT VT = Op.getSimpleValueType(); 1752 assert(VT.isVector() && "Unexpected type"); 1753 1754 SDLoc DL(Op); 1755 1756 // Freeze the source since we are increasing the number of uses. 1757 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1758 1759 // Truncate to integer and convert back to FP. 1760 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1761 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1762 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1763 1764 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1765 1766 if (Op.getOpcode() == ISD::FCEIL) { 1767 // If the truncated value is the greater than or equal to the original 1768 // value, we've computed the ceil. Otherwise, we went the wrong way and 1769 // need to increase by 1. 1770 // FIXME: This should use a masked operation. Handle here or in isel? 1771 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1772 DAG.getConstantFP(1.0, DL, VT)); 1773 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1774 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1775 } else if (Op.getOpcode() == ISD::FFLOOR) { 1776 // If the truncated value is the less than or equal to the original value, 1777 // we've computed the floor. Otherwise, we went the wrong way and need to 1778 // decrease by 1. 1779 // FIXME: This should use a masked operation. Handle here or in isel? 1780 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1781 DAG.getConstantFP(1.0, DL, VT)); 1782 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1783 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1784 } 1785 1786 // Restore the original sign so that -0.0 is preserved. 1787 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1788 1789 // Determine the largest integer that can be represented exactly. This and 1790 // values larger than it don't have any fractional bits so don't need to 1791 // be converted. 1792 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1793 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1794 APFloat MaxVal = APFloat(FltSem); 1795 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1796 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1797 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1798 1799 // If abs(Src) was larger than MaxVal or nan, keep it. 1800 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1801 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1802 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1803 } 1804 1805 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1806 // This mode isn't supported in vector hardware on RISCV. But as long as we 1807 // aren't compiling with trapping math, we can emulate this with 1808 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1809 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1810 // dependencies modeled yet. 1811 // FIXME: Use masked operations to avoid final merge. 1812 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1813 MVT VT = Op.getSimpleValueType(); 1814 assert(VT.isVector() && "Unexpected type"); 1815 1816 SDLoc DL(Op); 1817 1818 // Freeze the source since we are increasing the number of uses. 1819 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1820 1821 // We do the conversion on the absolute value and fix the sign at the end. 1822 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1823 1824 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1825 bool Ignored; 1826 APFloat Point5Pred = APFloat(0.5f); 1827 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1828 Point5Pred.next(/*nextDown*/ true); 1829 1830 // Add the adjustment. 1831 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1832 DAG.getConstantFP(Point5Pred, DL, VT)); 1833 1834 // Truncate to integer and convert back to fp. 1835 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1836 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1837 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1838 1839 // Restore the original sign. 1840 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1841 1842 // Determine the largest integer that can be represented exactly. This and 1843 // values larger than it don't have any fractional bits so don't need to 1844 // be converted. 1845 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1846 APFloat MaxVal = APFloat(FltSem); 1847 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1848 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1849 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1850 1851 // If abs(Src) was larger than MaxVal or nan, keep it. 1852 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1853 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1854 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1855 } 1856 1857 struct VIDSequence { 1858 int64_t StepNumerator; 1859 unsigned StepDenominator; 1860 int64_t Addend; 1861 }; 1862 1863 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1864 // to the (non-zero) step S and start value X. This can be then lowered as the 1865 // RVV sequence (VID * S) + X, for example. 1866 // The step S is represented as an integer numerator divided by a positive 1867 // denominator. Note that the implementation currently only identifies 1868 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1869 // cannot detect 2/3, for example. 1870 // Note that this method will also match potentially unappealing index 1871 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1872 // determine whether this is worth generating code for. 1873 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1874 unsigned NumElts = Op.getNumOperands(); 1875 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1876 if (!Op.getValueType().isInteger()) 1877 return None; 1878 1879 Optional<unsigned> SeqStepDenom; 1880 Optional<int64_t> SeqStepNum, SeqAddend; 1881 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1882 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1883 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1884 // Assume undef elements match the sequence; we just have to be careful 1885 // when interpolating across them. 1886 if (Op.getOperand(Idx).isUndef()) 1887 continue; 1888 // The BUILD_VECTOR must be all constants. 1889 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1890 return None; 1891 1892 uint64_t Val = Op.getConstantOperandVal(Idx) & 1893 maskTrailingOnes<uint64_t>(EltSizeInBits); 1894 1895 if (PrevElt) { 1896 // Calculate the step since the last non-undef element, and ensure 1897 // it's consistent across the entire sequence. 1898 unsigned IdxDiff = Idx - PrevElt->second; 1899 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1900 1901 // A zero-value value difference means that we're somewhere in the middle 1902 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1903 // step change before evaluating the sequence. 1904 if (ValDiff == 0) 1905 continue; 1906 1907 int64_t Remainder = ValDiff % IdxDiff; 1908 // Normalize the step if it's greater than 1. 1909 if (Remainder != ValDiff) { 1910 // The difference must cleanly divide the element span. 1911 if (Remainder != 0) 1912 return None; 1913 ValDiff /= IdxDiff; 1914 IdxDiff = 1; 1915 } 1916 1917 if (!SeqStepNum) 1918 SeqStepNum = ValDiff; 1919 else if (ValDiff != SeqStepNum) 1920 return None; 1921 1922 if (!SeqStepDenom) 1923 SeqStepDenom = IdxDiff; 1924 else if (IdxDiff != *SeqStepDenom) 1925 return None; 1926 } 1927 1928 // Record this non-undef element for later. 1929 if (!PrevElt || PrevElt->first != Val) 1930 PrevElt = std::make_pair(Val, Idx); 1931 } 1932 1933 // We need to have logged a step for this to count as a legal index sequence. 1934 if (!SeqStepNum || !SeqStepDenom) 1935 return None; 1936 1937 // Loop back through the sequence and validate elements we might have skipped 1938 // while waiting for a valid step. While doing this, log any sequence addend. 1939 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1940 if (Op.getOperand(Idx).isUndef()) 1941 continue; 1942 uint64_t Val = Op.getConstantOperandVal(Idx) & 1943 maskTrailingOnes<uint64_t>(EltSizeInBits); 1944 uint64_t ExpectedVal = 1945 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1946 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1947 if (!SeqAddend) 1948 SeqAddend = Addend; 1949 else if (Addend != SeqAddend) 1950 return None; 1951 } 1952 1953 assert(SeqAddend && "Must have an addend if we have a step"); 1954 1955 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1956 } 1957 1958 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1959 // and lower it as a VRGATHER_VX_VL from the source vector. 1960 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 1961 SelectionDAG &DAG, 1962 const RISCVSubtarget &Subtarget) { 1963 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1964 return SDValue(); 1965 SDValue Vec = SplatVal.getOperand(0); 1966 // Only perform this optimization on vectors of the same size for simplicity. 1967 // Don't perform this optimization for i1 vectors. 1968 // FIXME: Support i1 vectors, maybe by promoting to i8? 1969 if (Vec.getValueType() != VT || VT.getVectorElementType() == MVT::i1) 1970 return SDValue(); 1971 SDValue Idx = SplatVal.getOperand(1); 1972 // The index must be a legal type. 1973 if (Idx.getValueType() != Subtarget.getXLenVT()) 1974 return SDValue(); 1975 1976 MVT ContainerVT = VT; 1977 if (VT.isFixedLengthVector()) { 1978 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1979 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 1980 } 1981 1982 SDValue Mask, VL; 1983 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1984 1985 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 1986 Idx, Mask, DAG.getUNDEF(ContainerVT), VL); 1987 1988 if (!VT.isFixedLengthVector()) 1989 return Gather; 1990 1991 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 1992 } 1993 1994 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1995 const RISCVSubtarget &Subtarget) { 1996 MVT VT = Op.getSimpleValueType(); 1997 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1998 1999 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2000 2001 SDLoc DL(Op); 2002 SDValue Mask, VL; 2003 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2004 2005 MVT XLenVT = Subtarget.getXLenVT(); 2006 unsigned NumElts = Op.getNumOperands(); 2007 2008 if (VT.getVectorElementType() == MVT::i1) { 2009 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 2010 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 2011 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 2012 } 2013 2014 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 2015 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 2016 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 2017 } 2018 2019 // Lower constant mask BUILD_VECTORs via an integer vector type, in 2020 // scalar integer chunks whose bit-width depends on the number of mask 2021 // bits and XLEN. 2022 // First, determine the most appropriate scalar integer type to use. This 2023 // is at most XLenVT, but may be shrunk to a smaller vector element type 2024 // according to the size of the final vector - use i8 chunks rather than 2025 // XLenVT if we're producing a v8i1. This results in more consistent 2026 // codegen across RV32 and RV64. 2027 unsigned NumViaIntegerBits = 2028 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 2029 NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN()); 2030 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 2031 // If we have to use more than one INSERT_VECTOR_ELT then this 2032 // optimization is likely to increase code size; avoid peforming it in 2033 // such a case. We can use a load from a constant pool in this case. 2034 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 2035 return SDValue(); 2036 // Now we can create our integer vector type. Note that it may be larger 2037 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2038 MVT IntegerViaVecVT = 2039 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2040 divideCeil(NumElts, NumViaIntegerBits)); 2041 2042 uint64_t Bits = 0; 2043 unsigned BitPos = 0, IntegerEltIdx = 0; 2044 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2045 2046 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2047 // Once we accumulate enough bits to fill our scalar type, insert into 2048 // our vector and clear our accumulated data. 2049 if (I != 0 && I % NumViaIntegerBits == 0) { 2050 if (NumViaIntegerBits <= 32) 2051 Bits = SignExtend64<32>(Bits); 2052 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2053 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2054 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2055 Bits = 0; 2056 BitPos = 0; 2057 IntegerEltIdx++; 2058 } 2059 SDValue V = Op.getOperand(I); 2060 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2061 Bits |= ((uint64_t)BitValue << BitPos); 2062 } 2063 2064 // Insert the (remaining) scalar value into position in our integer 2065 // vector type. 2066 if (NumViaIntegerBits <= 32) 2067 Bits = SignExtend64<32>(Bits); 2068 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2069 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2070 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2071 2072 if (NumElts < NumViaIntegerBits) { 2073 // If we're producing a smaller vector than our minimum legal integer 2074 // type, bitcast to the equivalent (known-legal) mask type, and extract 2075 // our final mask. 2076 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2077 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2078 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2079 DAG.getConstant(0, DL, XLenVT)); 2080 } else { 2081 // Else we must have produced an integer type with the same size as the 2082 // mask type; bitcast for the final result. 2083 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2084 Vec = DAG.getBitcast(VT, Vec); 2085 } 2086 2087 return Vec; 2088 } 2089 2090 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2091 // vector type, we have a legal equivalently-sized i8 type, so we can use 2092 // that. 2093 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2094 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2095 2096 SDValue WideVec; 2097 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2098 // For a splat, perform a scalar truncate before creating the wider 2099 // vector. 2100 assert(Splat.getValueType() == XLenVT && 2101 "Unexpected type for i1 splat value"); 2102 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2103 DAG.getConstant(1, DL, XLenVT)); 2104 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2105 } else { 2106 SmallVector<SDValue, 8> Ops(Op->op_values()); 2107 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2108 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2109 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2110 } 2111 2112 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2113 } 2114 2115 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2116 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2117 return Gather; 2118 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2119 : RISCVISD::VMV_V_X_VL; 2120 Splat = 2121 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2122 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2123 } 2124 2125 // Try and match index sequences, which we can lower to the vid instruction 2126 // with optional modifications. An all-undef vector is matched by 2127 // getSplatValue, above. 2128 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2129 int64_t StepNumerator = SimpleVID->StepNumerator; 2130 unsigned StepDenominator = SimpleVID->StepDenominator; 2131 int64_t Addend = SimpleVID->Addend; 2132 2133 assert(StepNumerator != 0 && "Invalid step"); 2134 bool Negate = false; 2135 int64_t SplatStepVal = StepNumerator; 2136 unsigned StepOpcode = ISD::MUL; 2137 if (StepNumerator != 1) { 2138 if (isPowerOf2_64(std::abs(StepNumerator))) { 2139 Negate = StepNumerator < 0; 2140 StepOpcode = ISD::SHL; 2141 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2142 } 2143 } 2144 2145 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2146 // threshold since it's the immediate value many RVV instructions accept. 2147 // There is no vmul.vi instruction so ensure multiply constant can fit in 2148 // a single addi instruction. 2149 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2150 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2151 isPowerOf2_32(StepDenominator) && 2152 (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) { 2153 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2154 // Convert right out of the scalable type so we can use standard ISD 2155 // nodes for the rest of the computation. If we used scalable types with 2156 // these, we'd lose the fixed-length vector info and generate worse 2157 // vsetvli code. 2158 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2159 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2160 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2161 SDValue SplatStep = DAG.getSplatBuildVector( 2162 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2163 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2164 } 2165 if (StepDenominator != 1) { 2166 SDValue SplatStep = DAG.getSplatBuildVector( 2167 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2168 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2169 } 2170 if (Addend != 0 || Negate) { 2171 SDValue SplatAddend = DAG.getSplatBuildVector( 2172 VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2173 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2174 } 2175 return VID; 2176 } 2177 } 2178 2179 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2180 // when re-interpreted as a vector with a larger element type. For example, 2181 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2182 // could be instead splat as 2183 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2184 // TODO: This optimization could also work on non-constant splats, but it 2185 // would require bit-manipulation instructions to construct the splat value. 2186 SmallVector<SDValue> Sequence; 2187 unsigned EltBitSize = VT.getScalarSizeInBits(); 2188 const auto *BV = cast<BuildVectorSDNode>(Op); 2189 if (VT.isInteger() && EltBitSize < 64 && 2190 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2191 BV->getRepeatedSequence(Sequence) && 2192 (Sequence.size() * EltBitSize) <= 64) { 2193 unsigned SeqLen = Sequence.size(); 2194 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2195 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2196 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2197 ViaIntVT == MVT::i64) && 2198 "Unexpected sequence type"); 2199 2200 unsigned EltIdx = 0; 2201 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2202 uint64_t SplatValue = 0; 2203 // Construct the amalgamated value which can be splatted as this larger 2204 // vector type. 2205 for (const auto &SeqV : Sequence) { 2206 if (!SeqV.isUndef()) 2207 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2208 << (EltIdx * EltBitSize)); 2209 EltIdx++; 2210 } 2211 2212 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2213 // achieve better constant materializion. 2214 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2215 SplatValue = SignExtend64<32>(SplatValue); 2216 2217 // Since we can't introduce illegal i64 types at this stage, we can only 2218 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2219 // way we can use RVV instructions to splat. 2220 assert((ViaIntVT.bitsLE(XLenVT) || 2221 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2222 "Unexpected bitcast sequence"); 2223 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2224 SDValue ViaVL = 2225 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2226 MVT ViaContainerVT = 2227 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2228 SDValue Splat = 2229 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2230 DAG.getUNDEF(ViaContainerVT), 2231 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2232 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2233 return DAG.getBitcast(VT, Splat); 2234 } 2235 } 2236 2237 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2238 // which constitute a large proportion of the elements. In such cases we can 2239 // splat a vector with the dominant element and make up the shortfall with 2240 // INSERT_VECTOR_ELTs. 2241 // Note that this includes vectors of 2 elements by association. The 2242 // upper-most element is the "dominant" one, allowing us to use a splat to 2243 // "insert" the upper element, and an insert of the lower element at position 2244 // 0, which improves codegen. 2245 SDValue DominantValue; 2246 unsigned MostCommonCount = 0; 2247 DenseMap<SDValue, unsigned> ValueCounts; 2248 unsigned NumUndefElts = 2249 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2250 2251 // Track the number of scalar loads we know we'd be inserting, estimated as 2252 // any non-zero floating-point constant. Other kinds of element are either 2253 // already in registers or are materialized on demand. The threshold at which 2254 // a vector load is more desirable than several scalar materializion and 2255 // vector-insertion instructions is not known. 2256 unsigned NumScalarLoads = 0; 2257 2258 for (SDValue V : Op->op_values()) { 2259 if (V.isUndef()) 2260 continue; 2261 2262 ValueCounts.insert(std::make_pair(V, 0)); 2263 unsigned &Count = ValueCounts[V]; 2264 2265 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2266 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2267 2268 // Is this value dominant? In case of a tie, prefer the highest element as 2269 // it's cheaper to insert near the beginning of a vector than it is at the 2270 // end. 2271 if (++Count >= MostCommonCount) { 2272 DominantValue = V; 2273 MostCommonCount = Count; 2274 } 2275 } 2276 2277 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2278 unsigned NumDefElts = NumElts - NumUndefElts; 2279 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2280 2281 // Don't perform this optimization when optimizing for size, since 2282 // materializing elements and inserting them tends to cause code bloat. 2283 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2284 ((MostCommonCount > DominantValueCountThreshold) || 2285 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2286 // Start by splatting the most common element. 2287 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2288 2289 DenseSet<SDValue> Processed{DominantValue}; 2290 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2291 for (const auto &OpIdx : enumerate(Op->ops())) { 2292 const SDValue &V = OpIdx.value(); 2293 if (V.isUndef() || !Processed.insert(V).second) 2294 continue; 2295 if (ValueCounts[V] == 1) { 2296 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2297 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2298 } else { 2299 // Blend in all instances of this value using a VSELECT, using a 2300 // mask where each bit signals whether that element is the one 2301 // we're after. 2302 SmallVector<SDValue> Ops; 2303 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2304 return DAG.getConstant(V == V1, DL, XLenVT); 2305 }); 2306 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2307 DAG.getBuildVector(SelMaskTy, DL, Ops), 2308 DAG.getSplatBuildVector(VT, DL, V), Vec); 2309 } 2310 } 2311 2312 return Vec; 2313 } 2314 2315 return SDValue(); 2316 } 2317 2318 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2319 SDValue Lo, SDValue Hi, SDValue VL, 2320 SelectionDAG &DAG) { 2321 if (!Passthru) 2322 Passthru = DAG.getUNDEF(VT); 2323 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2324 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2325 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2326 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2327 // node in order to try and match RVV vector/scalar instructions. 2328 if ((LoC >> 31) == HiC) 2329 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2330 2331 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2332 // vmv.v.x whose EEW = 32 to lower it. 2333 auto *Const = dyn_cast<ConstantSDNode>(VL); 2334 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2335 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2336 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2337 // access the subtarget here now. 2338 auto InterVec = DAG.getNode( 2339 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2340 DAG.getRegister(RISCV::X0, MVT::i32)); 2341 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2342 } 2343 } 2344 2345 // Fall back to a stack store and stride x0 vector load. 2346 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2347 Hi, VL); 2348 } 2349 2350 // Called by type legalization to handle splat of i64 on RV32. 2351 // FIXME: We can optimize this when the type has sign or zero bits in one 2352 // of the halves. 2353 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2354 SDValue Scalar, SDValue VL, 2355 SelectionDAG &DAG) { 2356 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2357 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2358 DAG.getConstant(0, DL, MVT::i32)); 2359 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2360 DAG.getConstant(1, DL, MVT::i32)); 2361 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2362 } 2363 2364 // This function lowers a splat of a scalar operand Splat with the vector 2365 // length VL. It ensures the final sequence is type legal, which is useful when 2366 // lowering a splat after type legalization. 2367 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2368 MVT VT, SDLoc DL, SelectionDAG &DAG, 2369 const RISCVSubtarget &Subtarget) { 2370 bool HasPassthru = Passthru && !Passthru.isUndef(); 2371 if (!HasPassthru && !Passthru) 2372 Passthru = DAG.getUNDEF(VT); 2373 if (VT.isFloatingPoint()) { 2374 // If VL is 1, we could use vfmv.s.f. 2375 if (isOneConstant(VL)) 2376 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2377 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2378 } 2379 2380 MVT XLenVT = Subtarget.getXLenVT(); 2381 2382 // Simplest case is that the operand needs to be promoted to XLenVT. 2383 if (Scalar.getValueType().bitsLE(XLenVT)) { 2384 // If the operand is a constant, sign extend to increase our chances 2385 // of being able to use a .vi instruction. ANY_EXTEND would become a 2386 // a zero extend and the simm5 check in isel would fail. 2387 // FIXME: Should we ignore the upper bits in isel instead? 2388 unsigned ExtOpc = 2389 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2390 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2391 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2392 // If VL is 1 and the scalar value won't benefit from immediate, we could 2393 // use vmv.s.x. 2394 if (isOneConstant(VL) && 2395 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2396 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2397 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2398 } 2399 2400 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2401 "Unexpected scalar for splat lowering!"); 2402 2403 if (isOneConstant(VL) && isNullConstant(Scalar)) 2404 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2405 DAG.getConstant(0, DL, XLenVT), VL); 2406 2407 // Otherwise use the more complicated splatting algorithm. 2408 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2409 } 2410 2411 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2412 const RISCVSubtarget &Subtarget) { 2413 // We need to be able to widen elements to the next larger integer type. 2414 if (VT.getScalarSizeInBits() >= Subtarget.getELEN()) 2415 return false; 2416 2417 int Size = Mask.size(); 2418 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2419 2420 int Srcs[] = {-1, -1}; 2421 for (int i = 0; i != Size; ++i) { 2422 // Ignore undef elements. 2423 if (Mask[i] < 0) 2424 continue; 2425 2426 // Is this an even or odd element. 2427 int Pol = i % 2; 2428 2429 // Ensure we consistently use the same source for this element polarity. 2430 int Src = Mask[i] / Size; 2431 if (Srcs[Pol] < 0) 2432 Srcs[Pol] = Src; 2433 if (Srcs[Pol] != Src) 2434 return false; 2435 2436 // Make sure the element within the source is appropriate for this element 2437 // in the destination. 2438 int Elt = Mask[i] % Size; 2439 if (Elt != i / 2) 2440 return false; 2441 } 2442 2443 // We need to find a source for each polarity and they can't be the same. 2444 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2445 return false; 2446 2447 // Swap the sources if the second source was in the even polarity. 2448 SwapSources = Srcs[0] > Srcs[1]; 2449 2450 return true; 2451 } 2452 2453 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2454 /// and then extract the original number of elements from the rotated result. 2455 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2456 /// returned rotation amount is for a rotate right, where elements move from 2457 /// higher elements to lower elements. \p LoSrc indicates the first source 2458 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2459 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2460 /// 0 or 1 if a rotation is found. 2461 /// 2462 /// NOTE: We talk about rotate to the right which matches how bit shift and 2463 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2464 /// and the table below write vectors with the lowest elements on the left. 2465 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2466 int Size = Mask.size(); 2467 2468 // We need to detect various ways of spelling a rotation: 2469 // [11, 12, 13, 14, 15, 0, 1, 2] 2470 // [-1, 12, 13, 14, -1, -1, 1, -1] 2471 // [-1, -1, -1, -1, -1, -1, 1, 2] 2472 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2473 // [-1, 4, 5, 6, -1, -1, 9, -1] 2474 // [-1, 4, 5, 6, -1, -1, -1, -1] 2475 int Rotation = 0; 2476 LoSrc = -1; 2477 HiSrc = -1; 2478 for (int i = 0; i != Size; ++i) { 2479 int M = Mask[i]; 2480 if (M < 0) 2481 continue; 2482 2483 // Determine where a rotate vector would have started. 2484 int StartIdx = i - (M % Size); 2485 // The identity rotation isn't interesting, stop. 2486 if (StartIdx == 0) 2487 return -1; 2488 2489 // If we found the tail of a vector the rotation must be the missing 2490 // front. If we found the head of a vector, it must be how much of the 2491 // head. 2492 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2493 2494 if (Rotation == 0) 2495 Rotation = CandidateRotation; 2496 else if (Rotation != CandidateRotation) 2497 // The rotations don't match, so we can't match this mask. 2498 return -1; 2499 2500 // Compute which value this mask is pointing at. 2501 int MaskSrc = M < Size ? 0 : 1; 2502 2503 // Compute which of the two target values this index should be assigned to. 2504 // This reflects whether the high elements are remaining or the low elemnts 2505 // are remaining. 2506 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2507 2508 // Either set up this value if we've not encountered it before, or check 2509 // that it remains consistent. 2510 if (TargetSrc < 0) 2511 TargetSrc = MaskSrc; 2512 else if (TargetSrc != MaskSrc) 2513 // This may be a rotation, but it pulls from the inputs in some 2514 // unsupported interleaving. 2515 return -1; 2516 } 2517 2518 // Check that we successfully analyzed the mask, and normalize the results. 2519 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2520 assert((LoSrc >= 0 || HiSrc >= 0) && 2521 "Failed to find a rotated input vector!"); 2522 2523 return Rotation; 2524 } 2525 2526 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2527 const RISCVSubtarget &Subtarget) { 2528 SDValue V1 = Op.getOperand(0); 2529 SDValue V2 = Op.getOperand(1); 2530 SDLoc DL(Op); 2531 MVT XLenVT = Subtarget.getXLenVT(); 2532 MVT VT = Op.getSimpleValueType(); 2533 unsigned NumElts = VT.getVectorNumElements(); 2534 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2535 2536 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2537 2538 SDValue TrueMask, VL; 2539 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2540 2541 if (SVN->isSplat()) { 2542 const int Lane = SVN->getSplatIndex(); 2543 if (Lane >= 0) { 2544 MVT SVT = VT.getVectorElementType(); 2545 2546 // Turn splatted vector load into a strided load with an X0 stride. 2547 SDValue V = V1; 2548 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2549 // with undef. 2550 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2551 int Offset = Lane; 2552 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2553 int OpElements = 2554 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2555 V = V.getOperand(Offset / OpElements); 2556 Offset %= OpElements; 2557 } 2558 2559 // We need to ensure the load isn't atomic or volatile. 2560 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2561 auto *Ld = cast<LoadSDNode>(V); 2562 Offset *= SVT.getStoreSize(); 2563 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2564 TypeSize::Fixed(Offset), DL); 2565 2566 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2567 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2568 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2569 SDValue IntID = 2570 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2571 SDValue Ops[] = {Ld->getChain(), 2572 IntID, 2573 DAG.getUNDEF(ContainerVT), 2574 NewAddr, 2575 DAG.getRegister(RISCV::X0, XLenVT), 2576 VL}; 2577 SDValue NewLoad = DAG.getMemIntrinsicNode( 2578 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2579 DAG.getMachineFunction().getMachineMemOperand( 2580 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2581 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2582 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2583 } 2584 2585 // Otherwise use a scalar load and splat. This will give the best 2586 // opportunity to fold a splat into the operation. ISel can turn it into 2587 // the x0 strided load if we aren't able to fold away the select. 2588 if (SVT.isFloatingPoint()) 2589 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2590 Ld->getPointerInfo().getWithOffset(Offset), 2591 Ld->getOriginalAlign(), 2592 Ld->getMemOperand()->getFlags()); 2593 else 2594 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2595 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2596 Ld->getOriginalAlign(), 2597 Ld->getMemOperand()->getFlags()); 2598 DAG.makeEquivalentMemoryOrdering(Ld, V); 2599 2600 unsigned Opc = 2601 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2602 SDValue Splat = 2603 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2604 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2605 } 2606 2607 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2608 assert(Lane < (int)NumElts && "Unexpected lane!"); 2609 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, 2610 V1, DAG.getConstant(Lane, DL, XLenVT), 2611 TrueMask, DAG.getUNDEF(ContainerVT), VL); 2612 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2613 } 2614 } 2615 2616 ArrayRef<int> Mask = SVN->getMask(); 2617 2618 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2619 // be undef which can be handled with a single SLIDEDOWN/UP. 2620 int LoSrc, HiSrc; 2621 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2622 if (Rotation > 0) { 2623 SDValue LoV, HiV; 2624 if (LoSrc >= 0) { 2625 LoV = LoSrc == 0 ? V1 : V2; 2626 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2627 } 2628 if (HiSrc >= 0) { 2629 HiV = HiSrc == 0 ? V1 : V2; 2630 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2631 } 2632 2633 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2634 // to slide LoV up by (NumElts - Rotation). 2635 unsigned InvRotate = NumElts - Rotation; 2636 2637 SDValue Res = DAG.getUNDEF(ContainerVT); 2638 if (HiV) { 2639 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2640 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2641 // causes multiple vsetvlis in some test cases such as lowering 2642 // reduce.mul 2643 SDValue DownVL = VL; 2644 if (LoV) 2645 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2646 Res = 2647 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2648 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2649 } 2650 if (LoV) 2651 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2652 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2653 2654 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2655 } 2656 2657 // Detect an interleave shuffle and lower to 2658 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2659 bool SwapSources; 2660 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2661 // Swap sources if needed. 2662 if (SwapSources) 2663 std::swap(V1, V2); 2664 2665 // Extract the lower half of the vectors. 2666 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2667 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2668 DAG.getConstant(0, DL, XLenVT)); 2669 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2670 DAG.getConstant(0, DL, XLenVT)); 2671 2672 // Double the element width and halve the number of elements in an int type. 2673 unsigned EltBits = VT.getScalarSizeInBits(); 2674 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2675 MVT WideIntVT = 2676 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2677 // Convert this to a scalable vector. We need to base this on the 2678 // destination size to ensure there's always a type with a smaller LMUL. 2679 MVT WideIntContainerVT = 2680 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2681 2682 // Convert sources to scalable vectors with the same element count as the 2683 // larger type. 2684 MVT HalfContainerVT = MVT::getVectorVT( 2685 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2686 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2687 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2688 2689 // Cast sources to integer. 2690 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2691 MVT IntHalfVT = 2692 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2693 V1 = DAG.getBitcast(IntHalfVT, V1); 2694 V2 = DAG.getBitcast(IntHalfVT, V2); 2695 2696 // Freeze V2 since we use it twice and we need to be sure that the add and 2697 // multiply see the same value. 2698 V2 = DAG.getFreeze(V2); 2699 2700 // Recreate TrueMask using the widened type's element count. 2701 TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG); 2702 2703 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2704 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2705 V2, TrueMask, VL); 2706 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2707 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2708 DAG.getUNDEF(IntHalfVT), 2709 DAG.getAllOnesConstant(DL, XLenVT)); 2710 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2711 V2, Multiplier, TrueMask, VL); 2712 // Add the new copies to our previous addition giving us 2^eltbits copies of 2713 // V2. This is equivalent to shifting V2 left by eltbits. This should 2714 // combine with the vwmulu.vv above to form vwmaccu.vv. 2715 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2716 TrueMask, VL); 2717 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2718 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2719 // vector VT. 2720 ContainerVT = 2721 MVT::getVectorVT(VT.getVectorElementType(), 2722 WideIntContainerVT.getVectorElementCount() * 2); 2723 Add = DAG.getBitcast(ContainerVT, Add); 2724 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2725 } 2726 2727 // Detect shuffles which can be re-expressed as vector selects; these are 2728 // shuffles in which each element in the destination is taken from an element 2729 // at the corresponding index in either source vectors. 2730 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2731 int MaskIndex = MaskIdx.value(); 2732 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2733 }); 2734 2735 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2736 2737 SmallVector<SDValue> MaskVals; 2738 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2739 // merged with a second vrgather. 2740 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2741 2742 // By default we preserve the original operand order, and use a mask to 2743 // select LHS as true and RHS as false. However, since RVV vector selects may 2744 // feature splats but only on the LHS, we may choose to invert our mask and 2745 // instead select between RHS and LHS. 2746 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2747 bool InvertMask = IsSelect == SwapOps; 2748 2749 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2750 // half. 2751 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2752 2753 // Now construct the mask that will be used by the vselect or blended 2754 // vrgather operation. For vrgathers, construct the appropriate indices into 2755 // each vector. 2756 for (int MaskIndex : Mask) { 2757 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2758 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2759 if (!IsSelect) { 2760 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2761 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2762 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2763 : DAG.getUNDEF(XLenVT)); 2764 GatherIndicesRHS.push_back( 2765 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2766 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2767 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2768 ++LHSIndexCounts[MaskIndex]; 2769 if (!IsLHSOrUndefIndex) 2770 ++RHSIndexCounts[MaskIndex - NumElts]; 2771 } 2772 } 2773 2774 if (SwapOps) { 2775 std::swap(V1, V2); 2776 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2777 } 2778 2779 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2780 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2781 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2782 2783 if (IsSelect) 2784 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2785 2786 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2787 // On such a large vector we're unable to use i8 as the index type. 2788 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2789 // may involve vector splitting if we're already at LMUL=8, or our 2790 // user-supplied maximum fixed-length LMUL. 2791 return SDValue(); 2792 } 2793 2794 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2795 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2796 MVT IndexVT = VT.changeTypeToInteger(); 2797 // Since we can't introduce illegal index types at this stage, use i16 and 2798 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2799 // than XLenVT. 2800 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2801 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2802 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2803 } 2804 2805 MVT IndexContainerVT = 2806 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2807 2808 SDValue Gather; 2809 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2810 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2811 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2812 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2813 Subtarget); 2814 } else { 2815 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2816 // If only one index is used, we can use a "splat" vrgather. 2817 // TODO: We can splat the most-common index and fix-up any stragglers, if 2818 // that's beneficial. 2819 if (LHSIndexCounts.size() == 1) { 2820 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2821 Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2822 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, 2823 DAG.getUNDEF(ContainerVT), VL); 2824 } else { 2825 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2826 LHSIndices = 2827 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2828 2829 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2830 TrueMask, DAG.getUNDEF(ContainerVT), VL); 2831 } 2832 } 2833 2834 // If a second vector operand is used by this shuffle, blend it in with an 2835 // additional vrgather. 2836 if (!V2.isUndef()) { 2837 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2838 2839 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2840 SelectMask = 2841 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2842 2843 // If only one index is used, we can use a "splat" vrgather. 2844 // TODO: We can splat the most-common index and fix-up any stragglers, if 2845 // that's beneficial. 2846 if (RHSIndexCounts.size() == 1) { 2847 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2848 Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2849 DAG.getConstant(SplatIndex, DL, XLenVT), SelectMask, 2850 Gather, VL); 2851 } else { 2852 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2853 RHSIndices = 2854 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2855 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, 2856 SelectMask, Gather, VL); 2857 } 2858 } 2859 2860 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2861 } 2862 2863 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2864 // Support splats for any type. These should type legalize well. 2865 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2866 return true; 2867 2868 // Only support legal VTs for other shuffles for now. 2869 if (!isTypeLegal(VT)) 2870 return false; 2871 2872 MVT SVT = VT.getSimpleVT(); 2873 2874 bool SwapSources; 2875 int LoSrc, HiSrc; 2876 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2877 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2878 } 2879 2880 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2881 // the exponent. 2882 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2883 MVT VT = Op.getSimpleValueType(); 2884 unsigned EltSize = VT.getScalarSizeInBits(); 2885 SDValue Src = Op.getOperand(0); 2886 SDLoc DL(Op); 2887 2888 // We need a FP type that can represent the value. 2889 // TODO: Use f16 for i8 when possible? 2890 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2891 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2892 2893 // Legal types should have been checked in the RISCVTargetLowering 2894 // constructor. 2895 // TODO: Splitting may make sense in some cases. 2896 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2897 "Expected legal float type!"); 2898 2899 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2900 // The trailing zero count is equal to log2 of this single bit value. 2901 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2902 SDValue Neg = 2903 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2904 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2905 } 2906 2907 // We have a legal FP type, convert to it. 2908 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2909 // Bitcast to integer and shift the exponent to the LSB. 2910 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2911 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2912 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2913 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2914 DAG.getConstant(ShiftAmt, DL, IntVT)); 2915 // Truncate back to original type to allow vnsrl. 2916 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2917 // The exponent contains log2 of the value in biased form. 2918 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2919 2920 // For trailing zeros, we just need to subtract the bias. 2921 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2922 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2923 DAG.getConstant(ExponentBias, DL, VT)); 2924 2925 // For leading zeros, we need to remove the bias and convert from log2 to 2926 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2927 unsigned Adjust = ExponentBias + (EltSize - 1); 2928 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2929 } 2930 2931 // While RVV has alignment restrictions, we should always be able to load as a 2932 // legal equivalently-sized byte-typed vector instead. This method is 2933 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2934 // the load is already correctly-aligned, it returns SDValue(). 2935 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2936 SelectionDAG &DAG) const { 2937 auto *Load = cast<LoadSDNode>(Op); 2938 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2939 2940 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2941 Load->getMemoryVT(), 2942 *Load->getMemOperand())) 2943 return SDValue(); 2944 2945 SDLoc DL(Op); 2946 MVT VT = Op.getSimpleValueType(); 2947 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2948 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2949 "Unexpected unaligned RVV load type"); 2950 MVT NewVT = 2951 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2952 assert(NewVT.isValid() && 2953 "Expecting equally-sized RVV vector types to be legal"); 2954 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2955 Load->getPointerInfo(), Load->getOriginalAlign(), 2956 Load->getMemOperand()->getFlags()); 2957 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2958 } 2959 2960 // While RVV has alignment restrictions, we should always be able to store as a 2961 // legal equivalently-sized byte-typed vector instead. This method is 2962 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2963 // returns SDValue() if the store is already correctly aligned. 2964 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2965 SelectionDAG &DAG) const { 2966 auto *Store = cast<StoreSDNode>(Op); 2967 assert(Store && Store->getValue().getValueType().isVector() && 2968 "Expected vector store"); 2969 2970 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2971 Store->getMemoryVT(), 2972 *Store->getMemOperand())) 2973 return SDValue(); 2974 2975 SDLoc DL(Op); 2976 SDValue StoredVal = Store->getValue(); 2977 MVT VT = StoredVal.getSimpleValueType(); 2978 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2979 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2980 "Unexpected unaligned RVV store type"); 2981 MVT NewVT = 2982 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2983 assert(NewVT.isValid() && 2984 "Expecting equally-sized RVV vector types to be legal"); 2985 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2986 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2987 Store->getPointerInfo(), Store->getOriginalAlign(), 2988 Store->getMemOperand()->getFlags()); 2989 } 2990 2991 static SDValue lowerConstant(SDValue Op, SelectionDAG &DAG, 2992 const RISCVSubtarget &Subtarget) { 2993 assert(Op.getValueType() == MVT::i64 && "Unexpected VT"); 2994 2995 int64_t Imm = cast<ConstantSDNode>(Op)->getSExtValue(); 2996 2997 // All simm32 constants should be handled by isel. 2998 // NOTE: The getMaxBuildIntsCost call below should return a value >= 2 making 2999 // this check redundant, but small immediates are common so this check 3000 // should have better compile time. 3001 if (isInt<32>(Imm)) 3002 return Op; 3003 3004 // We only need to cost the immediate, if constant pool lowering is enabled. 3005 if (!Subtarget.useConstantPoolForLargeInts()) 3006 return Op; 3007 3008 RISCVMatInt::InstSeq Seq = 3009 RISCVMatInt::generateInstSeq(Imm, Subtarget.getFeatureBits()); 3010 if (Seq.size() <= Subtarget.getMaxBuildIntsCost()) 3011 return Op; 3012 3013 // Expand to a constant pool using the default expansion code. 3014 return SDValue(); 3015 } 3016 3017 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 3018 SelectionDAG &DAG) const { 3019 switch (Op.getOpcode()) { 3020 default: 3021 report_fatal_error("unimplemented operand"); 3022 case ISD::GlobalAddress: 3023 return lowerGlobalAddress(Op, DAG); 3024 case ISD::BlockAddress: 3025 return lowerBlockAddress(Op, DAG); 3026 case ISD::ConstantPool: 3027 return lowerConstantPool(Op, DAG); 3028 case ISD::JumpTable: 3029 return lowerJumpTable(Op, DAG); 3030 case ISD::GlobalTLSAddress: 3031 return lowerGlobalTLSAddress(Op, DAG); 3032 case ISD::Constant: 3033 return lowerConstant(Op, DAG, Subtarget); 3034 case ISD::SELECT: 3035 return lowerSELECT(Op, DAG); 3036 case ISD::BRCOND: 3037 return lowerBRCOND(Op, DAG); 3038 case ISD::VASTART: 3039 return lowerVASTART(Op, DAG); 3040 case ISD::FRAMEADDR: 3041 return lowerFRAMEADDR(Op, DAG); 3042 case ISD::RETURNADDR: 3043 return lowerRETURNADDR(Op, DAG); 3044 case ISD::SHL_PARTS: 3045 return lowerShiftLeftParts(Op, DAG); 3046 case ISD::SRA_PARTS: 3047 return lowerShiftRightParts(Op, DAG, true); 3048 case ISD::SRL_PARTS: 3049 return lowerShiftRightParts(Op, DAG, false); 3050 case ISD::BITCAST: { 3051 SDLoc DL(Op); 3052 EVT VT = Op.getValueType(); 3053 SDValue Op0 = Op.getOperand(0); 3054 EVT Op0VT = Op0.getValueType(); 3055 MVT XLenVT = Subtarget.getXLenVT(); 3056 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 3057 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 3058 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 3059 return FPConv; 3060 } 3061 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 3062 Subtarget.hasStdExtF()) { 3063 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3064 SDValue FPConv = 3065 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3066 return FPConv; 3067 } 3068 3069 // Consider other scalar<->scalar casts as legal if the types are legal. 3070 // Otherwise expand them. 3071 if (!VT.isVector() && !Op0VT.isVector()) { 3072 if (isTypeLegal(VT) && isTypeLegal(Op0VT)) 3073 return Op; 3074 return SDValue(); 3075 } 3076 3077 assert(!VT.isScalableVector() && !Op0VT.isScalableVector() && 3078 "Unexpected types"); 3079 3080 if (VT.isFixedLengthVector()) { 3081 // We can handle fixed length vector bitcasts with a simple replacement 3082 // in isel. 3083 if (Op0VT.isFixedLengthVector()) 3084 return Op; 3085 // When bitcasting from scalar to fixed-length vector, insert the scalar 3086 // into a one-element vector of the result type, and perform a vector 3087 // bitcast. 3088 if (!Op0VT.isVector()) { 3089 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 3090 if (!isTypeLegal(BVT)) 3091 return SDValue(); 3092 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 3093 DAG.getUNDEF(BVT), Op0, 3094 DAG.getConstant(0, DL, XLenVT))); 3095 } 3096 return SDValue(); 3097 } 3098 // Custom-legalize bitcasts from fixed-length vector types to scalar types 3099 // thus: bitcast the vector to a one-element vector type whose element type 3100 // is the same as the result type, and extract the first element. 3101 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 3102 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 3103 if (!isTypeLegal(BVT)) 3104 return SDValue(); 3105 SDValue BVec = DAG.getBitcast(BVT, Op0); 3106 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 3107 DAG.getConstant(0, DL, XLenVT)); 3108 } 3109 return SDValue(); 3110 } 3111 case ISD::INTRINSIC_WO_CHAIN: 3112 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3113 case ISD::INTRINSIC_W_CHAIN: 3114 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3115 case ISD::INTRINSIC_VOID: 3116 return LowerINTRINSIC_VOID(Op, DAG); 3117 case ISD::BSWAP: 3118 case ISD::BITREVERSE: { 3119 MVT VT = Op.getSimpleValueType(); 3120 SDLoc DL(Op); 3121 if (Subtarget.hasStdExtZbp()) { 3122 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3123 // Start with the maximum immediate value which is the bitwidth - 1. 3124 unsigned Imm = VT.getSizeInBits() - 1; 3125 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3126 if (Op.getOpcode() == ISD::BSWAP) 3127 Imm &= ~0x7U; 3128 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3129 DAG.getConstant(Imm, DL, VT)); 3130 } 3131 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3132 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3133 // Expand bitreverse to a bswap(rev8) followed by brev8. 3134 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3135 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3136 // as brev8 by an isel pattern. 3137 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3138 DAG.getConstant(7, DL, VT)); 3139 } 3140 case ISD::FSHL: 3141 case ISD::FSHR: { 3142 MVT VT = Op.getSimpleValueType(); 3143 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3144 SDLoc DL(Op); 3145 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3146 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3147 // accidentally setting the extra bit. 3148 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3149 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3150 DAG.getConstant(ShAmtWidth, DL, VT)); 3151 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3152 // instruction use different orders. fshl will return its first operand for 3153 // shift of zero, fshr will return its second operand. fsl and fsr both 3154 // return rs1 so the ISD nodes need to have different operand orders. 3155 // Shift amount is in rs2. 3156 SDValue Op0 = Op.getOperand(0); 3157 SDValue Op1 = Op.getOperand(1); 3158 unsigned Opc = RISCVISD::FSL; 3159 if (Op.getOpcode() == ISD::FSHR) { 3160 std::swap(Op0, Op1); 3161 Opc = RISCVISD::FSR; 3162 } 3163 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3164 } 3165 case ISD::TRUNCATE: 3166 // Only custom-lower vector truncates 3167 if (!Op.getSimpleValueType().isVector()) 3168 return Op; 3169 return lowerVectorTruncLike(Op, DAG); 3170 case ISD::ANY_EXTEND: 3171 case ISD::ZERO_EXTEND: 3172 if (Op.getOperand(0).getValueType().isVector() && 3173 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3174 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3175 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3176 case ISD::SIGN_EXTEND: 3177 if (Op.getOperand(0).getValueType().isVector() && 3178 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3179 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3180 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3181 case ISD::SPLAT_VECTOR_PARTS: 3182 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3183 case ISD::INSERT_VECTOR_ELT: 3184 return lowerINSERT_VECTOR_ELT(Op, DAG); 3185 case ISD::EXTRACT_VECTOR_ELT: 3186 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3187 case ISD::VSCALE: { 3188 MVT VT = Op.getSimpleValueType(); 3189 SDLoc DL(Op); 3190 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3191 // We define our scalable vector types for lmul=1 to use a 64 bit known 3192 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3193 // vscale as VLENB / 8. 3194 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3195 if (Subtarget.getRealMinVLen() < RISCV::RVVBitsPerBlock) 3196 report_fatal_error("Support for VLEN==32 is incomplete."); 3197 // We assume VLENB is a multiple of 8. We manually choose the best shift 3198 // here because SimplifyDemandedBits isn't always able to simplify it. 3199 uint64_t Val = Op.getConstantOperandVal(0); 3200 if (isPowerOf2_64(Val)) { 3201 uint64_t Log2 = Log2_64(Val); 3202 if (Log2 < 3) 3203 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3204 DAG.getConstant(3 - Log2, DL, VT)); 3205 if (Log2 > 3) 3206 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3207 DAG.getConstant(Log2 - 3, DL, VT)); 3208 return VLENB; 3209 } 3210 // If the multiplier is a multiple of 8, scale it down to avoid needing 3211 // to shift the VLENB value. 3212 if ((Val % 8) == 0) 3213 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3214 DAG.getConstant(Val / 8, DL, VT)); 3215 3216 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3217 DAG.getConstant(3, DL, VT)); 3218 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3219 } 3220 case ISD::FPOWI: { 3221 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3222 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3223 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3224 Op.getOperand(1).getValueType() == MVT::i32) { 3225 SDLoc DL(Op); 3226 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3227 SDValue Powi = 3228 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3229 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3230 DAG.getIntPtrConstant(0, DL)); 3231 } 3232 return SDValue(); 3233 } 3234 case ISD::FP_EXTEND: 3235 case ISD::FP_ROUND: 3236 if (!Op.getValueType().isVector()) 3237 return Op; 3238 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3239 case ISD::FP_TO_SINT: 3240 case ISD::FP_TO_UINT: 3241 case ISD::SINT_TO_FP: 3242 case ISD::UINT_TO_FP: { 3243 // RVV can only do fp<->int conversions to types half/double the size as 3244 // the source. We custom-lower any conversions that do two hops into 3245 // sequences. 3246 MVT VT = Op.getSimpleValueType(); 3247 if (!VT.isVector()) 3248 return Op; 3249 SDLoc DL(Op); 3250 SDValue Src = Op.getOperand(0); 3251 MVT EltVT = VT.getVectorElementType(); 3252 MVT SrcVT = Src.getSimpleValueType(); 3253 MVT SrcEltVT = SrcVT.getVectorElementType(); 3254 unsigned EltSize = EltVT.getSizeInBits(); 3255 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3256 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3257 "Unexpected vector element types"); 3258 3259 bool IsInt2FP = SrcEltVT.isInteger(); 3260 // Widening conversions 3261 if (EltSize > (2 * SrcEltSize)) { 3262 if (IsInt2FP) { 3263 // Do a regular integer sign/zero extension then convert to float. 3264 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), 3265 VT.getVectorElementCount()); 3266 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3267 ? ISD::ZERO_EXTEND 3268 : ISD::SIGN_EXTEND; 3269 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3270 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3271 } 3272 // FP2Int 3273 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3274 // Do one doubling fp_extend then complete the operation by converting 3275 // to int. 3276 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3277 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3278 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3279 } 3280 3281 // Narrowing conversions 3282 if (SrcEltSize > (2 * EltSize)) { 3283 if (IsInt2FP) { 3284 // One narrowing int_to_fp, then an fp_round. 3285 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3286 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3287 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3288 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3289 } 3290 // FP2Int 3291 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3292 // representable by the integer, the result is poison. 3293 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 3294 VT.getVectorElementCount()); 3295 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3296 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3297 } 3298 3299 // Scalable vectors can exit here. Patterns will handle equally-sized 3300 // conversions halving/doubling ones. 3301 if (!VT.isFixedLengthVector()) 3302 return Op; 3303 3304 // For fixed-length vectors we lower to a custom "VL" node. 3305 unsigned RVVOpc = 0; 3306 switch (Op.getOpcode()) { 3307 default: 3308 llvm_unreachable("Impossible opcode"); 3309 case ISD::FP_TO_SINT: 3310 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3311 break; 3312 case ISD::FP_TO_UINT: 3313 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3314 break; 3315 case ISD::SINT_TO_FP: 3316 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3317 break; 3318 case ISD::UINT_TO_FP: 3319 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3320 break; 3321 } 3322 3323 MVT ContainerVT, SrcContainerVT; 3324 // Derive the reference container type from the larger vector type. 3325 if (SrcEltSize > EltSize) { 3326 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3327 ContainerVT = 3328 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3329 } else { 3330 ContainerVT = getContainerForFixedLengthVector(VT); 3331 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3332 } 3333 3334 SDValue Mask, VL; 3335 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3336 3337 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3338 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3339 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3340 } 3341 case ISD::FP_TO_SINT_SAT: 3342 case ISD::FP_TO_UINT_SAT: 3343 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3344 case ISD::FTRUNC: 3345 case ISD::FCEIL: 3346 case ISD::FFLOOR: 3347 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3348 case ISD::FROUND: 3349 return lowerFROUND(Op, DAG); 3350 case ISD::VECREDUCE_ADD: 3351 case ISD::VECREDUCE_UMAX: 3352 case ISD::VECREDUCE_SMAX: 3353 case ISD::VECREDUCE_UMIN: 3354 case ISD::VECREDUCE_SMIN: 3355 return lowerVECREDUCE(Op, DAG); 3356 case ISD::VECREDUCE_AND: 3357 case ISD::VECREDUCE_OR: 3358 case ISD::VECREDUCE_XOR: 3359 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3360 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3361 return lowerVECREDUCE(Op, DAG); 3362 case ISD::VECREDUCE_FADD: 3363 case ISD::VECREDUCE_SEQ_FADD: 3364 case ISD::VECREDUCE_FMIN: 3365 case ISD::VECREDUCE_FMAX: 3366 return lowerFPVECREDUCE(Op, DAG); 3367 case ISD::VP_REDUCE_ADD: 3368 case ISD::VP_REDUCE_UMAX: 3369 case ISD::VP_REDUCE_SMAX: 3370 case ISD::VP_REDUCE_UMIN: 3371 case ISD::VP_REDUCE_SMIN: 3372 case ISD::VP_REDUCE_FADD: 3373 case ISD::VP_REDUCE_SEQ_FADD: 3374 case ISD::VP_REDUCE_FMIN: 3375 case ISD::VP_REDUCE_FMAX: 3376 return lowerVPREDUCE(Op, DAG); 3377 case ISD::VP_REDUCE_AND: 3378 case ISD::VP_REDUCE_OR: 3379 case ISD::VP_REDUCE_XOR: 3380 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3381 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3382 return lowerVPREDUCE(Op, DAG); 3383 case ISD::INSERT_SUBVECTOR: 3384 return lowerINSERT_SUBVECTOR(Op, DAG); 3385 case ISD::EXTRACT_SUBVECTOR: 3386 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3387 case ISD::STEP_VECTOR: 3388 return lowerSTEP_VECTOR(Op, DAG); 3389 case ISD::VECTOR_REVERSE: 3390 return lowerVECTOR_REVERSE(Op, DAG); 3391 case ISD::VECTOR_SPLICE: 3392 return lowerVECTOR_SPLICE(Op, DAG); 3393 case ISD::BUILD_VECTOR: 3394 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3395 case ISD::SPLAT_VECTOR: 3396 if (Op.getValueType().getVectorElementType() == MVT::i1) 3397 return lowerVectorMaskSplat(Op, DAG); 3398 return SDValue(); 3399 case ISD::VECTOR_SHUFFLE: 3400 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3401 case ISD::CONCAT_VECTORS: { 3402 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3403 // better than going through the stack, as the default expansion does. 3404 SDLoc DL(Op); 3405 MVT VT = Op.getSimpleValueType(); 3406 unsigned NumOpElts = 3407 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3408 SDValue Vec = DAG.getUNDEF(VT); 3409 for (const auto &OpIdx : enumerate(Op->ops())) { 3410 SDValue SubVec = OpIdx.value(); 3411 // Don't insert undef subvectors. 3412 if (SubVec.isUndef()) 3413 continue; 3414 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3415 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3416 } 3417 return Vec; 3418 } 3419 case ISD::LOAD: 3420 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3421 return V; 3422 if (Op.getValueType().isFixedLengthVector()) 3423 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3424 return Op; 3425 case ISD::STORE: 3426 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3427 return V; 3428 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3429 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3430 return Op; 3431 case ISD::MLOAD: 3432 case ISD::VP_LOAD: 3433 return lowerMaskedLoad(Op, DAG); 3434 case ISD::MSTORE: 3435 case ISD::VP_STORE: 3436 return lowerMaskedStore(Op, DAG); 3437 case ISD::SETCC: 3438 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3439 case ISD::ADD: 3440 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3441 case ISD::SUB: 3442 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3443 case ISD::MUL: 3444 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3445 case ISD::MULHS: 3446 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3447 case ISD::MULHU: 3448 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3449 case ISD::AND: 3450 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3451 RISCVISD::AND_VL); 3452 case ISD::OR: 3453 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3454 RISCVISD::OR_VL); 3455 case ISD::XOR: 3456 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3457 RISCVISD::XOR_VL); 3458 case ISD::SDIV: 3459 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3460 case ISD::SREM: 3461 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3462 case ISD::UDIV: 3463 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3464 case ISD::UREM: 3465 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3466 case ISD::SHL: 3467 case ISD::SRA: 3468 case ISD::SRL: 3469 if (Op.getSimpleValueType().isFixedLengthVector()) 3470 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3471 // This can be called for an i32 shift amount that needs to be promoted. 3472 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3473 "Unexpected custom legalisation"); 3474 return SDValue(); 3475 case ISD::SADDSAT: 3476 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3477 case ISD::UADDSAT: 3478 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3479 case ISD::SSUBSAT: 3480 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3481 case ISD::USUBSAT: 3482 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3483 case ISD::FADD: 3484 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3485 case ISD::FSUB: 3486 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3487 case ISD::FMUL: 3488 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3489 case ISD::FDIV: 3490 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3491 case ISD::FNEG: 3492 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3493 case ISD::FABS: 3494 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3495 case ISD::FSQRT: 3496 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3497 case ISD::FMA: 3498 return lowerToScalableOp(Op, DAG, RISCVISD::VFMADD_VL); 3499 case ISD::SMIN: 3500 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3501 case ISD::SMAX: 3502 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3503 case ISD::UMIN: 3504 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3505 case ISD::UMAX: 3506 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3507 case ISD::FMINNUM: 3508 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3509 case ISD::FMAXNUM: 3510 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3511 case ISD::ABS: 3512 return lowerABS(Op, DAG); 3513 case ISD::CTLZ_ZERO_UNDEF: 3514 case ISD::CTTZ_ZERO_UNDEF: 3515 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3516 case ISD::VSELECT: 3517 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3518 case ISD::FCOPYSIGN: 3519 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3520 case ISD::MGATHER: 3521 case ISD::VP_GATHER: 3522 return lowerMaskedGather(Op, DAG); 3523 case ISD::MSCATTER: 3524 case ISD::VP_SCATTER: 3525 return lowerMaskedScatter(Op, DAG); 3526 case ISD::FLT_ROUNDS_: 3527 return lowerGET_ROUNDING(Op, DAG); 3528 case ISD::SET_ROUNDING: 3529 return lowerSET_ROUNDING(Op, DAG); 3530 case ISD::EH_DWARF_CFA: 3531 return lowerEH_DWARF_CFA(Op, DAG); 3532 case ISD::VP_SELECT: 3533 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3534 case ISD::VP_MERGE: 3535 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3536 case ISD::VP_ADD: 3537 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3538 case ISD::VP_SUB: 3539 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3540 case ISD::VP_MUL: 3541 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3542 case ISD::VP_SDIV: 3543 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3544 case ISD::VP_UDIV: 3545 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3546 case ISD::VP_SREM: 3547 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3548 case ISD::VP_UREM: 3549 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3550 case ISD::VP_AND: 3551 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3552 case ISD::VP_OR: 3553 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3554 case ISD::VP_XOR: 3555 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3556 case ISD::VP_ASHR: 3557 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3558 case ISD::VP_LSHR: 3559 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3560 case ISD::VP_SHL: 3561 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3562 case ISD::VP_FADD: 3563 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3564 case ISD::VP_FSUB: 3565 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3566 case ISD::VP_FMUL: 3567 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3568 case ISD::VP_FDIV: 3569 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3570 case ISD::VP_FNEG: 3571 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3572 case ISD::VP_FMA: 3573 return lowerVPOp(Op, DAG, RISCVISD::VFMADD_VL); 3574 case ISD::VP_SIGN_EXTEND: 3575 case ISD::VP_ZERO_EXTEND: 3576 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3577 return lowerVPExtMaskOp(Op, DAG); 3578 return lowerVPOp(Op, DAG, 3579 Op.getOpcode() == ISD::VP_SIGN_EXTEND 3580 ? RISCVISD::VSEXT_VL 3581 : RISCVISD::VZEXT_VL); 3582 case ISD::VP_TRUNCATE: 3583 return lowerVectorTruncLike(Op, DAG); 3584 case ISD::VP_FP_EXTEND: 3585 case ISD::VP_FP_ROUND: 3586 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3587 case ISD::VP_FPTOSI: 3588 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL); 3589 case ISD::VP_FPTOUI: 3590 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL); 3591 case ISD::VP_SITOFP: 3592 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL); 3593 case ISD::VP_UITOFP: 3594 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL); 3595 case ISD::VP_SETCC: 3596 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3597 return lowerVPSetCCMaskOp(Op, DAG); 3598 return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL); 3599 } 3600 } 3601 3602 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3603 SelectionDAG &DAG, unsigned Flags) { 3604 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3605 } 3606 3607 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3608 SelectionDAG &DAG, unsigned Flags) { 3609 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3610 Flags); 3611 } 3612 3613 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3614 SelectionDAG &DAG, unsigned Flags) { 3615 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3616 N->getOffset(), Flags); 3617 } 3618 3619 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3620 SelectionDAG &DAG, unsigned Flags) { 3621 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3622 } 3623 3624 template <class NodeTy> 3625 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3626 bool IsLocal) const { 3627 SDLoc DL(N); 3628 EVT Ty = getPointerTy(DAG.getDataLayout()); 3629 3630 if (isPositionIndependent()) { 3631 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3632 if (IsLocal) 3633 // Use PC-relative addressing to access the symbol. This generates the 3634 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3635 // %pcrel_lo(auipc)). 3636 return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr); 3637 3638 // Use PC-relative addressing to access the GOT for this symbol, then load 3639 // the address from the GOT. This generates the pattern (PseudoLA sym), 3640 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3641 MachineFunction &MF = DAG.getMachineFunction(); 3642 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3643 MachinePointerInfo::getGOT(MF), 3644 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3645 MachineMemOperand::MOInvariant, 3646 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3647 SDValue Load = 3648 DAG.getMemIntrinsicNode(RISCVISD::LA, DL, DAG.getVTList(Ty, MVT::Other), 3649 {DAG.getEntryNode(), Addr}, Ty, MemOp); 3650 return Load; 3651 } 3652 3653 switch (getTargetMachine().getCodeModel()) { 3654 default: 3655 report_fatal_error("Unsupported code model for lowering"); 3656 case CodeModel::Small: { 3657 // Generate a sequence for accessing addresses within the first 2 GiB of 3658 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3659 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3660 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3661 SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi); 3662 return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNHi, AddrLo); 3663 } 3664 case CodeModel::Medium: { 3665 // Generate a sequence for accessing addresses within any 2GiB range within 3666 // the address space. This generates the pattern (PseudoLLA sym), which 3667 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3668 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3669 return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr); 3670 } 3671 } 3672 } 3673 3674 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3675 SelectionDAG &DAG) const { 3676 SDLoc DL(Op); 3677 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3678 assert(N->getOffset() == 0 && "unexpected offset in global node"); 3679 3680 const GlobalValue *GV = N->getGlobal(); 3681 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3682 return getAddr(N, DAG, IsLocal); 3683 } 3684 3685 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3686 SelectionDAG &DAG) const { 3687 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3688 3689 return getAddr(N, DAG); 3690 } 3691 3692 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3693 SelectionDAG &DAG) const { 3694 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3695 3696 return getAddr(N, DAG); 3697 } 3698 3699 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3700 SelectionDAG &DAG) const { 3701 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3702 3703 return getAddr(N, DAG); 3704 } 3705 3706 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3707 SelectionDAG &DAG, 3708 bool UseGOT) const { 3709 SDLoc DL(N); 3710 EVT Ty = getPointerTy(DAG.getDataLayout()); 3711 const GlobalValue *GV = N->getGlobal(); 3712 MVT XLenVT = Subtarget.getXLenVT(); 3713 3714 if (UseGOT) { 3715 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3716 // load the address from the GOT and add the thread pointer. This generates 3717 // the pattern (PseudoLA_TLS_IE sym), which expands to 3718 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3719 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3720 MachineFunction &MF = DAG.getMachineFunction(); 3721 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3722 MachinePointerInfo::getGOT(MF), 3723 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3724 MachineMemOperand::MOInvariant, 3725 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3726 SDValue Load = DAG.getMemIntrinsicNode( 3727 RISCVISD::LA_TLS_IE, DL, DAG.getVTList(Ty, MVT::Other), 3728 {DAG.getEntryNode(), Addr}, Ty, MemOp); 3729 3730 // Add the thread pointer. 3731 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3732 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3733 } 3734 3735 // Generate a sequence for accessing the address relative to the thread 3736 // pointer, with the appropriate adjustment for the thread pointer offset. 3737 // This generates the pattern 3738 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3739 SDValue AddrHi = 3740 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3741 SDValue AddrAdd = 3742 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3743 SDValue AddrLo = 3744 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3745 3746 SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi); 3747 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3748 SDValue MNAdd = 3749 DAG.getNode(RISCVISD::ADD_TPREL, DL, Ty, MNHi, TPReg, AddrAdd); 3750 return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNAdd, AddrLo); 3751 } 3752 3753 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3754 SelectionDAG &DAG) const { 3755 SDLoc DL(N); 3756 EVT Ty = getPointerTy(DAG.getDataLayout()); 3757 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3758 const GlobalValue *GV = N->getGlobal(); 3759 3760 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3761 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3762 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3763 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3764 SDValue Load = DAG.getNode(RISCVISD::LA_TLS_GD, DL, Ty, Addr); 3765 3766 // Prepare argument list to generate call. 3767 ArgListTy Args; 3768 ArgListEntry Entry; 3769 Entry.Node = Load; 3770 Entry.Ty = CallTy; 3771 Args.push_back(Entry); 3772 3773 // Setup call to __tls_get_addr. 3774 TargetLowering::CallLoweringInfo CLI(DAG); 3775 CLI.setDebugLoc(DL) 3776 .setChain(DAG.getEntryNode()) 3777 .setLibCallee(CallingConv::C, CallTy, 3778 DAG.getExternalSymbol("__tls_get_addr", Ty), 3779 std::move(Args)); 3780 3781 return LowerCallTo(CLI).first; 3782 } 3783 3784 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3785 SelectionDAG &DAG) const { 3786 SDLoc DL(Op); 3787 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3788 assert(N->getOffset() == 0 && "unexpected offset in global node"); 3789 3790 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3791 3792 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3793 CallingConv::GHC) 3794 report_fatal_error("In GHC calling convention TLS is not supported"); 3795 3796 SDValue Addr; 3797 switch (Model) { 3798 case TLSModel::LocalExec: 3799 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3800 break; 3801 case TLSModel::InitialExec: 3802 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3803 break; 3804 case TLSModel::LocalDynamic: 3805 case TLSModel::GeneralDynamic: 3806 Addr = getDynamicTLSAddr(N, DAG); 3807 break; 3808 } 3809 3810 return Addr; 3811 } 3812 3813 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3814 SDValue CondV = Op.getOperand(0); 3815 SDValue TrueV = Op.getOperand(1); 3816 SDValue FalseV = Op.getOperand(2); 3817 SDLoc DL(Op); 3818 MVT VT = Op.getSimpleValueType(); 3819 MVT XLenVT = Subtarget.getXLenVT(); 3820 3821 // Lower vector SELECTs to VSELECTs by splatting the condition. 3822 if (VT.isVector()) { 3823 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3824 SDValue CondSplat = VT.isScalableVector() 3825 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3826 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3827 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3828 } 3829 3830 // If the result type is XLenVT and CondV is the output of a SETCC node 3831 // which also operated on XLenVT inputs, then merge the SETCC node into the 3832 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3833 // compare+branch instructions. i.e.: 3834 // (select (setcc lhs, rhs, cc), truev, falsev) 3835 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3836 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3837 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3838 SDValue LHS = CondV.getOperand(0); 3839 SDValue RHS = CondV.getOperand(1); 3840 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3841 ISD::CondCode CCVal = CC->get(); 3842 3843 // Special case for a select of 2 constants that have a diffence of 1. 3844 // Normally this is done by DAGCombine, but if the select is introduced by 3845 // type legalization or op legalization, we miss it. Restricting to SETLT 3846 // case for now because that is what signed saturating add/sub need. 3847 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3848 // but we would probably want to swap the true/false values if the condition 3849 // is SETGE/SETLE to avoid an XORI. 3850 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3851 CCVal == ISD::SETLT) { 3852 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3853 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3854 if (TrueVal - 1 == FalseVal) 3855 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3856 if (TrueVal + 1 == FalseVal) 3857 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3858 } 3859 3860 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3861 3862 SDValue TargetCC = DAG.getCondCode(CCVal); 3863 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3864 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3865 } 3866 3867 // Otherwise: 3868 // (select condv, truev, falsev) 3869 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3870 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3871 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3872 3873 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3874 3875 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3876 } 3877 3878 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3879 SDValue CondV = Op.getOperand(1); 3880 SDLoc DL(Op); 3881 MVT XLenVT = Subtarget.getXLenVT(); 3882 3883 if (CondV.getOpcode() == ISD::SETCC && 3884 CondV.getOperand(0).getValueType() == XLenVT) { 3885 SDValue LHS = CondV.getOperand(0); 3886 SDValue RHS = CondV.getOperand(1); 3887 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3888 3889 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3890 3891 SDValue TargetCC = DAG.getCondCode(CCVal); 3892 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3893 LHS, RHS, TargetCC, Op.getOperand(2)); 3894 } 3895 3896 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3897 CondV, DAG.getConstant(0, DL, XLenVT), 3898 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3899 } 3900 3901 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3902 MachineFunction &MF = DAG.getMachineFunction(); 3903 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3904 3905 SDLoc DL(Op); 3906 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3907 getPointerTy(MF.getDataLayout())); 3908 3909 // vastart just stores the address of the VarArgsFrameIndex slot into the 3910 // memory location argument. 3911 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3912 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3913 MachinePointerInfo(SV)); 3914 } 3915 3916 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3917 SelectionDAG &DAG) const { 3918 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3919 MachineFunction &MF = DAG.getMachineFunction(); 3920 MachineFrameInfo &MFI = MF.getFrameInfo(); 3921 MFI.setFrameAddressIsTaken(true); 3922 Register FrameReg = RI.getFrameRegister(MF); 3923 int XLenInBytes = Subtarget.getXLen() / 8; 3924 3925 EVT VT = Op.getValueType(); 3926 SDLoc DL(Op); 3927 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3928 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3929 while (Depth--) { 3930 int Offset = -(XLenInBytes * 2); 3931 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3932 DAG.getIntPtrConstant(Offset, DL)); 3933 FrameAddr = 3934 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3935 } 3936 return FrameAddr; 3937 } 3938 3939 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3940 SelectionDAG &DAG) const { 3941 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3942 MachineFunction &MF = DAG.getMachineFunction(); 3943 MachineFrameInfo &MFI = MF.getFrameInfo(); 3944 MFI.setReturnAddressIsTaken(true); 3945 MVT XLenVT = Subtarget.getXLenVT(); 3946 int XLenInBytes = Subtarget.getXLen() / 8; 3947 3948 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3949 return SDValue(); 3950 3951 EVT VT = Op.getValueType(); 3952 SDLoc DL(Op); 3953 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3954 if (Depth) { 3955 int Off = -XLenInBytes; 3956 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3957 SDValue Offset = DAG.getConstant(Off, DL, VT); 3958 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3959 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3960 MachinePointerInfo()); 3961 } 3962 3963 // Return the value of the return address register, marking it an implicit 3964 // live-in. 3965 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3966 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3967 } 3968 3969 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3970 SelectionDAG &DAG) const { 3971 SDLoc DL(Op); 3972 SDValue Lo = Op.getOperand(0); 3973 SDValue Hi = Op.getOperand(1); 3974 SDValue Shamt = Op.getOperand(2); 3975 EVT VT = Lo.getValueType(); 3976 3977 // if Shamt-XLEN < 0: // Shamt < XLEN 3978 // Lo = Lo << Shamt 3979 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 3980 // else: 3981 // Lo = 0 3982 // Hi = Lo << (Shamt-XLEN) 3983 3984 SDValue Zero = DAG.getConstant(0, DL, VT); 3985 SDValue One = DAG.getConstant(1, DL, VT); 3986 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3987 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3988 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3989 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 3990 3991 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3992 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3993 SDValue ShiftRightLo = 3994 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3995 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3996 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3997 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3998 3999 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4000 4001 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 4002 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4003 4004 SDValue Parts[2] = {Lo, Hi}; 4005 return DAG.getMergeValues(Parts, DL); 4006 } 4007 4008 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 4009 bool IsSRA) const { 4010 SDLoc DL(Op); 4011 SDValue Lo = Op.getOperand(0); 4012 SDValue Hi = Op.getOperand(1); 4013 SDValue Shamt = Op.getOperand(2); 4014 EVT VT = Lo.getValueType(); 4015 4016 // SRA expansion: 4017 // if Shamt-XLEN < 0: // Shamt < XLEN 4018 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4019 // Hi = Hi >>s Shamt 4020 // else: 4021 // Lo = Hi >>s (Shamt-XLEN); 4022 // Hi = Hi >>s (XLEN-1) 4023 // 4024 // SRL expansion: 4025 // if Shamt-XLEN < 0: // Shamt < XLEN 4026 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4027 // Hi = Hi >>u Shamt 4028 // else: 4029 // Lo = Hi >>u (Shamt-XLEN); 4030 // Hi = 0; 4031 4032 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 4033 4034 SDValue Zero = DAG.getConstant(0, DL, VT); 4035 SDValue One = DAG.getConstant(1, DL, VT); 4036 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4037 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4038 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4039 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4040 4041 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 4042 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 4043 SDValue ShiftLeftHi = 4044 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 4045 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 4046 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 4047 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 4048 SDValue HiFalse = 4049 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 4050 4051 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4052 4053 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 4054 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4055 4056 SDValue Parts[2] = {Lo, Hi}; 4057 return DAG.getMergeValues(Parts, DL); 4058 } 4059 4060 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 4061 // legal equivalently-sized i8 type, so we can use that as a go-between. 4062 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4063 SelectionDAG &DAG) const { 4064 SDLoc DL(Op); 4065 MVT VT = Op.getSimpleValueType(); 4066 SDValue SplatVal = Op.getOperand(0); 4067 // All-zeros or all-ones splats are handled specially. 4068 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4069 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4070 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4071 } 4072 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4073 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4074 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4075 } 4076 MVT XLenVT = Subtarget.getXLenVT(); 4077 assert(SplatVal.getValueType() == XLenVT && 4078 "Unexpected type for i1 splat value"); 4079 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4080 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4081 DAG.getConstant(1, DL, XLenVT)); 4082 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4083 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4084 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4085 } 4086 4087 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4088 // illegal (currently only vXi64 RV32). 4089 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4090 // them to VMV_V_X_VL. 4091 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4092 SelectionDAG &DAG) const { 4093 SDLoc DL(Op); 4094 MVT VecVT = Op.getSimpleValueType(); 4095 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4096 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4097 4098 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4099 SDValue Lo = Op.getOperand(0); 4100 SDValue Hi = Op.getOperand(1); 4101 4102 if (VecVT.isFixedLengthVector()) { 4103 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4104 SDLoc DL(Op); 4105 SDValue Mask, VL; 4106 std::tie(Mask, VL) = 4107 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4108 4109 SDValue Res = 4110 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4111 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4112 } 4113 4114 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4115 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4116 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4117 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4118 // node in order to try and match RVV vector/scalar instructions. 4119 if ((LoC >> 31) == HiC) 4120 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4121 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4122 } 4123 4124 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4125 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4126 isa<ConstantSDNode>(Hi.getOperand(1)) && 4127 Hi.getConstantOperandVal(1) == 31) 4128 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4129 DAG.getRegister(RISCV::X0, MVT::i32)); 4130 4131 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4132 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4133 DAG.getUNDEF(VecVT), Lo, Hi, 4134 DAG.getRegister(RISCV::X0, MVT::i32)); 4135 } 4136 4137 // Custom-lower extensions from mask vectors by using a vselect either with 1 4138 // for zero/any-extension or -1 for sign-extension: 4139 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4140 // Note that any-extension is lowered identically to zero-extension. 4141 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4142 int64_t ExtTrueVal) const { 4143 SDLoc DL(Op); 4144 MVT VecVT = Op.getSimpleValueType(); 4145 SDValue Src = Op.getOperand(0); 4146 // Only custom-lower extensions from mask types 4147 assert(Src.getValueType().isVector() && 4148 Src.getValueType().getVectorElementType() == MVT::i1); 4149 4150 if (VecVT.isScalableVector()) { 4151 SDValue SplatZero = DAG.getConstant(0, DL, VecVT); 4152 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT); 4153 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4154 } 4155 4156 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4157 MVT I1ContainerVT = 4158 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4159 4160 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4161 4162 SDValue Mask, VL; 4163 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4164 4165 MVT XLenVT = Subtarget.getXLenVT(); 4166 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4167 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4168 4169 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4170 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4171 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4172 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4173 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4174 SplatTrueVal, SplatZero, VL); 4175 4176 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4177 } 4178 4179 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4180 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4181 MVT ExtVT = Op.getSimpleValueType(); 4182 // Only custom-lower extensions from fixed-length vector types. 4183 if (!ExtVT.isFixedLengthVector()) 4184 return Op; 4185 MVT VT = Op.getOperand(0).getSimpleValueType(); 4186 // Grab the canonical container type for the extended type. Infer the smaller 4187 // type from that to ensure the same number of vector elements, as we know 4188 // the LMUL will be sufficient to hold the smaller type. 4189 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4190 // Get the extended container type manually to ensure the same number of 4191 // vector elements between source and dest. 4192 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4193 ContainerExtVT.getVectorElementCount()); 4194 4195 SDValue Op1 = 4196 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4197 4198 SDLoc DL(Op); 4199 SDValue Mask, VL; 4200 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4201 4202 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4203 4204 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4205 } 4206 4207 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4208 // setcc operation: 4209 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4210 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op, 4211 SelectionDAG &DAG) const { 4212 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4213 SDLoc DL(Op); 4214 EVT MaskVT = Op.getValueType(); 4215 // Only expect to custom-lower truncations to mask types 4216 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4217 "Unexpected type for vector mask lowering"); 4218 SDValue Src = Op.getOperand(0); 4219 MVT VecVT = Src.getSimpleValueType(); 4220 SDValue Mask, VL; 4221 if (IsVPTrunc) { 4222 Mask = Op.getOperand(1); 4223 VL = Op.getOperand(2); 4224 } 4225 // If this is a fixed vector, we need to convert it to a scalable vector. 4226 MVT ContainerVT = VecVT; 4227 4228 if (VecVT.isFixedLengthVector()) { 4229 ContainerVT = getContainerForFixedLengthVector(VecVT); 4230 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4231 if (IsVPTrunc) { 4232 MVT MaskContainerVT = 4233 getContainerForFixedLengthVector(Mask.getSimpleValueType()); 4234 Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget); 4235 } 4236 } 4237 4238 if (!IsVPTrunc) { 4239 std::tie(Mask, VL) = 4240 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4241 } 4242 4243 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4244 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4245 4246 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4247 DAG.getUNDEF(ContainerVT), SplatOne, VL); 4248 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4249 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4250 4251 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4252 SDValue Trunc = 4253 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4254 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4255 DAG.getCondCode(ISD::SETNE), Mask, VL); 4256 if (MaskVT.isFixedLengthVector()) 4257 Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4258 return Trunc; 4259 } 4260 4261 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op, 4262 SelectionDAG &DAG) const { 4263 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4264 SDLoc DL(Op); 4265 4266 MVT VT = Op.getSimpleValueType(); 4267 // Only custom-lower vector truncates 4268 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4269 4270 // Truncates to mask types are handled differently 4271 if (VT.getVectorElementType() == MVT::i1) 4272 return lowerVectorMaskTruncLike(Op, DAG); 4273 4274 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 4275 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 4276 // truncate by one power of two at a time. 4277 MVT DstEltVT = VT.getVectorElementType(); 4278 4279 SDValue Src = Op.getOperand(0); 4280 MVT SrcVT = Src.getSimpleValueType(); 4281 MVT SrcEltVT = SrcVT.getVectorElementType(); 4282 4283 assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) && 4284 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 4285 "Unexpected vector truncate lowering"); 4286 4287 MVT ContainerVT = SrcVT; 4288 SDValue Mask, VL; 4289 if (IsVPTrunc) { 4290 Mask = Op.getOperand(1); 4291 VL = Op.getOperand(2); 4292 } 4293 if (SrcVT.isFixedLengthVector()) { 4294 ContainerVT = getContainerForFixedLengthVector(SrcVT); 4295 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4296 if (IsVPTrunc) { 4297 MVT MaskVT = getMaskTypeFor(ContainerVT); 4298 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4299 } 4300 } 4301 4302 SDValue Result = Src; 4303 if (!IsVPTrunc) { 4304 std::tie(Mask, VL) = 4305 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4306 } 4307 4308 LLVMContext &Context = *DAG.getContext(); 4309 const ElementCount Count = ContainerVT.getVectorElementCount(); 4310 do { 4311 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 4312 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 4313 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 4314 Mask, VL); 4315 } while (SrcEltVT != DstEltVT); 4316 4317 if (SrcVT.isFixedLengthVector()) 4318 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4319 4320 return Result; 4321 } 4322 4323 SDValue 4324 RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op, 4325 SelectionDAG &DAG) const { 4326 bool IsVP = 4327 Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND; 4328 bool IsExtend = 4329 Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND; 4330 // RVV can only do truncate fp to types half the size as the source. We 4331 // custom-lower f64->f16 rounds via RVV's round-to-odd float 4332 // conversion instruction. 4333 SDLoc DL(Op); 4334 MVT VT = Op.getSimpleValueType(); 4335 4336 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4337 4338 SDValue Src = Op.getOperand(0); 4339 MVT SrcVT = Src.getSimpleValueType(); 4340 4341 bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 || 4342 SrcVT.getVectorElementType() != MVT::f16); 4343 bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 || 4344 SrcVT.getVectorElementType() != MVT::f64); 4345 4346 bool IsDirectConv = IsDirectExtend || IsDirectTrunc; 4347 4348 // Prepare any fixed-length vector operands. 4349 MVT ContainerVT = VT; 4350 SDValue Mask, VL; 4351 if (IsVP) { 4352 Mask = Op.getOperand(1); 4353 VL = Op.getOperand(2); 4354 } 4355 if (VT.isFixedLengthVector()) { 4356 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 4357 ContainerVT = 4358 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 4359 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 4360 if (IsVP) { 4361 MVT MaskVT = getMaskTypeFor(ContainerVT); 4362 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4363 } 4364 } 4365 4366 if (!IsVP) 4367 std::tie(Mask, VL) = 4368 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4369 4370 unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL; 4371 4372 if (IsDirectConv) { 4373 Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL); 4374 if (VT.isFixedLengthVector()) 4375 Src = convertFromScalableVector(VT, Src, DAG, Subtarget); 4376 return Src; 4377 } 4378 4379 unsigned InterConvOpc = 4380 IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL; 4381 4382 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 4383 SDValue IntermediateConv = 4384 DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL); 4385 SDValue Result = 4386 DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL); 4387 if (VT.isFixedLengthVector()) 4388 return convertFromScalableVector(VT, Result, DAG, Subtarget); 4389 return Result; 4390 } 4391 4392 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4393 // first position of a vector, and that vector is slid up to the insert index. 4394 // By limiting the active vector length to index+1 and merging with the 4395 // original vector (with an undisturbed tail policy for elements >= VL), we 4396 // achieve the desired result of leaving all elements untouched except the one 4397 // at VL-1, which is replaced with the desired value. 4398 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4399 SelectionDAG &DAG) const { 4400 SDLoc DL(Op); 4401 MVT VecVT = Op.getSimpleValueType(); 4402 SDValue Vec = Op.getOperand(0); 4403 SDValue Val = Op.getOperand(1); 4404 SDValue Idx = Op.getOperand(2); 4405 4406 if (VecVT.getVectorElementType() == MVT::i1) { 4407 // FIXME: For now we just promote to an i8 vector and insert into that, 4408 // but this is probably not optimal. 4409 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4410 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4411 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4412 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4413 } 4414 4415 MVT ContainerVT = VecVT; 4416 // If the operand is a fixed-length vector, convert to a scalable one. 4417 if (VecVT.isFixedLengthVector()) { 4418 ContainerVT = getContainerForFixedLengthVector(VecVT); 4419 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4420 } 4421 4422 MVT XLenVT = Subtarget.getXLenVT(); 4423 4424 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4425 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4426 // Even i64-element vectors on RV32 can be lowered without scalar 4427 // legalization if the most-significant 32 bits of the value are not affected 4428 // by the sign-extension of the lower 32 bits. 4429 // TODO: We could also catch sign extensions of a 32-bit value. 4430 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4431 const auto *CVal = cast<ConstantSDNode>(Val); 4432 if (isInt<32>(CVal->getSExtValue())) { 4433 IsLegalInsert = true; 4434 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4435 } 4436 } 4437 4438 SDValue Mask, VL; 4439 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4440 4441 SDValue ValInVec; 4442 4443 if (IsLegalInsert) { 4444 unsigned Opc = 4445 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4446 if (isNullConstant(Idx)) { 4447 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4448 if (!VecVT.isFixedLengthVector()) 4449 return Vec; 4450 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4451 } 4452 ValInVec = 4453 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4454 } else { 4455 // On RV32, i64-element vectors must be specially handled to place the 4456 // value at element 0, by using two vslide1up instructions in sequence on 4457 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4458 // this. 4459 SDValue One = DAG.getConstant(1, DL, XLenVT); 4460 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4461 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4462 MVT I32ContainerVT = 4463 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4464 SDValue I32Mask = 4465 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4466 // Limit the active VL to two. 4467 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4468 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4469 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4470 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4471 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4472 // First slide in the hi value, then the lo in underneath it. 4473 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4474 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4475 I32Mask, InsertI64VL); 4476 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4477 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4478 I32Mask, InsertI64VL); 4479 // Bitcast back to the right container type. 4480 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4481 } 4482 4483 // Now that the value is in a vector, slide it into position. 4484 SDValue InsertVL = 4485 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4486 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4487 ValInVec, Idx, Mask, InsertVL); 4488 if (!VecVT.isFixedLengthVector()) 4489 return Slideup; 4490 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4491 } 4492 4493 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4494 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4495 // types this is done using VMV_X_S to allow us to glean information about the 4496 // sign bits of the result. 4497 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4498 SelectionDAG &DAG) const { 4499 SDLoc DL(Op); 4500 SDValue Idx = Op.getOperand(1); 4501 SDValue Vec = Op.getOperand(0); 4502 EVT EltVT = Op.getValueType(); 4503 MVT VecVT = Vec.getSimpleValueType(); 4504 MVT XLenVT = Subtarget.getXLenVT(); 4505 4506 if (VecVT.getVectorElementType() == MVT::i1) { 4507 if (VecVT.isFixedLengthVector()) { 4508 unsigned NumElts = VecVT.getVectorNumElements(); 4509 if (NumElts >= 8) { 4510 MVT WideEltVT; 4511 unsigned WidenVecLen; 4512 SDValue ExtractElementIdx; 4513 SDValue ExtractBitIdx; 4514 unsigned MaxEEW = Subtarget.getELEN(); 4515 MVT LargestEltVT = MVT::getIntegerVT( 4516 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4517 if (NumElts <= LargestEltVT.getSizeInBits()) { 4518 assert(isPowerOf2_32(NumElts) && 4519 "the number of elements should be power of 2"); 4520 WideEltVT = MVT::getIntegerVT(NumElts); 4521 WidenVecLen = 1; 4522 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4523 ExtractBitIdx = Idx; 4524 } else { 4525 WideEltVT = LargestEltVT; 4526 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4527 // extract element index = index / element width 4528 ExtractElementIdx = DAG.getNode( 4529 ISD::SRL, DL, XLenVT, Idx, 4530 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4531 // mask bit index = index % element width 4532 ExtractBitIdx = DAG.getNode( 4533 ISD::AND, DL, XLenVT, Idx, 4534 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4535 } 4536 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4537 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4538 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4539 Vec, ExtractElementIdx); 4540 // Extract the bit from GPR. 4541 SDValue ShiftRight = 4542 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4543 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4544 DAG.getConstant(1, DL, XLenVT)); 4545 } 4546 } 4547 // Otherwise, promote to an i8 vector and extract from that. 4548 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4549 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4550 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4551 } 4552 4553 // If this is a fixed vector, we need to convert it to a scalable vector. 4554 MVT ContainerVT = VecVT; 4555 if (VecVT.isFixedLengthVector()) { 4556 ContainerVT = getContainerForFixedLengthVector(VecVT); 4557 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4558 } 4559 4560 // If the index is 0, the vector is already in the right position. 4561 if (!isNullConstant(Idx)) { 4562 // Use a VL of 1 to avoid processing more elements than we need. 4563 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4564 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 4565 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4566 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4567 } 4568 4569 if (!EltVT.isInteger()) { 4570 // Floating-point extracts are handled in TableGen. 4571 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4572 DAG.getConstant(0, DL, XLenVT)); 4573 } 4574 4575 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4576 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4577 } 4578 4579 // Some RVV intrinsics may claim that they want an integer operand to be 4580 // promoted or expanded. 4581 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG, 4582 const RISCVSubtarget &Subtarget) { 4583 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4584 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4585 "Unexpected opcode"); 4586 4587 if (!Subtarget.hasVInstructions()) 4588 return SDValue(); 4589 4590 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4591 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4592 SDLoc DL(Op); 4593 4594 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4595 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4596 if (!II || !II->hasScalarOperand()) 4597 return SDValue(); 4598 4599 unsigned SplatOp = II->ScalarOperand + 1 + HasChain; 4600 assert(SplatOp < Op.getNumOperands()); 4601 4602 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4603 SDValue &ScalarOp = Operands[SplatOp]; 4604 MVT OpVT = ScalarOp.getSimpleValueType(); 4605 MVT XLenVT = Subtarget.getXLenVT(); 4606 4607 // If this isn't a scalar, or its type is XLenVT we're done. 4608 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4609 return SDValue(); 4610 4611 // Simplest case is that the operand needs to be promoted to XLenVT. 4612 if (OpVT.bitsLT(XLenVT)) { 4613 // If the operand is a constant, sign extend to increase our chances 4614 // of being able to use a .vi instruction. ANY_EXTEND would become a 4615 // a zero extend and the simm5 check in isel would fail. 4616 // FIXME: Should we ignore the upper bits in isel instead? 4617 unsigned ExtOpc = 4618 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4619 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4620 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4621 } 4622 4623 // Use the previous operand to get the vXi64 VT. The result might be a mask 4624 // VT for compares. Using the previous operand assumes that the previous 4625 // operand will never have a smaller element size than a scalar operand and 4626 // that a widening operation never uses SEW=64. 4627 // NOTE: If this fails the below assert, we can probably just find the 4628 // element count from any operand or result and use it to construct the VT. 4629 assert(II->ScalarOperand > 0 && "Unexpected splat operand!"); 4630 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4631 4632 // The more complex case is when the scalar is larger than XLenVT. 4633 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4634 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4635 4636 // If this is a sign-extended 32-bit value, we can truncate it and rely on the 4637 // instruction to sign-extend since SEW>XLEN. 4638 if (DAG.ComputeNumSignBits(ScalarOp) > 32) { 4639 ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp); 4640 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4641 } 4642 4643 switch (IntNo) { 4644 case Intrinsic::riscv_vslide1up: 4645 case Intrinsic::riscv_vslide1down: 4646 case Intrinsic::riscv_vslide1up_mask: 4647 case Intrinsic::riscv_vslide1down_mask: { 4648 // We need to special case these when the scalar is larger than XLen. 4649 unsigned NumOps = Op.getNumOperands(); 4650 bool IsMasked = NumOps == 7; 4651 4652 // Convert the vector source to the equivalent nxvXi32 vector. 4653 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4654 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4655 4656 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4657 DAG.getConstant(0, DL, XLenVT)); 4658 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4659 DAG.getConstant(1, DL, XLenVT)); 4660 4661 // Double the VL since we halved SEW. 4662 SDValue AVL = getVLOperand(Op); 4663 SDValue I32VL; 4664 4665 // Optimize for constant AVL 4666 if (isa<ConstantSDNode>(AVL)) { 4667 unsigned EltSize = VT.getScalarSizeInBits(); 4668 unsigned MinSize = VT.getSizeInBits().getKnownMinValue(); 4669 4670 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 4671 unsigned MaxVLMAX = 4672 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 4673 4674 unsigned VectorBitsMin = Subtarget.getRealMinVLen(); 4675 unsigned MinVLMAX = 4676 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize); 4677 4678 uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue(); 4679 if (AVLInt <= MinVLMAX) { 4680 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT); 4681 } else if (AVLInt >= 2 * MaxVLMAX) { 4682 // Just set vl to VLMAX in this situation 4683 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT); 4684 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4685 unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits()); 4686 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4687 SDValue SETVLMAX = DAG.getTargetConstant( 4688 Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32); 4689 I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW, 4690 LMUL); 4691 } else { 4692 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl 4693 // is related to the hardware implementation. 4694 // So let the following code handle 4695 } 4696 } 4697 if (!I32VL) { 4698 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT); 4699 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4700 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits()); 4701 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4702 SDValue SETVL = 4703 DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32); 4704 // Using vsetvli instruction to get actually used length which related to 4705 // the hardware implementation 4706 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL, 4707 SEW, LMUL); 4708 I32VL = 4709 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4710 } 4711 4712 SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG); 4713 4714 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4715 // instructions. 4716 SDValue Passthru; 4717 if (IsMasked) 4718 Passthru = DAG.getUNDEF(I32VT); 4719 else 4720 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4721 4722 if (IntNo == Intrinsic::riscv_vslide1up || 4723 IntNo == Intrinsic::riscv_vslide1up_mask) { 4724 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4725 ScalarHi, I32Mask, I32VL); 4726 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4727 ScalarLo, I32Mask, I32VL); 4728 } else { 4729 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4730 ScalarLo, I32Mask, I32VL); 4731 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4732 ScalarHi, I32Mask, I32VL); 4733 } 4734 4735 // Convert back to nxvXi64. 4736 Vec = DAG.getBitcast(VT, Vec); 4737 4738 if (!IsMasked) 4739 return Vec; 4740 // Apply mask after the operation. 4741 SDValue Mask = Operands[NumOps - 3]; 4742 SDValue MaskedOff = Operands[1]; 4743 // Assume Policy operand is the last operand. 4744 uint64_t Policy = 4745 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4746 // We don't need to select maskedoff if it's undef. 4747 if (MaskedOff.isUndef()) 4748 return Vec; 4749 // TAMU 4750 if (Policy == RISCVII::TAIL_AGNOSTIC) 4751 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4752 AVL); 4753 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4754 // It's fine because vmerge does not care mask policy. 4755 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, 4756 AVL); 4757 } 4758 } 4759 4760 // We need to convert the scalar to a splat vector. 4761 SDValue VL = getVLOperand(Op); 4762 assert(VL.getValueType() == XLenVT); 4763 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4764 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4765 } 4766 4767 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4768 SelectionDAG &DAG) const { 4769 unsigned IntNo = Op.getConstantOperandVal(0); 4770 SDLoc DL(Op); 4771 MVT XLenVT = Subtarget.getXLenVT(); 4772 4773 switch (IntNo) { 4774 default: 4775 break; // Don't custom lower most intrinsics. 4776 case Intrinsic::thread_pointer: { 4777 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4778 return DAG.getRegister(RISCV::X4, PtrVT); 4779 } 4780 case Intrinsic::riscv_orc_b: 4781 case Intrinsic::riscv_brev8: { 4782 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4783 unsigned Opc = 4784 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4785 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4786 DAG.getConstant(7, DL, XLenVT)); 4787 } 4788 case Intrinsic::riscv_grev: 4789 case Intrinsic::riscv_gorc: { 4790 unsigned Opc = 4791 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4792 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4793 } 4794 case Intrinsic::riscv_zip: 4795 case Intrinsic::riscv_unzip: { 4796 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4797 // For i32 the immediate is 15. For i64 the immediate is 31. 4798 unsigned Opc = 4799 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4800 unsigned BitWidth = Op.getValueSizeInBits(); 4801 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4802 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4803 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4804 } 4805 case Intrinsic::riscv_shfl: 4806 case Intrinsic::riscv_unshfl: { 4807 unsigned Opc = 4808 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4809 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4810 } 4811 case Intrinsic::riscv_bcompress: 4812 case Intrinsic::riscv_bdecompress: { 4813 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4814 : RISCVISD::BDECOMPRESS; 4815 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4816 } 4817 case Intrinsic::riscv_bfp: 4818 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4819 Op.getOperand(2)); 4820 case Intrinsic::riscv_fsl: 4821 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4822 Op.getOperand(2), Op.getOperand(3)); 4823 case Intrinsic::riscv_fsr: 4824 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4825 Op.getOperand(2), Op.getOperand(3)); 4826 case Intrinsic::riscv_vmv_x_s: 4827 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4828 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4829 Op.getOperand(1)); 4830 case Intrinsic::riscv_vmv_v_x: 4831 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4832 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4833 Subtarget); 4834 case Intrinsic::riscv_vfmv_v_f: 4835 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4836 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4837 case Intrinsic::riscv_vmv_s_x: { 4838 SDValue Scalar = Op.getOperand(2); 4839 4840 if (Scalar.getValueType().bitsLE(XLenVT)) { 4841 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4842 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4843 Op.getOperand(1), Scalar, Op.getOperand(3)); 4844 } 4845 4846 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4847 4848 // This is an i64 value that lives in two scalar registers. We have to 4849 // insert this in a convoluted way. First we build vXi64 splat containing 4850 // the two values that we assemble using some bit math. Next we'll use 4851 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4852 // to merge element 0 from our splat into the source vector. 4853 // FIXME: This is probably not the best way to do this, but it is 4854 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4855 // point. 4856 // sw lo, (a0) 4857 // sw hi, 4(a0) 4858 // vlse vX, (a0) 4859 // 4860 // vid.v vVid 4861 // vmseq.vx mMask, vVid, 0 4862 // vmerge.vvm vDest, vSrc, vVal, mMask 4863 MVT VT = Op.getSimpleValueType(); 4864 SDValue Vec = Op.getOperand(1); 4865 SDValue VL = getVLOperand(Op); 4866 4867 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4868 if (Op.getOperand(1).isUndef()) 4869 return SplattedVal; 4870 SDValue SplattedIdx = 4871 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4872 DAG.getConstant(0, DL, MVT::i32), VL); 4873 4874 MVT MaskVT = getMaskTypeFor(VT); 4875 SDValue Mask = getAllOnesMask(VT, VL, DL, DAG); 4876 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4877 SDValue SelectCond = 4878 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4879 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4880 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4881 Vec, VL); 4882 } 4883 } 4884 4885 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4886 } 4887 4888 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4889 SelectionDAG &DAG) const { 4890 unsigned IntNo = Op.getConstantOperandVal(1); 4891 switch (IntNo) { 4892 default: 4893 break; 4894 case Intrinsic::riscv_masked_strided_load: { 4895 SDLoc DL(Op); 4896 MVT XLenVT = Subtarget.getXLenVT(); 4897 4898 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4899 // the selection of the masked intrinsics doesn't do this for us. 4900 SDValue Mask = Op.getOperand(5); 4901 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4902 4903 MVT VT = Op->getSimpleValueType(0); 4904 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4905 4906 SDValue PassThru = Op.getOperand(2); 4907 if (!IsUnmasked) { 4908 MVT MaskVT = getMaskTypeFor(ContainerVT); 4909 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4910 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4911 } 4912 4913 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4914 4915 SDValue IntID = DAG.getTargetConstant( 4916 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4917 XLenVT); 4918 4919 auto *Load = cast<MemIntrinsicSDNode>(Op); 4920 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4921 if (IsUnmasked) 4922 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4923 else 4924 Ops.push_back(PassThru); 4925 Ops.push_back(Op.getOperand(3)); // Ptr 4926 Ops.push_back(Op.getOperand(4)); // Stride 4927 if (!IsUnmasked) 4928 Ops.push_back(Mask); 4929 Ops.push_back(VL); 4930 if (!IsUnmasked) { 4931 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4932 Ops.push_back(Policy); 4933 } 4934 4935 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4936 SDValue Result = 4937 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4938 Load->getMemoryVT(), Load->getMemOperand()); 4939 SDValue Chain = Result.getValue(1); 4940 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4941 return DAG.getMergeValues({Result, Chain}, DL); 4942 } 4943 case Intrinsic::riscv_seg2_load: 4944 case Intrinsic::riscv_seg3_load: 4945 case Intrinsic::riscv_seg4_load: 4946 case Intrinsic::riscv_seg5_load: 4947 case Intrinsic::riscv_seg6_load: 4948 case Intrinsic::riscv_seg7_load: 4949 case Intrinsic::riscv_seg8_load: { 4950 SDLoc DL(Op); 4951 static const Intrinsic::ID VlsegInts[7] = { 4952 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 4953 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 4954 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 4955 Intrinsic::riscv_vlseg8}; 4956 unsigned NF = Op->getNumValues() - 1; 4957 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 4958 MVT XLenVT = Subtarget.getXLenVT(); 4959 MVT VT = Op->getSimpleValueType(0); 4960 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4961 4962 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4963 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 4964 auto *Load = cast<MemIntrinsicSDNode>(Op); 4965 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 4966 ContainerVTs.push_back(MVT::Other); 4967 SDVTList VTs = DAG.getVTList(ContainerVTs); 4968 SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID}; 4969 Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT)); 4970 Ops.push_back(Op.getOperand(2)); 4971 Ops.push_back(VL); 4972 SDValue Result = 4973 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4974 Load->getMemoryVT(), Load->getMemOperand()); 4975 SmallVector<SDValue, 9> Results; 4976 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 4977 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 4978 DAG, Subtarget)); 4979 Results.push_back(Result.getValue(NF)); 4980 return DAG.getMergeValues(Results, DL); 4981 } 4982 } 4983 4984 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4985 } 4986 4987 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4988 SelectionDAG &DAG) const { 4989 unsigned IntNo = Op.getConstantOperandVal(1); 4990 switch (IntNo) { 4991 default: 4992 break; 4993 case Intrinsic::riscv_masked_strided_store: { 4994 SDLoc DL(Op); 4995 MVT XLenVT = Subtarget.getXLenVT(); 4996 4997 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4998 // the selection of the masked intrinsics doesn't do this for us. 4999 SDValue Mask = Op.getOperand(5); 5000 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5001 5002 SDValue Val = Op.getOperand(2); 5003 MVT VT = Val.getSimpleValueType(); 5004 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5005 5006 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5007 if (!IsUnmasked) { 5008 MVT MaskVT = getMaskTypeFor(ContainerVT); 5009 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5010 } 5011 5012 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5013 5014 SDValue IntID = DAG.getTargetConstant( 5015 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 5016 XLenVT); 5017 5018 auto *Store = cast<MemIntrinsicSDNode>(Op); 5019 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 5020 Ops.push_back(Val); 5021 Ops.push_back(Op.getOperand(3)); // Ptr 5022 Ops.push_back(Op.getOperand(4)); // Stride 5023 if (!IsUnmasked) 5024 Ops.push_back(Mask); 5025 Ops.push_back(VL); 5026 5027 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 5028 Ops, Store->getMemoryVT(), 5029 Store->getMemOperand()); 5030 } 5031 } 5032 5033 return SDValue(); 5034 } 5035 5036 static MVT getLMUL1VT(MVT VT) { 5037 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 5038 "Unexpected vector MVT"); 5039 return MVT::getScalableVectorVT( 5040 VT.getVectorElementType(), 5041 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 5042 } 5043 5044 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 5045 switch (ISDOpcode) { 5046 default: 5047 llvm_unreachable("Unhandled reduction"); 5048 case ISD::VECREDUCE_ADD: 5049 return RISCVISD::VECREDUCE_ADD_VL; 5050 case ISD::VECREDUCE_UMAX: 5051 return RISCVISD::VECREDUCE_UMAX_VL; 5052 case ISD::VECREDUCE_SMAX: 5053 return RISCVISD::VECREDUCE_SMAX_VL; 5054 case ISD::VECREDUCE_UMIN: 5055 return RISCVISD::VECREDUCE_UMIN_VL; 5056 case ISD::VECREDUCE_SMIN: 5057 return RISCVISD::VECREDUCE_SMIN_VL; 5058 case ISD::VECREDUCE_AND: 5059 return RISCVISD::VECREDUCE_AND_VL; 5060 case ISD::VECREDUCE_OR: 5061 return RISCVISD::VECREDUCE_OR_VL; 5062 case ISD::VECREDUCE_XOR: 5063 return RISCVISD::VECREDUCE_XOR_VL; 5064 } 5065 } 5066 5067 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 5068 SelectionDAG &DAG, 5069 bool IsVP) const { 5070 SDLoc DL(Op); 5071 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 5072 MVT VecVT = Vec.getSimpleValueType(); 5073 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 5074 Op.getOpcode() == ISD::VECREDUCE_OR || 5075 Op.getOpcode() == ISD::VECREDUCE_XOR || 5076 Op.getOpcode() == ISD::VP_REDUCE_AND || 5077 Op.getOpcode() == ISD::VP_REDUCE_OR || 5078 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5079 "Unexpected reduction lowering"); 5080 5081 MVT XLenVT = Subtarget.getXLenVT(); 5082 assert(Op.getValueType() == XLenVT && 5083 "Expected reduction output to be legalized to XLenVT"); 5084 5085 MVT ContainerVT = VecVT; 5086 if (VecVT.isFixedLengthVector()) { 5087 ContainerVT = getContainerForFixedLengthVector(VecVT); 5088 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5089 } 5090 5091 SDValue Mask, VL; 5092 if (IsVP) { 5093 Mask = Op.getOperand(2); 5094 VL = Op.getOperand(3); 5095 } else { 5096 std::tie(Mask, VL) = 5097 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5098 } 5099 5100 unsigned BaseOpc; 5101 ISD::CondCode CC; 5102 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5103 5104 switch (Op.getOpcode()) { 5105 default: 5106 llvm_unreachable("Unhandled reduction"); 5107 case ISD::VECREDUCE_AND: 5108 case ISD::VP_REDUCE_AND: { 5109 // vcpop ~x == 0 5110 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5111 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5112 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5113 CC = ISD::SETEQ; 5114 BaseOpc = ISD::AND; 5115 break; 5116 } 5117 case ISD::VECREDUCE_OR: 5118 case ISD::VP_REDUCE_OR: 5119 // vcpop x != 0 5120 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5121 CC = ISD::SETNE; 5122 BaseOpc = ISD::OR; 5123 break; 5124 case ISD::VECREDUCE_XOR: 5125 case ISD::VP_REDUCE_XOR: { 5126 // ((vcpop x) & 1) != 0 5127 SDValue One = DAG.getConstant(1, DL, XLenVT); 5128 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5129 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5130 CC = ISD::SETNE; 5131 BaseOpc = ISD::XOR; 5132 break; 5133 } 5134 } 5135 5136 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5137 5138 if (!IsVP) 5139 return SetCC; 5140 5141 // Now include the start value in the operation. 5142 // Note that we must return the start value when no elements are operated 5143 // upon. The vcpop instructions we've emitted in each case above will return 5144 // 0 for an inactive vector, and so we've already received the neutral value: 5145 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5146 // can simply include the start value. 5147 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5148 } 5149 5150 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5151 SelectionDAG &DAG) const { 5152 SDLoc DL(Op); 5153 SDValue Vec = Op.getOperand(0); 5154 EVT VecEVT = Vec.getValueType(); 5155 5156 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5157 5158 // Due to ordering in legalize types we may have a vector type that needs to 5159 // be split. Do that manually so we can get down to a legal type. 5160 while (getTypeAction(*DAG.getContext(), VecEVT) == 5161 TargetLowering::TypeSplitVector) { 5162 SDValue Lo, Hi; 5163 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5164 VecEVT = Lo.getValueType(); 5165 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5166 } 5167 5168 // TODO: The type may need to be widened rather than split. Or widened before 5169 // it can be split. 5170 if (!isTypeLegal(VecEVT)) 5171 return SDValue(); 5172 5173 MVT VecVT = VecEVT.getSimpleVT(); 5174 MVT VecEltVT = VecVT.getVectorElementType(); 5175 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5176 5177 MVT ContainerVT = VecVT; 5178 if (VecVT.isFixedLengthVector()) { 5179 ContainerVT = getContainerForFixedLengthVector(VecVT); 5180 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5181 } 5182 5183 MVT M1VT = getLMUL1VT(ContainerVT); 5184 MVT XLenVT = Subtarget.getXLenVT(); 5185 5186 SDValue Mask, VL; 5187 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5188 5189 SDValue NeutralElem = 5190 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5191 SDValue IdentitySplat = 5192 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5193 M1VT, DL, DAG, Subtarget); 5194 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5195 IdentitySplat, Mask, VL); 5196 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5197 DAG.getConstant(0, DL, XLenVT)); 5198 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5199 } 5200 5201 // Given a reduction op, this function returns the matching reduction opcode, 5202 // the vector SDValue and the scalar SDValue required to lower this to a 5203 // RISCVISD node. 5204 static std::tuple<unsigned, SDValue, SDValue> 5205 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5206 SDLoc DL(Op); 5207 auto Flags = Op->getFlags(); 5208 unsigned Opcode = Op.getOpcode(); 5209 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5210 switch (Opcode) { 5211 default: 5212 llvm_unreachable("Unhandled reduction"); 5213 case ISD::VECREDUCE_FADD: { 5214 // Use positive zero if we can. It is cheaper to materialize. 5215 SDValue Zero = 5216 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5217 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5218 } 5219 case ISD::VECREDUCE_SEQ_FADD: 5220 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5221 Op.getOperand(0)); 5222 case ISD::VECREDUCE_FMIN: 5223 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5224 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5225 case ISD::VECREDUCE_FMAX: 5226 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5227 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5228 } 5229 } 5230 5231 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5232 SelectionDAG &DAG) const { 5233 SDLoc DL(Op); 5234 MVT VecEltVT = Op.getSimpleValueType(); 5235 5236 unsigned RVVOpcode; 5237 SDValue VectorVal, ScalarVal; 5238 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5239 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5240 MVT VecVT = VectorVal.getSimpleValueType(); 5241 5242 MVT ContainerVT = VecVT; 5243 if (VecVT.isFixedLengthVector()) { 5244 ContainerVT = getContainerForFixedLengthVector(VecVT); 5245 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5246 } 5247 5248 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5249 MVT XLenVT = Subtarget.getXLenVT(); 5250 5251 SDValue Mask, VL; 5252 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5253 5254 SDValue ScalarSplat = 5255 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5256 M1VT, DL, DAG, Subtarget); 5257 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5258 VectorVal, ScalarSplat, Mask, VL); 5259 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5260 DAG.getConstant(0, DL, XLenVT)); 5261 } 5262 5263 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5264 switch (ISDOpcode) { 5265 default: 5266 llvm_unreachable("Unhandled reduction"); 5267 case ISD::VP_REDUCE_ADD: 5268 return RISCVISD::VECREDUCE_ADD_VL; 5269 case ISD::VP_REDUCE_UMAX: 5270 return RISCVISD::VECREDUCE_UMAX_VL; 5271 case ISD::VP_REDUCE_SMAX: 5272 return RISCVISD::VECREDUCE_SMAX_VL; 5273 case ISD::VP_REDUCE_UMIN: 5274 return RISCVISD::VECREDUCE_UMIN_VL; 5275 case ISD::VP_REDUCE_SMIN: 5276 return RISCVISD::VECREDUCE_SMIN_VL; 5277 case ISD::VP_REDUCE_AND: 5278 return RISCVISD::VECREDUCE_AND_VL; 5279 case ISD::VP_REDUCE_OR: 5280 return RISCVISD::VECREDUCE_OR_VL; 5281 case ISD::VP_REDUCE_XOR: 5282 return RISCVISD::VECREDUCE_XOR_VL; 5283 case ISD::VP_REDUCE_FADD: 5284 return RISCVISD::VECREDUCE_FADD_VL; 5285 case ISD::VP_REDUCE_SEQ_FADD: 5286 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5287 case ISD::VP_REDUCE_FMAX: 5288 return RISCVISD::VECREDUCE_FMAX_VL; 5289 case ISD::VP_REDUCE_FMIN: 5290 return RISCVISD::VECREDUCE_FMIN_VL; 5291 } 5292 } 5293 5294 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5295 SelectionDAG &DAG) const { 5296 SDLoc DL(Op); 5297 SDValue Vec = Op.getOperand(1); 5298 EVT VecEVT = Vec.getValueType(); 5299 5300 // TODO: The type may need to be widened rather than split. Or widened before 5301 // it can be split. 5302 if (!isTypeLegal(VecEVT)) 5303 return SDValue(); 5304 5305 MVT VecVT = VecEVT.getSimpleVT(); 5306 MVT VecEltVT = VecVT.getVectorElementType(); 5307 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5308 5309 MVT ContainerVT = VecVT; 5310 if (VecVT.isFixedLengthVector()) { 5311 ContainerVT = getContainerForFixedLengthVector(VecVT); 5312 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5313 } 5314 5315 SDValue VL = Op.getOperand(3); 5316 SDValue Mask = Op.getOperand(2); 5317 5318 MVT M1VT = getLMUL1VT(ContainerVT); 5319 MVT XLenVT = Subtarget.getXLenVT(); 5320 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5321 5322 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5323 DAG.getConstant(1, DL, XLenVT), M1VT, 5324 DL, DAG, Subtarget); 5325 SDValue Reduction = 5326 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5327 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5328 DAG.getConstant(0, DL, XLenVT)); 5329 if (!VecVT.isInteger()) 5330 return Elt0; 5331 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5332 } 5333 5334 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5335 SelectionDAG &DAG) const { 5336 SDValue Vec = Op.getOperand(0); 5337 SDValue SubVec = Op.getOperand(1); 5338 MVT VecVT = Vec.getSimpleValueType(); 5339 MVT SubVecVT = SubVec.getSimpleValueType(); 5340 5341 SDLoc DL(Op); 5342 MVT XLenVT = Subtarget.getXLenVT(); 5343 unsigned OrigIdx = Op.getConstantOperandVal(2); 5344 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5345 5346 // We don't have the ability to slide mask vectors up indexed by their i1 5347 // elements; the smallest we can do is i8. Often we are able to bitcast to 5348 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5349 // into a scalable one, we might not necessarily have enough scalable 5350 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5351 if (SubVecVT.getVectorElementType() == MVT::i1 && 5352 (OrigIdx != 0 || !Vec.isUndef())) { 5353 if (VecVT.getVectorMinNumElements() >= 8 && 5354 SubVecVT.getVectorMinNumElements() >= 8) { 5355 assert(OrigIdx % 8 == 0 && "Invalid index"); 5356 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5357 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5358 "Unexpected mask vector lowering"); 5359 OrigIdx /= 8; 5360 SubVecVT = 5361 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5362 SubVecVT.isScalableVector()); 5363 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5364 VecVT.isScalableVector()); 5365 Vec = DAG.getBitcast(VecVT, Vec); 5366 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5367 } else { 5368 // We can't slide this mask vector up indexed by its i1 elements. 5369 // This poses a problem when we wish to insert a scalable vector which 5370 // can't be re-expressed as a larger type. Just choose the slow path and 5371 // extend to a larger type, then truncate back down. 5372 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5373 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5374 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5375 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5376 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5377 Op.getOperand(2)); 5378 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5379 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5380 } 5381 } 5382 5383 // If the subvector vector is a fixed-length type, we cannot use subregister 5384 // manipulation to simplify the codegen; we don't know which register of a 5385 // LMUL group contains the specific subvector as we only know the minimum 5386 // register size. Therefore we must slide the vector group up the full 5387 // amount. 5388 if (SubVecVT.isFixedLengthVector()) { 5389 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5390 return Op; 5391 MVT ContainerVT = VecVT; 5392 if (VecVT.isFixedLengthVector()) { 5393 ContainerVT = getContainerForFixedLengthVector(VecVT); 5394 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5395 } 5396 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5397 DAG.getUNDEF(ContainerVT), SubVec, 5398 DAG.getConstant(0, DL, XLenVT)); 5399 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5400 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5401 return DAG.getBitcast(Op.getValueType(), SubVec); 5402 } 5403 SDValue Mask = 5404 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5405 // Set the vector length to only the number of elements we care about. Note 5406 // that for slideup this includes the offset. 5407 SDValue VL = 5408 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5409 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5410 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5411 SubVec, SlideupAmt, Mask, VL); 5412 if (VecVT.isFixedLengthVector()) 5413 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5414 return DAG.getBitcast(Op.getValueType(), Slideup); 5415 } 5416 5417 unsigned SubRegIdx, RemIdx; 5418 std::tie(SubRegIdx, RemIdx) = 5419 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5420 VecVT, SubVecVT, OrigIdx, TRI); 5421 5422 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5423 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5424 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5425 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5426 5427 // 1. If the Idx has been completely eliminated and this subvector's size is 5428 // a vector register or a multiple thereof, or the surrounding elements are 5429 // undef, then this is a subvector insert which naturally aligns to a vector 5430 // register. These can easily be handled using subregister manipulation. 5431 // 2. If the subvector is smaller than a vector register, then the insertion 5432 // must preserve the undisturbed elements of the register. We do this by 5433 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5434 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5435 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5436 // LMUL=1 type back into the larger vector (resolving to another subregister 5437 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5438 // to avoid allocating a large register group to hold our subvector. 5439 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5440 return Op; 5441 5442 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5443 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5444 // (in our case undisturbed). This means we can set up a subvector insertion 5445 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5446 // size of the subvector. 5447 MVT InterSubVT = VecVT; 5448 SDValue AlignedExtract = Vec; 5449 unsigned AlignedIdx = OrigIdx - RemIdx; 5450 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5451 InterSubVT = getLMUL1VT(VecVT); 5452 // Extract a subvector equal to the nearest full vector register type. This 5453 // should resolve to a EXTRACT_SUBREG instruction. 5454 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5455 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5456 } 5457 5458 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5459 // For scalable vectors this must be further multiplied by vscale. 5460 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5461 5462 SDValue Mask, VL; 5463 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5464 5465 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5466 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5467 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5468 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5469 5470 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5471 DAG.getUNDEF(InterSubVT), SubVec, 5472 DAG.getConstant(0, DL, XLenVT)); 5473 5474 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5475 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5476 5477 // If required, insert this subvector back into the correct vector register. 5478 // This should resolve to an INSERT_SUBREG instruction. 5479 if (VecVT.bitsGT(InterSubVT)) 5480 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5481 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5482 5483 // We might have bitcast from a mask type: cast back to the original type if 5484 // required. 5485 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5486 } 5487 5488 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5489 SelectionDAG &DAG) const { 5490 SDValue Vec = Op.getOperand(0); 5491 MVT SubVecVT = Op.getSimpleValueType(); 5492 MVT VecVT = Vec.getSimpleValueType(); 5493 5494 SDLoc DL(Op); 5495 MVT XLenVT = Subtarget.getXLenVT(); 5496 unsigned OrigIdx = Op.getConstantOperandVal(1); 5497 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5498 5499 // We don't have the ability to slide mask vectors down indexed by their i1 5500 // elements; the smallest we can do is i8. Often we are able to bitcast to 5501 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5502 // from a scalable one, we might not necessarily have enough scalable 5503 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5504 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5505 if (VecVT.getVectorMinNumElements() >= 8 && 5506 SubVecVT.getVectorMinNumElements() >= 8) { 5507 assert(OrigIdx % 8 == 0 && "Invalid index"); 5508 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5509 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5510 "Unexpected mask vector lowering"); 5511 OrigIdx /= 8; 5512 SubVecVT = 5513 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5514 SubVecVT.isScalableVector()); 5515 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5516 VecVT.isScalableVector()); 5517 Vec = DAG.getBitcast(VecVT, Vec); 5518 } else { 5519 // We can't slide this mask vector down, indexed by its i1 elements. 5520 // This poses a problem when we wish to extract a scalable vector which 5521 // can't be re-expressed as a larger type. Just choose the slow path and 5522 // extend to a larger type, then truncate back down. 5523 // TODO: We could probably improve this when extracting certain fixed 5524 // from fixed, where we can extract as i8 and shift the correct element 5525 // right to reach the desired subvector? 5526 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5527 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5528 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5529 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5530 Op.getOperand(1)); 5531 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5532 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5533 } 5534 } 5535 5536 // If the subvector vector is a fixed-length type, we cannot use subregister 5537 // manipulation to simplify the codegen; we don't know which register of a 5538 // LMUL group contains the specific subvector as we only know the minimum 5539 // register size. Therefore we must slide the vector group down the full 5540 // amount. 5541 if (SubVecVT.isFixedLengthVector()) { 5542 // With an index of 0 this is a cast-like subvector, which can be performed 5543 // with subregister operations. 5544 if (OrigIdx == 0) 5545 return Op; 5546 MVT ContainerVT = VecVT; 5547 if (VecVT.isFixedLengthVector()) { 5548 ContainerVT = getContainerForFixedLengthVector(VecVT); 5549 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5550 } 5551 SDValue Mask = 5552 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5553 // Set the vector length to only the number of elements we care about. This 5554 // avoids sliding down elements we're going to discard straight away. 5555 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5556 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5557 SDValue Slidedown = 5558 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5559 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5560 // Now we can use a cast-like subvector extract to get the result. 5561 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5562 DAG.getConstant(0, DL, XLenVT)); 5563 return DAG.getBitcast(Op.getValueType(), Slidedown); 5564 } 5565 5566 unsigned SubRegIdx, RemIdx; 5567 std::tie(SubRegIdx, RemIdx) = 5568 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5569 VecVT, SubVecVT, OrigIdx, TRI); 5570 5571 // If the Idx has been completely eliminated then this is a subvector extract 5572 // which naturally aligns to a vector register. These can easily be handled 5573 // using subregister manipulation. 5574 if (RemIdx == 0) 5575 return Op; 5576 5577 // Else we must shift our vector register directly to extract the subvector. 5578 // Do this using VSLIDEDOWN. 5579 5580 // If the vector type is an LMUL-group type, extract a subvector equal to the 5581 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5582 // instruction. 5583 MVT InterSubVT = VecVT; 5584 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5585 InterSubVT = getLMUL1VT(VecVT); 5586 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5587 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5588 } 5589 5590 // Slide this vector register down by the desired number of elements in order 5591 // to place the desired subvector starting at element 0. 5592 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5593 // For scalable vectors this must be further multiplied by vscale. 5594 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5595 5596 SDValue Mask, VL; 5597 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5598 SDValue Slidedown = 5599 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5600 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5601 5602 // Now the vector is in the right position, extract our final subvector. This 5603 // should resolve to a COPY. 5604 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5605 DAG.getConstant(0, DL, XLenVT)); 5606 5607 // We might have bitcast from a mask type: cast back to the original type if 5608 // required. 5609 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5610 } 5611 5612 // Lower step_vector to the vid instruction. Any non-identity step value must 5613 // be accounted for my manual expansion. 5614 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5615 SelectionDAG &DAG) const { 5616 SDLoc DL(Op); 5617 MVT VT = Op.getSimpleValueType(); 5618 MVT XLenVT = Subtarget.getXLenVT(); 5619 SDValue Mask, VL; 5620 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5621 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5622 uint64_t StepValImm = Op.getConstantOperandVal(0); 5623 if (StepValImm != 1) { 5624 if (isPowerOf2_64(StepValImm)) { 5625 SDValue StepVal = 5626 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5627 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5628 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5629 } else { 5630 SDValue StepVal = lowerScalarSplat( 5631 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5632 VL, VT, DL, DAG, Subtarget); 5633 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5634 } 5635 } 5636 return StepVec; 5637 } 5638 5639 // Implement vector_reverse using vrgather.vv with indices determined by 5640 // subtracting the id of each element from (VLMAX-1). This will convert 5641 // the indices like so: 5642 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5643 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5644 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5645 SelectionDAG &DAG) const { 5646 SDLoc DL(Op); 5647 MVT VecVT = Op.getSimpleValueType(); 5648 if (VecVT.getVectorElementType() == MVT::i1) { 5649 MVT WidenVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 5650 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenVT, Op.getOperand(0)); 5651 SDValue Op2 = DAG.getNode(ISD::VECTOR_REVERSE, DL, WidenVT, Op1); 5652 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Op2); 5653 } 5654 unsigned EltSize = VecVT.getScalarSizeInBits(); 5655 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5656 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 5657 unsigned MaxVLMAX = 5658 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 5659 5660 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5661 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5662 5663 // If this is SEW=8 and VLMAX is potentially more than 256, we need 5664 // to use vrgatherei16.vv. 5665 // TODO: It's also possible to use vrgatherei16.vv for other types to 5666 // decrease register width for the index calculation. 5667 if (MaxVLMAX > 256 && EltSize == 8) { 5668 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5669 // Reverse each half, then reassemble them in reverse order. 5670 // NOTE: It's also possible that after splitting that VLMAX no longer 5671 // requires vrgatherei16.vv. 5672 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5673 SDValue Lo, Hi; 5674 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5675 EVT LoVT, HiVT; 5676 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5677 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5678 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5679 // Reassemble the low and high pieces reversed. 5680 // FIXME: This is a CONCAT_VECTORS. 5681 SDValue Res = 5682 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5683 DAG.getIntPtrConstant(0, DL)); 5684 return DAG.getNode( 5685 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5686 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5687 } 5688 5689 // Just promote the int type to i16 which will double the LMUL. 5690 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5691 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5692 } 5693 5694 MVT XLenVT = Subtarget.getXLenVT(); 5695 SDValue Mask, VL; 5696 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5697 5698 // Calculate VLMAX-1 for the desired SEW. 5699 unsigned MinElts = VecVT.getVectorMinNumElements(); 5700 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5701 DAG.getConstant(MinElts, DL, XLenVT)); 5702 SDValue VLMinus1 = 5703 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5704 5705 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5706 bool IsRV32E64 = 5707 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5708 SDValue SplatVL; 5709 if (!IsRV32E64) 5710 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5711 else 5712 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5713 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5714 5715 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5716 SDValue Indices = 5717 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5718 5719 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, 5720 DAG.getUNDEF(VecVT), VL); 5721 } 5722 5723 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5724 SelectionDAG &DAG) const { 5725 SDLoc DL(Op); 5726 SDValue V1 = Op.getOperand(0); 5727 SDValue V2 = Op.getOperand(1); 5728 MVT XLenVT = Subtarget.getXLenVT(); 5729 MVT VecVT = Op.getSimpleValueType(); 5730 5731 unsigned MinElts = VecVT.getVectorMinNumElements(); 5732 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5733 DAG.getConstant(MinElts, DL, XLenVT)); 5734 5735 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5736 SDValue DownOffset, UpOffset; 5737 if (ImmValue >= 0) { 5738 // The operand is a TargetConstant, we need to rebuild it as a regular 5739 // constant. 5740 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5741 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5742 } else { 5743 // The operand is a TargetConstant, we need to rebuild it as a regular 5744 // constant rather than negating the original operand. 5745 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5746 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5747 } 5748 5749 SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG); 5750 5751 SDValue SlideDown = 5752 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5753 DownOffset, TrueMask, UpOffset); 5754 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5755 TrueMask, 5756 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 5757 } 5758 5759 SDValue 5760 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5761 SelectionDAG &DAG) const { 5762 SDLoc DL(Op); 5763 auto *Load = cast<LoadSDNode>(Op); 5764 5765 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5766 Load->getMemoryVT(), 5767 *Load->getMemOperand()) && 5768 "Expecting a correctly-aligned load"); 5769 5770 MVT VT = Op.getSimpleValueType(); 5771 MVT XLenVT = Subtarget.getXLenVT(); 5772 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5773 5774 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5775 5776 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5777 SDValue IntID = DAG.getTargetConstant( 5778 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 5779 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 5780 if (!IsMaskOp) 5781 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5782 Ops.push_back(Load->getBasePtr()); 5783 Ops.push_back(VL); 5784 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5785 SDValue NewLoad = 5786 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5787 Load->getMemoryVT(), Load->getMemOperand()); 5788 5789 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5790 return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL); 5791 } 5792 5793 SDValue 5794 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5795 SelectionDAG &DAG) const { 5796 SDLoc DL(Op); 5797 auto *Store = cast<StoreSDNode>(Op); 5798 5799 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5800 Store->getMemoryVT(), 5801 *Store->getMemOperand()) && 5802 "Expecting a correctly-aligned store"); 5803 5804 SDValue StoreVal = Store->getValue(); 5805 MVT VT = StoreVal.getSimpleValueType(); 5806 MVT XLenVT = Subtarget.getXLenVT(); 5807 5808 // If the size less than a byte, we need to pad with zeros to make a byte. 5809 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5810 VT = MVT::v8i1; 5811 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5812 DAG.getConstant(0, DL, VT), StoreVal, 5813 DAG.getIntPtrConstant(0, DL)); 5814 } 5815 5816 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5817 5818 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5819 5820 SDValue NewValue = 5821 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5822 5823 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5824 SDValue IntID = DAG.getTargetConstant( 5825 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 5826 return DAG.getMemIntrinsicNode( 5827 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 5828 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 5829 Store->getMemoryVT(), Store->getMemOperand()); 5830 } 5831 5832 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5833 SelectionDAG &DAG) const { 5834 SDLoc DL(Op); 5835 MVT VT = Op.getSimpleValueType(); 5836 5837 const auto *MemSD = cast<MemSDNode>(Op); 5838 EVT MemVT = MemSD->getMemoryVT(); 5839 MachineMemOperand *MMO = MemSD->getMemOperand(); 5840 SDValue Chain = MemSD->getChain(); 5841 SDValue BasePtr = MemSD->getBasePtr(); 5842 5843 SDValue Mask, PassThru, VL; 5844 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5845 Mask = VPLoad->getMask(); 5846 PassThru = DAG.getUNDEF(VT); 5847 VL = VPLoad->getVectorLength(); 5848 } else { 5849 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5850 Mask = MLoad->getMask(); 5851 PassThru = MLoad->getPassThru(); 5852 } 5853 5854 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5855 5856 MVT XLenVT = Subtarget.getXLenVT(); 5857 5858 MVT ContainerVT = VT; 5859 if (VT.isFixedLengthVector()) { 5860 ContainerVT = getContainerForFixedLengthVector(VT); 5861 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5862 if (!IsUnmasked) { 5863 MVT MaskVT = getMaskTypeFor(ContainerVT); 5864 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5865 } 5866 } 5867 5868 if (!VL) 5869 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5870 5871 unsigned IntID = 5872 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5873 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5874 if (IsUnmasked) 5875 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5876 else 5877 Ops.push_back(PassThru); 5878 Ops.push_back(BasePtr); 5879 if (!IsUnmasked) 5880 Ops.push_back(Mask); 5881 Ops.push_back(VL); 5882 if (!IsUnmasked) 5883 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5884 5885 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5886 5887 SDValue Result = 5888 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5889 Chain = Result.getValue(1); 5890 5891 if (VT.isFixedLengthVector()) 5892 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5893 5894 return DAG.getMergeValues({Result, Chain}, DL); 5895 } 5896 5897 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5898 SelectionDAG &DAG) const { 5899 SDLoc DL(Op); 5900 5901 const auto *MemSD = cast<MemSDNode>(Op); 5902 EVT MemVT = MemSD->getMemoryVT(); 5903 MachineMemOperand *MMO = MemSD->getMemOperand(); 5904 SDValue Chain = MemSD->getChain(); 5905 SDValue BasePtr = MemSD->getBasePtr(); 5906 SDValue Val, Mask, VL; 5907 5908 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5909 Val = VPStore->getValue(); 5910 Mask = VPStore->getMask(); 5911 VL = VPStore->getVectorLength(); 5912 } else { 5913 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5914 Val = MStore->getValue(); 5915 Mask = MStore->getMask(); 5916 } 5917 5918 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5919 5920 MVT VT = Val.getSimpleValueType(); 5921 MVT XLenVT = Subtarget.getXLenVT(); 5922 5923 MVT ContainerVT = VT; 5924 if (VT.isFixedLengthVector()) { 5925 ContainerVT = getContainerForFixedLengthVector(VT); 5926 5927 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5928 if (!IsUnmasked) { 5929 MVT MaskVT = getMaskTypeFor(ContainerVT); 5930 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5931 } 5932 } 5933 5934 if (!VL) 5935 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5936 5937 unsigned IntID = 5938 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5939 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5940 Ops.push_back(Val); 5941 Ops.push_back(BasePtr); 5942 if (!IsUnmasked) 5943 Ops.push_back(Mask); 5944 Ops.push_back(VL); 5945 5946 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5947 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5948 } 5949 5950 SDValue 5951 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5952 SelectionDAG &DAG) const { 5953 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5954 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5955 5956 MVT VT = Op.getSimpleValueType(); 5957 5958 SDValue Op1 = 5959 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5960 SDValue Op2 = 5961 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5962 5963 SDLoc DL(Op); 5964 SDValue VL = 5965 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5966 5967 MVT MaskVT = getMaskTypeFor(ContainerVT); 5968 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 5969 5970 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5971 Op.getOperand(2), Mask, VL); 5972 5973 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5974 } 5975 5976 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5977 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5978 MVT VT = Op.getSimpleValueType(); 5979 5980 if (VT.getVectorElementType() == MVT::i1) 5981 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5982 5983 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5984 } 5985 5986 SDValue 5987 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5988 SelectionDAG &DAG) const { 5989 unsigned Opc; 5990 switch (Op.getOpcode()) { 5991 default: llvm_unreachable("Unexpected opcode!"); 5992 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5993 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5994 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5995 } 5996 5997 return lowerToScalableOp(Op, DAG, Opc); 5998 } 5999 6000 // Lower vector ABS to smax(X, sub(0, X)). 6001 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 6002 SDLoc DL(Op); 6003 MVT VT = Op.getSimpleValueType(); 6004 SDValue X = Op.getOperand(0); 6005 6006 assert(VT.isFixedLengthVector() && "Unexpected type"); 6007 6008 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6009 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 6010 6011 SDValue Mask, VL; 6012 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6013 6014 SDValue SplatZero = DAG.getNode( 6015 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 6016 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 6017 SDValue NegX = 6018 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 6019 SDValue Max = 6020 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 6021 6022 return convertFromScalableVector(VT, Max, DAG, Subtarget); 6023 } 6024 6025 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 6026 SDValue Op, SelectionDAG &DAG) const { 6027 SDLoc DL(Op); 6028 MVT VT = Op.getSimpleValueType(); 6029 SDValue Mag = Op.getOperand(0); 6030 SDValue Sign = Op.getOperand(1); 6031 assert(Mag.getValueType() == Sign.getValueType() && 6032 "Can only handle COPYSIGN with matching types."); 6033 6034 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6035 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 6036 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 6037 6038 SDValue Mask, VL; 6039 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6040 6041 SDValue CopySign = 6042 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 6043 6044 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 6045 } 6046 6047 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 6048 SDValue Op, SelectionDAG &DAG) const { 6049 MVT VT = Op.getSimpleValueType(); 6050 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6051 6052 MVT I1ContainerVT = 6053 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6054 6055 SDValue CC = 6056 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 6057 SDValue Op1 = 6058 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 6059 SDValue Op2 = 6060 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 6061 6062 SDLoc DL(Op); 6063 SDValue Mask, VL; 6064 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6065 6066 SDValue Select = 6067 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 6068 6069 return convertFromScalableVector(VT, Select, DAG, Subtarget); 6070 } 6071 6072 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 6073 unsigned NewOpc, 6074 bool HasMask) const { 6075 MVT VT = Op.getSimpleValueType(); 6076 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6077 6078 // Create list of operands by converting existing ones to scalable types. 6079 SmallVector<SDValue, 6> Ops; 6080 for (const SDValue &V : Op->op_values()) { 6081 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6082 6083 // Pass through non-vector operands. 6084 if (!V.getValueType().isVector()) { 6085 Ops.push_back(V); 6086 continue; 6087 } 6088 6089 // "cast" fixed length vector to a scalable vector. 6090 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6091 "Only fixed length vectors are supported!"); 6092 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6093 } 6094 6095 SDLoc DL(Op); 6096 SDValue Mask, VL; 6097 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6098 if (HasMask) 6099 Ops.push_back(Mask); 6100 Ops.push_back(VL); 6101 6102 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6103 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6104 } 6105 6106 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6107 // * Operands of each node are assumed to be in the same order. 6108 // * The EVL operand is promoted from i32 to i64 on RV64. 6109 // * Fixed-length vectors are converted to their scalable-vector container 6110 // types. 6111 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6112 unsigned RISCVISDOpc) const { 6113 SDLoc DL(Op); 6114 MVT VT = Op.getSimpleValueType(); 6115 SmallVector<SDValue, 4> Ops; 6116 6117 for (const auto &OpIdx : enumerate(Op->ops())) { 6118 SDValue V = OpIdx.value(); 6119 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6120 // Pass through operands which aren't fixed-length vectors. 6121 if (!V.getValueType().isFixedLengthVector()) { 6122 Ops.push_back(V); 6123 continue; 6124 } 6125 // "cast" fixed length vector to a scalable vector. 6126 MVT OpVT = V.getSimpleValueType(); 6127 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6128 assert(useRVVForFixedLengthVectorVT(OpVT) && 6129 "Only fixed length vectors are supported!"); 6130 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6131 } 6132 6133 if (!VT.isFixedLengthVector()) 6134 return DAG.getNode(RISCVISDOpc, DL, VT, Ops, Op->getFlags()); 6135 6136 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6137 6138 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops, Op->getFlags()); 6139 6140 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6141 } 6142 6143 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op, 6144 SelectionDAG &DAG) const { 6145 SDLoc DL(Op); 6146 MVT VT = Op.getSimpleValueType(); 6147 6148 SDValue Src = Op.getOperand(0); 6149 // NOTE: Mask is dropped. 6150 SDValue VL = Op.getOperand(2); 6151 6152 MVT ContainerVT = VT; 6153 if (VT.isFixedLengthVector()) { 6154 ContainerVT = getContainerForFixedLengthVector(VT); 6155 MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6156 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6157 } 6158 6159 MVT XLenVT = Subtarget.getXLenVT(); 6160 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6161 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6162 DAG.getUNDEF(ContainerVT), Zero, VL); 6163 6164 SDValue SplatValue = DAG.getConstant( 6165 Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT); 6166 SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6167 DAG.getUNDEF(ContainerVT), SplatValue, VL); 6168 6169 SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src, 6170 Splat, ZeroSplat, VL); 6171 if (!VT.isFixedLengthVector()) 6172 return Result; 6173 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6174 } 6175 6176 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op, 6177 SelectionDAG &DAG) const { 6178 SDLoc DL(Op); 6179 MVT VT = Op.getSimpleValueType(); 6180 6181 SDValue Op1 = Op.getOperand(0); 6182 SDValue Op2 = Op.getOperand(1); 6183 ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 6184 // NOTE: Mask is dropped. 6185 SDValue VL = Op.getOperand(4); 6186 6187 MVT ContainerVT = VT; 6188 if (VT.isFixedLengthVector()) { 6189 ContainerVT = getContainerForFixedLengthVector(VT); 6190 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6191 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6192 } 6193 6194 SDValue Result; 6195 SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 6196 6197 switch (Condition) { 6198 default: 6199 break; 6200 // X != Y --> (X^Y) 6201 case ISD::SETNE: 6202 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6203 break; 6204 // X == Y --> ~(X^Y) 6205 case ISD::SETEQ: { 6206 SDValue Temp = 6207 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6208 Result = 6209 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL); 6210 break; 6211 } 6212 // X >s Y --> X == 0 & Y == 1 --> ~X & Y 6213 // X <u Y --> X == 0 & Y == 1 --> ~X & Y 6214 case ISD::SETGT: 6215 case ISD::SETULT: { 6216 SDValue Temp = 6217 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6218 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL); 6219 break; 6220 } 6221 // X <s Y --> X == 1 & Y == 0 --> ~Y & X 6222 // X >u Y --> X == 1 & Y == 0 --> ~Y & X 6223 case ISD::SETLT: 6224 case ISD::SETUGT: { 6225 SDValue Temp = 6226 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6227 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL); 6228 break; 6229 } 6230 // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 6231 // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 6232 case ISD::SETGE: 6233 case ISD::SETULE: { 6234 SDValue Temp = 6235 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6236 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL); 6237 break; 6238 } 6239 // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 6240 // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 6241 case ISD::SETLE: 6242 case ISD::SETUGE: { 6243 SDValue Temp = 6244 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6245 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL); 6246 break; 6247 } 6248 } 6249 6250 if (!VT.isFixedLengthVector()) 6251 return Result; 6252 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6253 } 6254 6255 // Lower Floating-Point/Integer Type-Convert VP SDNodes 6256 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG, 6257 unsigned RISCVISDOpc) const { 6258 SDLoc DL(Op); 6259 6260 SDValue Src = Op.getOperand(0); 6261 SDValue Mask = Op.getOperand(1); 6262 SDValue VL = Op.getOperand(2); 6263 6264 MVT DstVT = Op.getSimpleValueType(); 6265 MVT SrcVT = Src.getSimpleValueType(); 6266 if (DstVT.isFixedLengthVector()) { 6267 DstVT = getContainerForFixedLengthVector(DstVT); 6268 SrcVT = getContainerForFixedLengthVector(SrcVT); 6269 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6270 MVT MaskVT = getMaskTypeFor(DstVT); 6271 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6272 } 6273 6274 unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL || 6275 RISCVISDOpc == RISCVISD::FP_TO_SINT_VL) 6276 ? RISCVISD::VSEXT_VL 6277 : RISCVISD::VZEXT_VL; 6278 6279 unsigned DstEltSize = DstVT.getScalarSizeInBits(); 6280 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 6281 6282 SDValue Result; 6283 if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion. 6284 if (SrcVT.isInteger()) { 6285 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6286 6287 // Do we need to do any pre-widening before converting? 6288 if (SrcEltSize == 1) { 6289 MVT IntVT = DstVT.changeVectorElementTypeToInteger(); 6290 MVT XLenVT = Subtarget.getXLenVT(); 6291 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6292 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6293 DAG.getUNDEF(IntVT), Zero, VL); 6294 SDValue One = DAG.getConstant( 6295 RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT); 6296 SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6297 DAG.getUNDEF(IntVT), One, VL); 6298 Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat, 6299 ZeroSplat, VL); 6300 } else if (DstEltSize > (2 * SrcEltSize)) { 6301 // Widen before converting. 6302 MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2), 6303 DstVT.getVectorElementCount()); 6304 Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL); 6305 } 6306 6307 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6308 } else { 6309 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6310 "Wrong input/output vector types"); 6311 6312 // Convert f16 to f32 then convert f32 to i64. 6313 if (DstEltSize > (2 * SrcEltSize)) { 6314 assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6315 MVT InterimFVT = 6316 MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6317 Src = 6318 DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL); 6319 } 6320 6321 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6322 } 6323 } else { // Narrowing + Conversion 6324 if (SrcVT.isInteger()) { 6325 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6326 // First do a narrowing convert to an FP type half the size, then round 6327 // the FP type to a small FP type if needed. 6328 6329 MVT InterimFVT = DstVT; 6330 if (SrcEltSize > (2 * DstEltSize)) { 6331 assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!"); 6332 assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6333 InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6334 } 6335 6336 Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL); 6337 6338 if (InterimFVT != DstVT) { 6339 Src = Result; 6340 Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL); 6341 } 6342 } else { 6343 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6344 "Wrong input/output vector types"); 6345 // First do a narrowing conversion to an integer half the size, then 6346 // truncate if needed. 6347 6348 if (DstEltSize == 1) { 6349 // First convert to the same size integer, then convert to mask using 6350 // setcc. 6351 assert(SrcEltSize >= 16 && "Unexpected FP type!"); 6352 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize), 6353 DstVT.getVectorElementCount()); 6354 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6355 6356 // Compare the integer result to 0. The integer should be 0 or 1/-1, 6357 // otherwise the conversion was undefined. 6358 MVT XLenVT = Subtarget.getXLenVT(); 6359 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 6360 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT, 6361 DAG.getUNDEF(InterimIVT), SplatZero); 6362 Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero, 6363 DAG.getCondCode(ISD::SETNE), Mask, VL); 6364 } else { 6365 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6366 DstVT.getVectorElementCount()); 6367 6368 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6369 6370 while (InterimIVT != DstVT) { 6371 SrcEltSize /= 2; 6372 Src = Result; 6373 InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6374 DstVT.getVectorElementCount()); 6375 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT, 6376 Src, Mask, VL); 6377 } 6378 } 6379 } 6380 } 6381 6382 MVT VT = Op.getSimpleValueType(); 6383 if (!VT.isFixedLengthVector()) 6384 return Result; 6385 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6386 } 6387 6388 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6389 unsigned MaskOpc, 6390 unsigned VecOpc) const { 6391 MVT VT = Op.getSimpleValueType(); 6392 if (VT.getVectorElementType() != MVT::i1) 6393 return lowerVPOp(Op, DAG, VecOpc); 6394 6395 // It is safe to drop mask parameter as masked-off elements are undef. 6396 SDValue Op1 = Op->getOperand(0); 6397 SDValue Op2 = Op->getOperand(1); 6398 SDValue VL = Op->getOperand(3); 6399 6400 MVT ContainerVT = VT; 6401 const bool IsFixed = VT.isFixedLengthVector(); 6402 if (IsFixed) { 6403 ContainerVT = getContainerForFixedLengthVector(VT); 6404 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6405 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6406 } 6407 6408 SDLoc DL(Op); 6409 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6410 if (!IsFixed) 6411 return Val; 6412 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6413 } 6414 6415 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6416 // matched to a RVV indexed load. The RVV indexed load instructions only 6417 // support the "unsigned unscaled" addressing mode; indices are implicitly 6418 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6419 // signed or scaled indexing is extended to the XLEN value type and scaled 6420 // accordingly. 6421 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6422 SelectionDAG &DAG) const { 6423 SDLoc DL(Op); 6424 MVT VT = Op.getSimpleValueType(); 6425 6426 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6427 EVT MemVT = MemSD->getMemoryVT(); 6428 MachineMemOperand *MMO = MemSD->getMemOperand(); 6429 SDValue Chain = MemSD->getChain(); 6430 SDValue BasePtr = MemSD->getBasePtr(); 6431 6432 ISD::LoadExtType LoadExtType; 6433 SDValue Index, Mask, PassThru, VL; 6434 6435 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6436 Index = VPGN->getIndex(); 6437 Mask = VPGN->getMask(); 6438 PassThru = DAG.getUNDEF(VT); 6439 VL = VPGN->getVectorLength(); 6440 // VP doesn't support extending loads. 6441 LoadExtType = ISD::NON_EXTLOAD; 6442 } else { 6443 // Else it must be a MGATHER. 6444 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6445 Index = MGN->getIndex(); 6446 Mask = MGN->getMask(); 6447 PassThru = MGN->getPassThru(); 6448 LoadExtType = MGN->getExtensionType(); 6449 } 6450 6451 MVT IndexVT = Index.getSimpleValueType(); 6452 MVT XLenVT = Subtarget.getXLenVT(); 6453 6454 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6455 "Unexpected VTs!"); 6456 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6457 // Targets have to explicitly opt-in for extending vector loads. 6458 assert(LoadExtType == ISD::NON_EXTLOAD && 6459 "Unexpected extending MGATHER/VP_GATHER"); 6460 (void)LoadExtType; 6461 6462 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6463 // the selection of the masked intrinsics doesn't do this for us. 6464 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6465 6466 MVT ContainerVT = VT; 6467 if (VT.isFixedLengthVector()) { 6468 ContainerVT = getContainerForFixedLengthVector(VT); 6469 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6470 ContainerVT.getVectorElementCount()); 6471 6472 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6473 6474 if (!IsUnmasked) { 6475 MVT MaskVT = getMaskTypeFor(ContainerVT); 6476 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6477 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6478 } 6479 } 6480 6481 if (!VL) 6482 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6483 6484 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6485 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6486 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6487 VL); 6488 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6489 TrueMask, VL); 6490 } 6491 6492 unsigned IntID = 6493 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6494 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6495 if (IsUnmasked) 6496 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6497 else 6498 Ops.push_back(PassThru); 6499 Ops.push_back(BasePtr); 6500 Ops.push_back(Index); 6501 if (!IsUnmasked) 6502 Ops.push_back(Mask); 6503 Ops.push_back(VL); 6504 if (!IsUnmasked) 6505 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6506 6507 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6508 SDValue Result = 6509 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6510 Chain = Result.getValue(1); 6511 6512 if (VT.isFixedLengthVector()) 6513 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6514 6515 return DAG.getMergeValues({Result, Chain}, DL); 6516 } 6517 6518 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6519 // matched to a RVV indexed store. The RVV indexed store instructions only 6520 // support the "unsigned unscaled" addressing mode; indices are implicitly 6521 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6522 // signed or scaled indexing is extended to the XLEN value type and scaled 6523 // accordingly. 6524 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6525 SelectionDAG &DAG) const { 6526 SDLoc DL(Op); 6527 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6528 EVT MemVT = MemSD->getMemoryVT(); 6529 MachineMemOperand *MMO = MemSD->getMemOperand(); 6530 SDValue Chain = MemSD->getChain(); 6531 SDValue BasePtr = MemSD->getBasePtr(); 6532 6533 bool IsTruncatingStore = false; 6534 SDValue Index, Mask, Val, VL; 6535 6536 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6537 Index = VPSN->getIndex(); 6538 Mask = VPSN->getMask(); 6539 Val = VPSN->getValue(); 6540 VL = VPSN->getVectorLength(); 6541 // VP doesn't support truncating stores. 6542 IsTruncatingStore = false; 6543 } else { 6544 // Else it must be a MSCATTER. 6545 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6546 Index = MSN->getIndex(); 6547 Mask = MSN->getMask(); 6548 Val = MSN->getValue(); 6549 IsTruncatingStore = MSN->isTruncatingStore(); 6550 } 6551 6552 MVT VT = Val.getSimpleValueType(); 6553 MVT IndexVT = Index.getSimpleValueType(); 6554 MVT XLenVT = Subtarget.getXLenVT(); 6555 6556 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6557 "Unexpected VTs!"); 6558 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6559 // Targets have to explicitly opt-in for extending vector loads and 6560 // truncating vector stores. 6561 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6562 (void)IsTruncatingStore; 6563 6564 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6565 // the selection of the masked intrinsics doesn't do this for us. 6566 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6567 6568 MVT ContainerVT = VT; 6569 if (VT.isFixedLengthVector()) { 6570 ContainerVT = getContainerForFixedLengthVector(VT); 6571 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6572 ContainerVT.getVectorElementCount()); 6573 6574 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6575 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6576 6577 if (!IsUnmasked) { 6578 MVT MaskVT = getMaskTypeFor(ContainerVT); 6579 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6580 } 6581 } 6582 6583 if (!VL) 6584 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6585 6586 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6587 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6588 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6589 VL); 6590 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6591 TrueMask, VL); 6592 } 6593 6594 unsigned IntID = 6595 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6596 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6597 Ops.push_back(Val); 6598 Ops.push_back(BasePtr); 6599 Ops.push_back(Index); 6600 if (!IsUnmasked) 6601 Ops.push_back(Mask); 6602 Ops.push_back(VL); 6603 6604 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6605 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6606 } 6607 6608 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6609 SelectionDAG &DAG) const { 6610 const MVT XLenVT = Subtarget.getXLenVT(); 6611 SDLoc DL(Op); 6612 SDValue Chain = Op->getOperand(0); 6613 SDValue SysRegNo = DAG.getTargetConstant( 6614 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6615 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6616 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6617 6618 // Encoding used for rounding mode in RISCV differs from that used in 6619 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6620 // table, which consists of a sequence of 4-bit fields, each representing 6621 // corresponding FLT_ROUNDS mode. 6622 static const int Table = 6623 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6624 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6625 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6626 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6627 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6628 6629 SDValue Shift = 6630 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6631 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6632 DAG.getConstant(Table, DL, XLenVT), Shift); 6633 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6634 DAG.getConstant(7, DL, XLenVT)); 6635 6636 return DAG.getMergeValues({Masked, Chain}, DL); 6637 } 6638 6639 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6640 SelectionDAG &DAG) const { 6641 const MVT XLenVT = Subtarget.getXLenVT(); 6642 SDLoc DL(Op); 6643 SDValue Chain = Op->getOperand(0); 6644 SDValue RMValue = Op->getOperand(1); 6645 SDValue SysRegNo = DAG.getTargetConstant( 6646 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6647 6648 // Encoding used for rounding mode in RISCV differs from that used in 6649 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6650 // a table, which consists of a sequence of 4-bit fields, each representing 6651 // corresponding RISCV mode. 6652 static const unsigned Table = 6653 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6654 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6655 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6656 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6657 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6658 6659 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6660 DAG.getConstant(2, DL, XLenVT)); 6661 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6662 DAG.getConstant(Table, DL, XLenVT), Shift); 6663 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6664 DAG.getConstant(0x7, DL, XLenVT)); 6665 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6666 RMValue); 6667 } 6668 6669 SDValue RISCVTargetLowering::lowerEH_DWARF_CFA(SDValue Op, 6670 SelectionDAG &DAG) const { 6671 MachineFunction &MF = DAG.getMachineFunction(); 6672 6673 bool isRISCV64 = Subtarget.is64Bit(); 6674 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6675 6676 int FI = MF.getFrameInfo().CreateFixedObject(isRISCV64 ? 8 : 4, 0, false); 6677 return DAG.getFrameIndex(FI, PtrVT); 6678 } 6679 6680 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6681 switch (IntNo) { 6682 default: 6683 llvm_unreachable("Unexpected Intrinsic"); 6684 case Intrinsic::riscv_bcompress: 6685 return RISCVISD::BCOMPRESSW; 6686 case Intrinsic::riscv_bdecompress: 6687 return RISCVISD::BDECOMPRESSW; 6688 case Intrinsic::riscv_bfp: 6689 return RISCVISD::BFPW; 6690 case Intrinsic::riscv_fsl: 6691 return RISCVISD::FSLW; 6692 case Intrinsic::riscv_fsr: 6693 return RISCVISD::FSRW; 6694 } 6695 } 6696 6697 // Converts the given intrinsic to a i64 operation with any extension. 6698 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6699 unsigned IntNo) { 6700 SDLoc DL(N); 6701 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6702 // Deal with the Instruction Operands 6703 SmallVector<SDValue, 3> NewOps; 6704 for (SDValue Op : drop_begin(N->ops())) 6705 // Promote the operand to i64 type 6706 NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op)); 6707 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps); 6708 // ReplaceNodeResults requires we maintain the same type for the return value. 6709 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6710 } 6711 6712 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6713 // form of the given Opcode. 6714 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6715 switch (Opcode) { 6716 default: 6717 llvm_unreachable("Unexpected opcode"); 6718 case ISD::SHL: 6719 return RISCVISD::SLLW; 6720 case ISD::SRA: 6721 return RISCVISD::SRAW; 6722 case ISD::SRL: 6723 return RISCVISD::SRLW; 6724 case ISD::SDIV: 6725 return RISCVISD::DIVW; 6726 case ISD::UDIV: 6727 return RISCVISD::DIVUW; 6728 case ISD::UREM: 6729 return RISCVISD::REMUW; 6730 case ISD::ROTL: 6731 return RISCVISD::ROLW; 6732 case ISD::ROTR: 6733 return RISCVISD::RORW; 6734 } 6735 } 6736 6737 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6738 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6739 // otherwise be promoted to i64, making it difficult to select the 6740 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6741 // type i8/i16/i32 is lost. 6742 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6743 unsigned ExtOpc = ISD::ANY_EXTEND) { 6744 SDLoc DL(N); 6745 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6746 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6747 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6748 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6749 // ReplaceNodeResults requires we maintain the same type for the return value. 6750 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6751 } 6752 6753 // Converts the given 32-bit operation to a i64 operation with signed extension 6754 // semantic to reduce the signed extension instructions. 6755 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6756 SDLoc DL(N); 6757 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6758 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6759 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6760 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6761 DAG.getValueType(MVT::i32)); 6762 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6763 } 6764 6765 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6766 SmallVectorImpl<SDValue> &Results, 6767 SelectionDAG &DAG) const { 6768 SDLoc DL(N); 6769 switch (N->getOpcode()) { 6770 default: 6771 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6772 case ISD::STRICT_FP_TO_SINT: 6773 case ISD::STRICT_FP_TO_UINT: 6774 case ISD::FP_TO_SINT: 6775 case ISD::FP_TO_UINT: { 6776 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6777 "Unexpected custom legalisation"); 6778 bool IsStrict = N->isStrictFPOpcode(); 6779 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6780 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6781 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6782 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6783 TargetLowering::TypeSoftenFloat) { 6784 if (!isTypeLegal(Op0.getValueType())) 6785 return; 6786 if (IsStrict) { 6787 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6788 : RISCVISD::STRICT_FCVT_WU_RV64; 6789 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6790 SDValue Res = DAG.getNode( 6791 Opc, DL, VTs, N->getOperand(0), Op0, 6792 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6793 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6794 Results.push_back(Res.getValue(1)); 6795 return; 6796 } 6797 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6798 SDValue Res = 6799 DAG.getNode(Opc, DL, MVT::i64, Op0, 6800 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6801 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6802 return; 6803 } 6804 // If the FP type needs to be softened, emit a library call using the 'si' 6805 // version. If we left it to default legalization we'd end up with 'di'. If 6806 // the FP type doesn't need to be softened just let generic type 6807 // legalization promote the result type. 6808 RTLIB::Libcall LC; 6809 if (IsSigned) 6810 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6811 else 6812 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6813 MakeLibCallOptions CallOptions; 6814 EVT OpVT = Op0.getValueType(); 6815 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6816 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6817 SDValue Result; 6818 std::tie(Result, Chain) = 6819 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6820 Results.push_back(Result); 6821 if (IsStrict) 6822 Results.push_back(Chain); 6823 break; 6824 } 6825 case ISD::READCYCLECOUNTER: { 6826 assert(!Subtarget.is64Bit() && 6827 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6828 6829 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6830 SDValue RCW = 6831 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6832 6833 Results.push_back( 6834 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6835 Results.push_back(RCW.getValue(2)); 6836 break; 6837 } 6838 case ISD::MUL: { 6839 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6840 unsigned XLen = Subtarget.getXLen(); 6841 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6842 if (Size > XLen) { 6843 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6844 SDValue LHS = N->getOperand(0); 6845 SDValue RHS = N->getOperand(1); 6846 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6847 6848 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6849 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6850 // We need exactly one side to be unsigned. 6851 if (LHSIsU == RHSIsU) 6852 return; 6853 6854 auto MakeMULPair = [&](SDValue S, SDValue U) { 6855 MVT XLenVT = Subtarget.getXLenVT(); 6856 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6857 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6858 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6859 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6860 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6861 }; 6862 6863 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6864 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6865 6866 // The other operand should be signed, but still prefer MULH when 6867 // possible. 6868 if (RHSIsU && LHSIsS && !RHSIsS) 6869 Results.push_back(MakeMULPair(LHS, RHS)); 6870 else if (LHSIsU && RHSIsS && !LHSIsS) 6871 Results.push_back(MakeMULPair(RHS, LHS)); 6872 6873 return; 6874 } 6875 LLVM_FALLTHROUGH; 6876 } 6877 case ISD::ADD: 6878 case ISD::SUB: 6879 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6880 "Unexpected custom legalisation"); 6881 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6882 break; 6883 case ISD::SHL: 6884 case ISD::SRA: 6885 case ISD::SRL: 6886 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6887 "Unexpected custom legalisation"); 6888 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6889 // If we can use a BSET instruction, allow default promotion to apply. 6890 if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() && 6891 isOneConstant(N->getOperand(0))) 6892 break; 6893 Results.push_back(customLegalizeToWOp(N, DAG)); 6894 break; 6895 } 6896 6897 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6898 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6899 // shift amount. 6900 if (N->getOpcode() == ISD::SHL) { 6901 SDLoc DL(N); 6902 SDValue NewOp0 = 6903 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6904 SDValue NewOp1 = 6905 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6906 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6907 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6908 DAG.getValueType(MVT::i32)); 6909 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6910 } 6911 6912 break; 6913 case ISD::ROTL: 6914 case ISD::ROTR: 6915 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6916 "Unexpected custom legalisation"); 6917 Results.push_back(customLegalizeToWOp(N, DAG)); 6918 break; 6919 case ISD::CTTZ: 6920 case ISD::CTTZ_ZERO_UNDEF: 6921 case ISD::CTLZ: 6922 case ISD::CTLZ_ZERO_UNDEF: { 6923 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6924 "Unexpected custom legalisation"); 6925 6926 SDValue NewOp0 = 6927 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6928 bool IsCTZ = 6929 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6930 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6931 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6932 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6933 return; 6934 } 6935 case ISD::SDIV: 6936 case ISD::UDIV: 6937 case ISD::UREM: { 6938 MVT VT = N->getSimpleValueType(0); 6939 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6940 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6941 "Unexpected custom legalisation"); 6942 // Don't promote division/remainder by constant since we should expand those 6943 // to multiply by magic constant. 6944 // FIXME: What if the expansion is disabled for minsize. 6945 if (N->getOperand(1).getOpcode() == ISD::Constant) 6946 return; 6947 6948 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6949 // the upper 32 bits. For other types we need to sign or zero extend 6950 // based on the opcode. 6951 unsigned ExtOpc = ISD::ANY_EXTEND; 6952 if (VT != MVT::i32) 6953 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6954 : ISD::ZERO_EXTEND; 6955 6956 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6957 break; 6958 } 6959 case ISD::UADDO: 6960 case ISD::USUBO: { 6961 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6962 "Unexpected custom legalisation"); 6963 bool IsAdd = N->getOpcode() == ISD::UADDO; 6964 // Create an ADDW or SUBW. 6965 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6966 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6967 SDValue Res = 6968 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6969 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6970 DAG.getValueType(MVT::i32)); 6971 6972 SDValue Overflow; 6973 if (IsAdd && isOneConstant(RHS)) { 6974 // Special case uaddo X, 1 overflowed if the addition result is 0. 6975 // The general case (X + C) < C is not necessarily beneficial. Although we 6976 // reduce the live range of X, we may introduce the materialization of 6977 // constant C, especially when the setcc result is used by branch. We have 6978 // no compare with constant and branch instructions. 6979 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, 6980 DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ); 6981 } else { 6982 // Sign extend the LHS and perform an unsigned compare with the ADDW 6983 // result. Since the inputs are sign extended from i32, this is equivalent 6984 // to comparing the lower 32 bits. 6985 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6986 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6987 IsAdd ? ISD::SETULT : ISD::SETUGT); 6988 } 6989 6990 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6991 Results.push_back(Overflow); 6992 return; 6993 } 6994 case ISD::UADDSAT: 6995 case ISD::USUBSAT: { 6996 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6997 "Unexpected custom legalisation"); 6998 if (Subtarget.hasStdExtZbb()) { 6999 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 7000 // sign extend allows overflow of the lower 32 bits to be detected on 7001 // the promoted size. 7002 SDValue LHS = 7003 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 7004 SDValue RHS = 7005 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 7006 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 7007 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7008 return; 7009 } 7010 7011 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 7012 // promotion for UADDO/USUBO. 7013 Results.push_back(expandAddSubSat(N, DAG)); 7014 return; 7015 } 7016 case ISD::ABS: { 7017 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7018 "Unexpected custom legalisation"); 7019 7020 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 7021 7022 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7023 7024 // Freeze the source so we can increase it's use count. 7025 Src = DAG.getFreeze(Src); 7026 7027 // Copy sign bit to all bits using the sraiw pattern. 7028 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 7029 DAG.getValueType(MVT::i32)); 7030 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 7031 DAG.getConstant(31, DL, MVT::i64)); 7032 7033 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 7034 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 7035 7036 // NOTE: The result is only required to be anyextended, but sext is 7037 // consistent with type legalization of sub. 7038 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 7039 DAG.getValueType(MVT::i32)); 7040 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 7041 return; 7042 } 7043 case ISD::BITCAST: { 7044 EVT VT = N->getValueType(0); 7045 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 7046 SDValue Op0 = N->getOperand(0); 7047 EVT Op0VT = Op0.getValueType(); 7048 MVT XLenVT = Subtarget.getXLenVT(); 7049 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 7050 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 7051 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 7052 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 7053 Subtarget.hasStdExtF()) { 7054 SDValue FPConv = 7055 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 7056 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 7057 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 7058 isTypeLegal(Op0VT)) { 7059 // Custom-legalize bitcasts from fixed-length vector types to illegal 7060 // scalar types in order to improve codegen. Bitcast the vector to a 7061 // one-element vector type whose element type is the same as the result 7062 // type, and extract the first element. 7063 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 7064 if (isTypeLegal(BVT)) { 7065 SDValue BVec = DAG.getBitcast(BVT, Op0); 7066 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 7067 DAG.getConstant(0, DL, XLenVT))); 7068 } 7069 } 7070 break; 7071 } 7072 case RISCVISD::GREV: 7073 case RISCVISD::GORC: 7074 case RISCVISD::SHFL: { 7075 MVT VT = N->getSimpleValueType(0); 7076 MVT XLenVT = Subtarget.getXLenVT(); 7077 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) && 7078 "Unexpected custom legalisation"); 7079 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 7080 assert((Subtarget.hasStdExtZbp() || 7081 (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV && 7082 N->getConstantOperandVal(1) == 7)) && 7083 "Unexpected extension"); 7084 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7085 SDValue NewOp1 = 7086 DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1)); 7087 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1); 7088 // ReplaceNodeResults requires we maintain the same type for the return 7089 // value. 7090 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes)); 7091 break; 7092 } 7093 case ISD::BSWAP: 7094 case ISD::BITREVERSE: { 7095 MVT VT = N->getSimpleValueType(0); 7096 MVT XLenVT = Subtarget.getXLenVT(); 7097 assert((VT == MVT::i8 || VT == MVT::i16 || 7098 (VT == MVT::i32 && Subtarget.is64Bit())) && 7099 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 7100 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7101 unsigned Imm = VT.getSizeInBits() - 1; 7102 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 7103 if (N->getOpcode() == ISD::BSWAP) 7104 Imm &= ~0x7U; 7105 SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0, 7106 DAG.getConstant(Imm, DL, XLenVT)); 7107 // ReplaceNodeResults requires we maintain the same type for the return 7108 // value. 7109 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 7110 break; 7111 } 7112 case ISD::FSHL: 7113 case ISD::FSHR: { 7114 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7115 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 7116 SDValue NewOp0 = 7117 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7118 SDValue NewOp1 = 7119 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7120 SDValue NewShAmt = 7121 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7122 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 7123 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 7124 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 7125 DAG.getConstant(0x1f, DL, MVT::i64)); 7126 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 7127 // instruction use different orders. fshl will return its first operand for 7128 // shift of zero, fshr will return its second operand. fsl and fsr both 7129 // return rs1 so the ISD nodes need to have different operand orders. 7130 // Shift amount is in rs2. 7131 unsigned Opc = RISCVISD::FSLW; 7132 if (N->getOpcode() == ISD::FSHR) { 7133 std::swap(NewOp0, NewOp1); 7134 Opc = RISCVISD::FSRW; 7135 } 7136 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 7137 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 7138 break; 7139 } 7140 case ISD::EXTRACT_VECTOR_ELT: { 7141 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 7142 // type is illegal (currently only vXi64 RV32). 7143 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 7144 // transferred to the destination register. We issue two of these from the 7145 // upper- and lower- halves of the SEW-bit vector element, slid down to the 7146 // first element. 7147 SDValue Vec = N->getOperand(0); 7148 SDValue Idx = N->getOperand(1); 7149 7150 // The vector type hasn't been legalized yet so we can't issue target 7151 // specific nodes if it needs legalization. 7152 // FIXME: We would manually legalize if it's important. 7153 if (!isTypeLegal(Vec.getValueType())) 7154 return; 7155 7156 MVT VecVT = Vec.getSimpleValueType(); 7157 7158 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 7159 VecVT.getVectorElementType() == MVT::i64 && 7160 "Unexpected EXTRACT_VECTOR_ELT legalization"); 7161 7162 // If this is a fixed vector, we need to convert it to a scalable vector. 7163 MVT ContainerVT = VecVT; 7164 if (VecVT.isFixedLengthVector()) { 7165 ContainerVT = getContainerForFixedLengthVector(VecVT); 7166 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 7167 } 7168 7169 MVT XLenVT = Subtarget.getXLenVT(); 7170 7171 // Use a VL of 1 to avoid processing more elements than we need. 7172 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7173 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 7174 7175 // Unless the index is known to be 0, we must slide the vector down to get 7176 // the desired element into index 0. 7177 if (!isNullConstant(Idx)) { 7178 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 7179 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 7180 } 7181 7182 // Extract the lower XLEN bits of the correct vector element. 7183 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7184 7185 // To extract the upper XLEN bits of the vector element, shift the first 7186 // element right by 32 bits and re-extract the lower XLEN bits. 7187 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 7188 DAG.getUNDEF(ContainerVT), 7189 DAG.getConstant(32, DL, XLenVT), VL); 7190 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 7191 ThirtyTwoV, Mask, VL); 7192 7193 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7194 7195 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7196 break; 7197 } 7198 case ISD::INTRINSIC_WO_CHAIN: { 7199 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7200 switch (IntNo) { 7201 default: 7202 llvm_unreachable( 7203 "Don't know how to custom type legalize this intrinsic!"); 7204 case Intrinsic::riscv_grev: 7205 case Intrinsic::riscv_gorc: { 7206 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7207 "Unexpected custom legalisation"); 7208 SDValue NewOp1 = 7209 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7210 SDValue NewOp2 = 7211 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7212 unsigned Opc = 7213 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 7214 // If the control is a constant, promote the node by clearing any extra 7215 // bits bits in the control. isel will form greviw/gorciw if the result is 7216 // sign extended. 7217 if (isa<ConstantSDNode>(NewOp2)) { 7218 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7219 DAG.getConstant(0x1f, DL, MVT::i64)); 7220 Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 7221 } 7222 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7223 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7224 break; 7225 } 7226 case Intrinsic::riscv_bcompress: 7227 case Intrinsic::riscv_bdecompress: 7228 case Intrinsic::riscv_bfp: 7229 case Intrinsic::riscv_fsl: 7230 case Intrinsic::riscv_fsr: { 7231 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7232 "Unexpected custom legalisation"); 7233 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 7234 break; 7235 } 7236 case Intrinsic::riscv_orc_b: { 7237 // Lower to the GORCI encoding for orc.b with the operand extended. 7238 SDValue NewOp = 7239 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7240 SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp, 7241 DAG.getConstant(7, DL, MVT::i64)); 7242 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7243 return; 7244 } 7245 case Intrinsic::riscv_shfl: 7246 case Intrinsic::riscv_unshfl: { 7247 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7248 "Unexpected custom legalisation"); 7249 SDValue NewOp1 = 7250 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7251 SDValue NewOp2 = 7252 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7253 unsigned Opc = 7254 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 7255 // There is no (UN)SHFLIW. If the control word is a constant, we can use 7256 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 7257 // will be shuffled the same way as the lower 32 bit half, but the two 7258 // halves won't cross. 7259 if (isa<ConstantSDNode>(NewOp2)) { 7260 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7261 DAG.getConstant(0xf, DL, MVT::i64)); 7262 Opc = 7263 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 7264 } 7265 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7266 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7267 break; 7268 } 7269 case Intrinsic::riscv_vmv_x_s: { 7270 EVT VT = N->getValueType(0); 7271 MVT XLenVT = Subtarget.getXLenVT(); 7272 if (VT.bitsLT(XLenVT)) { 7273 // Simple case just extract using vmv.x.s and truncate. 7274 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 7275 Subtarget.getXLenVT(), N->getOperand(1)); 7276 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 7277 return; 7278 } 7279 7280 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 7281 "Unexpected custom legalization"); 7282 7283 // We need to do the move in two steps. 7284 SDValue Vec = N->getOperand(1); 7285 MVT VecVT = Vec.getSimpleValueType(); 7286 7287 // First extract the lower XLEN bits of the element. 7288 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7289 7290 // To extract the upper XLEN bits of the vector element, shift the first 7291 // element right by 32 bits and re-extract the lower XLEN bits. 7292 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7293 SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG); 7294 7295 SDValue ThirtyTwoV = 7296 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 7297 DAG.getConstant(32, DL, XLenVT), VL); 7298 SDValue LShr32 = 7299 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 7300 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7301 7302 Results.push_back( 7303 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7304 break; 7305 } 7306 } 7307 break; 7308 } 7309 case ISD::VECREDUCE_ADD: 7310 case ISD::VECREDUCE_AND: 7311 case ISD::VECREDUCE_OR: 7312 case ISD::VECREDUCE_XOR: 7313 case ISD::VECREDUCE_SMAX: 7314 case ISD::VECREDUCE_UMAX: 7315 case ISD::VECREDUCE_SMIN: 7316 case ISD::VECREDUCE_UMIN: 7317 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 7318 Results.push_back(V); 7319 break; 7320 case ISD::VP_REDUCE_ADD: 7321 case ISD::VP_REDUCE_AND: 7322 case ISD::VP_REDUCE_OR: 7323 case ISD::VP_REDUCE_XOR: 7324 case ISD::VP_REDUCE_SMAX: 7325 case ISD::VP_REDUCE_UMAX: 7326 case ISD::VP_REDUCE_SMIN: 7327 case ISD::VP_REDUCE_UMIN: 7328 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 7329 Results.push_back(V); 7330 break; 7331 case ISD::FLT_ROUNDS_: { 7332 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7333 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7334 Results.push_back(Res.getValue(0)); 7335 Results.push_back(Res.getValue(1)); 7336 break; 7337 } 7338 } 7339 } 7340 7341 // A structure to hold one of the bit-manipulation patterns below. Together, a 7342 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7343 // (or (and (shl x, 1), 0xAAAAAAAA), 7344 // (and (srl x, 1), 0x55555555)) 7345 struct RISCVBitmanipPat { 7346 SDValue Op; 7347 unsigned ShAmt; 7348 bool IsSHL; 7349 7350 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7351 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7352 } 7353 }; 7354 7355 // Matches patterns of the form 7356 // (and (shl x, C2), (C1 << C2)) 7357 // (and (srl x, C2), C1) 7358 // (shl (and x, C1), C2) 7359 // (srl (and x, (C1 << C2)), C2) 7360 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7361 // The expected masks for each shift amount are specified in BitmanipMasks where 7362 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7363 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7364 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7365 // XLen is 64. 7366 static Optional<RISCVBitmanipPat> 7367 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7368 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7369 "Unexpected number of masks"); 7370 Optional<uint64_t> Mask; 7371 // Optionally consume a mask around the shift operation. 7372 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7373 Mask = Op.getConstantOperandVal(1); 7374 Op = Op.getOperand(0); 7375 } 7376 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7377 return None; 7378 bool IsSHL = Op.getOpcode() == ISD::SHL; 7379 7380 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7381 return None; 7382 uint64_t ShAmt = Op.getConstantOperandVal(1); 7383 7384 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7385 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7386 return None; 7387 // If we don't have enough masks for 64 bit, then we must be trying to 7388 // match SHFL so we're only allowed to shift 1/4 of the width. 7389 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7390 return None; 7391 7392 SDValue Src = Op.getOperand(0); 7393 7394 // The expected mask is shifted left when the AND is found around SHL 7395 // patterns. 7396 // ((x >> 1) & 0x55555555) 7397 // ((x << 1) & 0xAAAAAAAA) 7398 bool SHLExpMask = IsSHL; 7399 7400 if (!Mask) { 7401 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7402 // the mask is all ones: consume that now. 7403 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7404 Mask = Src.getConstantOperandVal(1); 7405 Src = Src.getOperand(0); 7406 // The expected mask is now in fact shifted left for SRL, so reverse the 7407 // decision. 7408 // ((x & 0xAAAAAAAA) >> 1) 7409 // ((x & 0x55555555) << 1) 7410 SHLExpMask = !SHLExpMask; 7411 } else { 7412 // Use a default shifted mask of all-ones if there's no AND, truncated 7413 // down to the expected width. This simplifies the logic later on. 7414 Mask = maskTrailingOnes<uint64_t>(Width); 7415 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7416 } 7417 } 7418 7419 unsigned MaskIdx = Log2_32(ShAmt); 7420 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7421 7422 if (SHLExpMask) 7423 ExpMask <<= ShAmt; 7424 7425 if (Mask != ExpMask) 7426 return None; 7427 7428 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7429 } 7430 7431 // Matches any of the following bit-manipulation patterns: 7432 // (and (shl x, 1), (0x55555555 << 1)) 7433 // (and (srl x, 1), 0x55555555) 7434 // (shl (and x, 0x55555555), 1) 7435 // (srl (and x, (0x55555555 << 1)), 1) 7436 // where the shift amount and mask may vary thus: 7437 // [1] = 0x55555555 / 0xAAAAAAAA 7438 // [2] = 0x33333333 / 0xCCCCCCCC 7439 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7440 // [8] = 0x00FF00FF / 0xFF00FF00 7441 // [16] = 0x0000FFFF / 0xFFFFFFFF 7442 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7443 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7444 // These are the unshifted masks which we use to match bit-manipulation 7445 // patterns. They may be shifted left in certain circumstances. 7446 static const uint64_t BitmanipMasks[] = { 7447 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7448 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7449 7450 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7451 } 7452 7453 // Try to fold (<bop> x, (reduction.<bop> vec, start)) 7454 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) { 7455 auto BinOpToRVVReduce = [](unsigned Opc) { 7456 switch (Opc) { 7457 default: 7458 llvm_unreachable("Unhandled binary to transfrom reduction"); 7459 case ISD::ADD: 7460 return RISCVISD::VECREDUCE_ADD_VL; 7461 case ISD::UMAX: 7462 return RISCVISD::VECREDUCE_UMAX_VL; 7463 case ISD::SMAX: 7464 return RISCVISD::VECREDUCE_SMAX_VL; 7465 case ISD::UMIN: 7466 return RISCVISD::VECREDUCE_UMIN_VL; 7467 case ISD::SMIN: 7468 return RISCVISD::VECREDUCE_SMIN_VL; 7469 case ISD::AND: 7470 return RISCVISD::VECREDUCE_AND_VL; 7471 case ISD::OR: 7472 return RISCVISD::VECREDUCE_OR_VL; 7473 case ISD::XOR: 7474 return RISCVISD::VECREDUCE_XOR_VL; 7475 case ISD::FADD: 7476 return RISCVISD::VECREDUCE_FADD_VL; 7477 case ISD::FMAXNUM: 7478 return RISCVISD::VECREDUCE_FMAX_VL; 7479 case ISD::FMINNUM: 7480 return RISCVISD::VECREDUCE_FMIN_VL; 7481 } 7482 }; 7483 7484 auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) { 7485 return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7486 isNullConstant(V.getOperand(1)) && 7487 V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc); 7488 }; 7489 7490 unsigned Opc = N->getOpcode(); 7491 unsigned ReduceIdx; 7492 if (IsReduction(N->getOperand(0), Opc)) 7493 ReduceIdx = 0; 7494 else if (IsReduction(N->getOperand(1), Opc)) 7495 ReduceIdx = 1; 7496 else 7497 return SDValue(); 7498 7499 // Skip if FADD disallows reassociation but the combiner needs. 7500 if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation()) 7501 return SDValue(); 7502 7503 SDValue Extract = N->getOperand(ReduceIdx); 7504 SDValue Reduce = Extract.getOperand(0); 7505 if (!Reduce.hasOneUse()) 7506 return SDValue(); 7507 7508 SDValue ScalarV = Reduce.getOperand(2); 7509 7510 // Make sure that ScalarV is a splat with VL=1. 7511 if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL && 7512 ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL && 7513 ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL) 7514 return SDValue(); 7515 7516 if (!isOneConstant(ScalarV.getOperand(2))) 7517 return SDValue(); 7518 7519 // TODO: Deal with value other than neutral element. 7520 auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) { 7521 if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() && 7522 isNullFPConstant(V)) 7523 return true; 7524 return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(), 7525 N->getFlags()) == V; 7526 }; 7527 7528 // Check the scalar of ScalarV is neutral element 7529 if (!IsRVVNeutralElement(N, ScalarV.getOperand(1))) 7530 return SDValue(); 7531 7532 if (!ScalarV.hasOneUse()) 7533 return SDValue(); 7534 7535 EVT SplatVT = ScalarV.getValueType(); 7536 SDValue NewStart = N->getOperand(1 - ReduceIdx); 7537 unsigned SplatOpc = RISCVISD::VFMV_S_F_VL; 7538 if (SplatVT.isInteger()) { 7539 auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode()); 7540 if (!C || C->isZero() || !isInt<5>(C->getSExtValue())) 7541 SplatOpc = RISCVISD::VMV_S_X_VL; 7542 else 7543 SplatOpc = RISCVISD::VMV_V_X_VL; 7544 } 7545 7546 SDValue NewScalarV = 7547 DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart, 7548 ScalarV.getOperand(2)); 7549 SDValue NewReduce = 7550 DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(), 7551 Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV, 7552 Reduce.getOperand(3), Reduce.getOperand(4)); 7553 return DAG.getNode(Extract.getOpcode(), SDLoc(Extract), 7554 Extract.getValueType(), NewReduce, Extract.getOperand(1)); 7555 } 7556 7557 // Match the following pattern as a GREVI(W) operation 7558 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7559 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7560 const RISCVSubtarget &Subtarget) { 7561 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7562 EVT VT = Op.getValueType(); 7563 7564 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7565 auto LHS = matchGREVIPat(Op.getOperand(0)); 7566 auto RHS = matchGREVIPat(Op.getOperand(1)); 7567 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7568 SDLoc DL(Op); 7569 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7570 DAG.getConstant(LHS->ShAmt, DL, VT)); 7571 } 7572 } 7573 return SDValue(); 7574 } 7575 7576 // Matches any the following pattern as a GORCI(W) operation 7577 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7578 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7579 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7580 // Note that with the variant of 3., 7581 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7582 // the inner pattern will first be matched as GREVI and then the outer 7583 // pattern will be matched to GORC via the first rule above. 7584 // 4. (or (rotl/rotr x, bitwidth/2), x) 7585 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7586 const RISCVSubtarget &Subtarget) { 7587 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7588 EVT VT = Op.getValueType(); 7589 7590 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7591 SDLoc DL(Op); 7592 SDValue Op0 = Op.getOperand(0); 7593 SDValue Op1 = Op.getOperand(1); 7594 7595 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7596 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7597 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7598 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7599 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7600 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7601 if ((Reverse.getOpcode() == ISD::ROTL || 7602 Reverse.getOpcode() == ISD::ROTR) && 7603 Reverse.getOperand(0) == X && 7604 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7605 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7606 if (RotAmt == (VT.getSizeInBits() / 2)) 7607 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7608 DAG.getConstant(RotAmt, DL, VT)); 7609 } 7610 return SDValue(); 7611 }; 7612 7613 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7614 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7615 return V; 7616 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7617 return V; 7618 7619 // OR is commutable so canonicalize its OR operand to the left 7620 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7621 std::swap(Op0, Op1); 7622 if (Op0.getOpcode() != ISD::OR) 7623 return SDValue(); 7624 SDValue OrOp0 = Op0.getOperand(0); 7625 SDValue OrOp1 = Op0.getOperand(1); 7626 auto LHS = matchGREVIPat(OrOp0); 7627 // OR is commutable so swap the operands and try again: x might have been 7628 // on the left 7629 if (!LHS) { 7630 std::swap(OrOp0, OrOp1); 7631 LHS = matchGREVIPat(OrOp0); 7632 } 7633 auto RHS = matchGREVIPat(Op1); 7634 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7635 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7636 DAG.getConstant(LHS->ShAmt, DL, VT)); 7637 } 7638 } 7639 return SDValue(); 7640 } 7641 7642 // Matches any of the following bit-manipulation patterns: 7643 // (and (shl x, 1), (0x22222222 << 1)) 7644 // (and (srl x, 1), 0x22222222) 7645 // (shl (and x, 0x22222222), 1) 7646 // (srl (and x, (0x22222222 << 1)), 1) 7647 // where the shift amount and mask may vary thus: 7648 // [1] = 0x22222222 / 0x44444444 7649 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7650 // [4] = 0x00F000F0 / 0x0F000F00 7651 // [8] = 0x0000FF00 / 0x00FF0000 7652 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7653 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7654 // These are the unshifted masks which we use to match bit-manipulation 7655 // patterns. They may be shifted left in certain circumstances. 7656 static const uint64_t BitmanipMasks[] = { 7657 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7658 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7659 7660 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7661 } 7662 7663 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7664 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7665 const RISCVSubtarget &Subtarget) { 7666 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7667 EVT VT = Op.getValueType(); 7668 7669 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7670 return SDValue(); 7671 7672 SDValue Op0 = Op.getOperand(0); 7673 SDValue Op1 = Op.getOperand(1); 7674 7675 // Or is commutable so canonicalize the second OR to the LHS. 7676 if (Op0.getOpcode() != ISD::OR) 7677 std::swap(Op0, Op1); 7678 if (Op0.getOpcode() != ISD::OR) 7679 return SDValue(); 7680 7681 // We found an inner OR, so our operands are the operands of the inner OR 7682 // and the other operand of the outer OR. 7683 SDValue A = Op0.getOperand(0); 7684 SDValue B = Op0.getOperand(1); 7685 SDValue C = Op1; 7686 7687 auto Match1 = matchSHFLPat(A); 7688 auto Match2 = matchSHFLPat(B); 7689 7690 // If neither matched, we failed. 7691 if (!Match1 && !Match2) 7692 return SDValue(); 7693 7694 // We had at least one match. if one failed, try the remaining C operand. 7695 if (!Match1) { 7696 std::swap(A, C); 7697 Match1 = matchSHFLPat(A); 7698 if (!Match1) 7699 return SDValue(); 7700 } else if (!Match2) { 7701 std::swap(B, C); 7702 Match2 = matchSHFLPat(B); 7703 if (!Match2) 7704 return SDValue(); 7705 } 7706 assert(Match1 && Match2); 7707 7708 // Make sure our matches pair up. 7709 if (!Match1->formsPairWith(*Match2)) 7710 return SDValue(); 7711 7712 // All the remains is to make sure C is an AND with the same input, that masks 7713 // out the bits that are being shuffled. 7714 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7715 C.getOperand(0) != Match1->Op) 7716 return SDValue(); 7717 7718 uint64_t Mask = C.getConstantOperandVal(1); 7719 7720 static const uint64_t BitmanipMasks[] = { 7721 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7722 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7723 }; 7724 7725 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7726 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7727 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7728 7729 if (Mask != ExpMask) 7730 return SDValue(); 7731 7732 SDLoc DL(Op); 7733 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7734 DAG.getConstant(Match1->ShAmt, DL, VT)); 7735 } 7736 7737 // Optimize (add (shl x, c0), (shl y, c1)) -> 7738 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7739 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7740 const RISCVSubtarget &Subtarget) { 7741 // Perform this optimization only in the zba extension. 7742 if (!Subtarget.hasStdExtZba()) 7743 return SDValue(); 7744 7745 // Skip for vector types and larger types. 7746 EVT VT = N->getValueType(0); 7747 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7748 return SDValue(); 7749 7750 // The two operand nodes must be SHL and have no other use. 7751 SDValue N0 = N->getOperand(0); 7752 SDValue N1 = N->getOperand(1); 7753 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7754 !N0->hasOneUse() || !N1->hasOneUse()) 7755 return SDValue(); 7756 7757 // Check c0 and c1. 7758 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7759 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7760 if (!N0C || !N1C) 7761 return SDValue(); 7762 int64_t C0 = N0C->getSExtValue(); 7763 int64_t C1 = N1C->getSExtValue(); 7764 if (C0 <= 0 || C1 <= 0) 7765 return SDValue(); 7766 7767 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7768 int64_t Bits = std::min(C0, C1); 7769 int64_t Diff = std::abs(C0 - C1); 7770 if (Diff != 1 && Diff != 2 && Diff != 3) 7771 return SDValue(); 7772 7773 // Build nodes. 7774 SDLoc DL(N); 7775 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7776 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7777 SDValue NA0 = 7778 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7779 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7780 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7781 } 7782 7783 // Combine 7784 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7785 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7786 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7787 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7788 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7789 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7790 // The grev patterns represents BSWAP. 7791 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7792 // off the grev. 7793 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7794 const RISCVSubtarget &Subtarget) { 7795 bool IsWInstruction = 7796 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7797 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7798 IsWInstruction) && 7799 "Unexpected opcode!"); 7800 SDValue Src = N->getOperand(0); 7801 EVT VT = N->getValueType(0); 7802 SDLoc DL(N); 7803 7804 if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV) 7805 return SDValue(); 7806 7807 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7808 !isa<ConstantSDNode>(Src.getOperand(1))) 7809 return SDValue(); 7810 7811 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7812 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7813 7814 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7815 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7816 unsigned ShAmt1 = N->getConstantOperandVal(1); 7817 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7818 if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7819 return SDValue(); 7820 7821 Src = Src.getOperand(0); 7822 7823 // Toggle bit the MSB of the shift. 7824 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7825 if (CombinedShAmt == 0) 7826 return Src; 7827 7828 SDValue Res = DAG.getNode( 7829 RISCVISD::GREV, DL, VT, Src, 7830 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7831 if (!IsWInstruction) 7832 return Res; 7833 7834 // Sign extend the result to match the behavior of the rotate. This will be 7835 // selected to GREVIW in isel. 7836 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res, 7837 DAG.getValueType(MVT::i32)); 7838 } 7839 7840 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7841 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7842 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7843 // not undo itself, but they are redundant. 7844 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7845 bool IsGORC = N->getOpcode() == RISCVISD::GORC; 7846 assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode"); 7847 SDValue Src = N->getOperand(0); 7848 7849 if (Src.getOpcode() != N->getOpcode()) 7850 return SDValue(); 7851 7852 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7853 !isa<ConstantSDNode>(Src.getOperand(1))) 7854 return SDValue(); 7855 7856 unsigned ShAmt1 = N->getConstantOperandVal(1); 7857 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7858 Src = Src.getOperand(0); 7859 7860 unsigned CombinedShAmt; 7861 if (IsGORC) 7862 CombinedShAmt = ShAmt1 | ShAmt2; 7863 else 7864 CombinedShAmt = ShAmt1 ^ ShAmt2; 7865 7866 if (CombinedShAmt == 0) 7867 return Src; 7868 7869 SDLoc DL(N); 7870 return DAG.getNode( 7871 N->getOpcode(), DL, N->getValueType(0), Src, 7872 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7873 } 7874 7875 // Combine a constant select operand into its use: 7876 // 7877 // (and (select cond, -1, c), x) 7878 // -> (select cond, x, (and x, c)) [AllOnes=1] 7879 // (or (select cond, 0, c), x) 7880 // -> (select cond, x, (or x, c)) [AllOnes=0] 7881 // (xor (select cond, 0, c), x) 7882 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7883 // (add (select cond, 0, c), x) 7884 // -> (select cond, x, (add x, c)) [AllOnes=0] 7885 // (sub x, (select cond, 0, c)) 7886 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7887 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7888 SelectionDAG &DAG, bool AllOnes) { 7889 EVT VT = N->getValueType(0); 7890 7891 // Skip vectors. 7892 if (VT.isVector()) 7893 return SDValue(); 7894 7895 if ((Slct.getOpcode() != ISD::SELECT && 7896 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7897 !Slct.hasOneUse()) 7898 return SDValue(); 7899 7900 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7901 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7902 }; 7903 7904 bool SwapSelectOps; 7905 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7906 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7907 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7908 SDValue NonConstantVal; 7909 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7910 SwapSelectOps = false; 7911 NonConstantVal = FalseVal; 7912 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7913 SwapSelectOps = true; 7914 NonConstantVal = TrueVal; 7915 } else 7916 return SDValue(); 7917 7918 // Slct is now know to be the desired identity constant when CC is true. 7919 TrueVal = OtherOp; 7920 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7921 // Unless SwapSelectOps says the condition should be false. 7922 if (SwapSelectOps) 7923 std::swap(TrueVal, FalseVal); 7924 7925 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7926 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7927 {Slct.getOperand(0), Slct.getOperand(1), 7928 Slct.getOperand(2), TrueVal, FalseVal}); 7929 7930 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7931 {Slct.getOperand(0), TrueVal, FalseVal}); 7932 } 7933 7934 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7935 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7936 bool AllOnes) { 7937 SDValue N0 = N->getOperand(0); 7938 SDValue N1 = N->getOperand(1); 7939 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7940 return Result; 7941 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7942 return Result; 7943 return SDValue(); 7944 } 7945 7946 // Transform (add (mul x, c0), c1) -> 7947 // (add (mul (add x, c1/c0), c0), c1%c0). 7948 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7949 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7950 // to an infinite loop in DAGCombine if transformed. 7951 // Or transform (add (mul x, c0), c1) -> 7952 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7953 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7954 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7955 // lead to an infinite loop in DAGCombine if transformed. 7956 // Or transform (add (mul x, c0), c1) -> 7957 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7958 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7959 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7960 // lead to an infinite loop in DAGCombine if transformed. 7961 // Or transform (add (mul x, c0), c1) -> 7962 // (mul (add x, c1/c0), c0). 7963 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7964 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7965 const RISCVSubtarget &Subtarget) { 7966 // Skip for vector types and larger types. 7967 EVT VT = N->getValueType(0); 7968 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7969 return SDValue(); 7970 // The first operand node must be a MUL and has no other use. 7971 SDValue N0 = N->getOperand(0); 7972 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7973 return SDValue(); 7974 // Check if c0 and c1 match above conditions. 7975 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7976 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7977 if (!N0C || !N1C) 7978 return SDValue(); 7979 // If N0C has multiple uses it's possible one of the cases in 7980 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 7981 // in an infinite loop. 7982 if (!N0C->hasOneUse()) 7983 return SDValue(); 7984 int64_t C0 = N0C->getSExtValue(); 7985 int64_t C1 = N1C->getSExtValue(); 7986 int64_t CA, CB; 7987 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7988 return SDValue(); 7989 // Search for proper CA (non-zero) and CB that both are simm12. 7990 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7991 !isInt<12>(C0 * (C1 / C0))) { 7992 CA = C1 / C0; 7993 CB = C1 % C0; 7994 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7995 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7996 CA = C1 / C0 + 1; 7997 CB = C1 % C0 - C0; 7998 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7999 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 8000 CA = C1 / C0 - 1; 8001 CB = C1 % C0 + C0; 8002 } else 8003 return SDValue(); 8004 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 8005 SDLoc DL(N); 8006 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 8007 DAG.getConstant(CA, DL, VT)); 8008 SDValue New1 = 8009 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 8010 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 8011 } 8012 8013 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 8014 const RISCVSubtarget &Subtarget) { 8015 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 8016 return V; 8017 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 8018 return V; 8019 if (SDValue V = combineBinOpToReduce(N, DAG)) 8020 return V; 8021 // fold (add (select lhs, rhs, cc, 0, y), x) -> 8022 // (select lhs, rhs, cc, x, (add x, y)) 8023 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8024 } 8025 8026 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 8027 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 8028 // (select lhs, rhs, cc, x, (sub x, y)) 8029 SDValue N0 = N->getOperand(0); 8030 SDValue N1 = N->getOperand(1); 8031 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 8032 } 8033 8034 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG, 8035 const RISCVSubtarget &Subtarget) { 8036 SDValue N0 = N->getOperand(0); 8037 // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero 8038 // extending X. This is safe since we only need the LSB after the shift and 8039 // shift amounts larger than 31 would produce poison. If we wait until 8040 // type legalization, we'll create RISCVISD::SRLW and we can't recover it 8041 // to use a BEXT instruction. 8042 if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() && 8043 N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) && 8044 N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) && 8045 N0.hasOneUse()) { 8046 SDLoc DL(N); 8047 SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0)); 8048 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1)); 8049 SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1); 8050 SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl, 8051 DAG.getConstant(1, DL, MVT::i64)); 8052 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And); 8053 } 8054 8055 if (SDValue V = combineBinOpToReduce(N, DAG)) 8056 return V; 8057 8058 // fold (and (select lhs, rhs, cc, -1, y), x) -> 8059 // (select lhs, rhs, cc, x, (and x, y)) 8060 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 8061 } 8062 8063 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 8064 const RISCVSubtarget &Subtarget) { 8065 if (Subtarget.hasStdExtZbp()) { 8066 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 8067 return GREV; 8068 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 8069 return GORC; 8070 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 8071 return SHFL; 8072 } 8073 8074 if (SDValue V = combineBinOpToReduce(N, DAG)) 8075 return V; 8076 // fold (or (select cond, 0, y), x) -> 8077 // (select cond, x, (or x, y)) 8078 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8079 } 8080 8081 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 8082 SDValue N0 = N->getOperand(0); 8083 SDValue N1 = N->getOperand(1); 8084 8085 // fold (xor (sllw 1, x), -1) -> (rolw ~1, x) 8086 // NOTE: Assumes ROL being legal means ROLW is legal. 8087 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8088 if (N0.getOpcode() == RISCVISD::SLLW && 8089 isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) && 8090 TLI.isOperationLegal(ISD::ROTL, MVT::i64)) { 8091 SDLoc DL(N); 8092 return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64, 8093 DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1)); 8094 } 8095 8096 if (SDValue V = combineBinOpToReduce(N, DAG)) 8097 return V; 8098 // fold (xor (select cond, 0, y), x) -> 8099 // (select cond, x, (xor x, y)) 8100 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8101 } 8102 8103 static SDValue 8104 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 8105 const RISCVSubtarget &Subtarget) { 8106 SDValue Src = N->getOperand(0); 8107 EVT VT = N->getValueType(0); 8108 8109 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 8110 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8111 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 8112 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 8113 Src.getOperand(0)); 8114 8115 // Fold (i64 (sext_inreg (abs X), i32)) -> 8116 // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits. 8117 // The (sext_inreg (neg X), i32) will be selected to negw by isel. This 8118 // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user 8119 // of the (i32 (abs X)) is a sext or setcc or something else that causes type 8120 // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have 8121 // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg 8122 // may get combined into an earlier operation so we need to use 8123 // ComputeNumSignBits. 8124 // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for 8125 // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so 8126 // we can't assume that X has 33 sign bits. We must check. 8127 if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() && 8128 Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 && 8129 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 && 8130 DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) { 8131 SDLoc DL(N); 8132 SDValue Freeze = DAG.getFreeze(Src.getOperand(0)); 8133 SDValue Neg = 8134 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze); 8135 Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg, 8136 DAG.getValueType(MVT::i32)); 8137 return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg); 8138 } 8139 8140 return SDValue(); 8141 } 8142 8143 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 8144 // vwadd(u).vv/vx or vwsub(u).vv/vx. 8145 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 8146 bool Commute = false) { 8147 assert((N->getOpcode() == RISCVISD::ADD_VL || 8148 N->getOpcode() == RISCVISD::SUB_VL) && 8149 "Unexpected opcode"); 8150 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 8151 SDValue Op0 = N->getOperand(0); 8152 SDValue Op1 = N->getOperand(1); 8153 if (Commute) 8154 std::swap(Op0, Op1); 8155 8156 MVT VT = N->getSimpleValueType(0); 8157 8158 // Determine the narrow size for a widening add/sub. 8159 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8160 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8161 VT.getVectorElementCount()); 8162 8163 SDValue Mask = N->getOperand(2); 8164 SDValue VL = N->getOperand(3); 8165 8166 SDLoc DL(N); 8167 8168 // If the RHS is a sext or zext, we can form a widening op. 8169 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 8170 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 8171 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 8172 unsigned ExtOpc = Op1.getOpcode(); 8173 Op1 = Op1.getOperand(0); 8174 // Re-introduce narrower extends if needed. 8175 if (Op1.getValueType() != NarrowVT) 8176 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8177 8178 unsigned WOpc; 8179 if (ExtOpc == RISCVISD::VSEXT_VL) 8180 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 8181 else 8182 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 8183 8184 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 8185 } 8186 8187 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 8188 // sext/zext? 8189 8190 return SDValue(); 8191 } 8192 8193 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 8194 // vwsub(u).vv/vx. 8195 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 8196 SDValue Op0 = N->getOperand(0); 8197 SDValue Op1 = N->getOperand(1); 8198 SDValue Mask = N->getOperand(2); 8199 SDValue VL = N->getOperand(3); 8200 8201 MVT VT = N->getSimpleValueType(0); 8202 MVT NarrowVT = Op1.getSimpleValueType(); 8203 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 8204 8205 unsigned VOpc; 8206 switch (N->getOpcode()) { 8207 default: llvm_unreachable("Unexpected opcode"); 8208 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 8209 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 8210 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 8211 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 8212 } 8213 8214 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 8215 N->getOpcode() == RISCVISD::VWSUB_W_VL; 8216 8217 SDLoc DL(N); 8218 8219 // If the LHS is a sext or zext, we can narrow this op to the same size as 8220 // the RHS. 8221 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 8222 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 8223 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 8224 unsigned ExtOpc = Op0.getOpcode(); 8225 Op0 = Op0.getOperand(0); 8226 // Re-introduce narrower extends if needed. 8227 if (Op0.getValueType() != NarrowVT) 8228 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8229 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 8230 } 8231 8232 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 8233 N->getOpcode() == RISCVISD::VWADDU_W_VL; 8234 8235 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 8236 // to commute and use a vwadd(u).vx instead. 8237 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 8238 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 8239 Op0 = Op0.getOperand(1); 8240 8241 // See if have enough sign bits or zero bits in the scalar to use a 8242 // widening add/sub by splatting to smaller element size. 8243 unsigned EltBits = VT.getScalarSizeInBits(); 8244 unsigned ScalarBits = Op0.getValueSizeInBits(); 8245 // Make sure we're getting all element bits from the scalar register. 8246 // FIXME: Support implicit sign extension of vmv.v.x? 8247 if (ScalarBits < EltBits) 8248 return SDValue(); 8249 8250 if (IsSigned) { 8251 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 8252 return SDValue(); 8253 } else { 8254 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8255 if (!DAG.MaskedValueIsZero(Op0, Mask)) 8256 return SDValue(); 8257 } 8258 8259 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8260 DAG.getUNDEF(NarrowVT), Op0, VL); 8261 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 8262 } 8263 8264 return SDValue(); 8265 } 8266 8267 // Try to form VWMUL, VWMULU or VWMULSU. 8268 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 8269 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 8270 bool Commute) { 8271 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 8272 SDValue Op0 = N->getOperand(0); 8273 SDValue Op1 = N->getOperand(1); 8274 if (Commute) 8275 std::swap(Op0, Op1); 8276 8277 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 8278 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 8279 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 8280 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 8281 return SDValue(); 8282 8283 SDValue Mask = N->getOperand(2); 8284 SDValue VL = N->getOperand(3); 8285 8286 // Make sure the mask and VL match. 8287 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 8288 return SDValue(); 8289 8290 MVT VT = N->getSimpleValueType(0); 8291 8292 // Determine the narrow size for a widening multiply. 8293 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8294 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8295 VT.getVectorElementCount()); 8296 8297 SDLoc DL(N); 8298 8299 // See if the other operand is the same opcode. 8300 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 8301 if (!Op1.hasOneUse()) 8302 return SDValue(); 8303 8304 // Make sure the mask and VL match. 8305 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 8306 return SDValue(); 8307 8308 Op1 = Op1.getOperand(0); 8309 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 8310 // The operand is a splat of a scalar. 8311 8312 // The pasthru must be undef for tail agnostic 8313 if (!Op1.getOperand(0).isUndef()) 8314 return SDValue(); 8315 // The VL must be the same. 8316 if (Op1.getOperand(2) != VL) 8317 return SDValue(); 8318 8319 // Get the scalar value. 8320 Op1 = Op1.getOperand(1); 8321 8322 // See if have enough sign bits or zero bits in the scalar to use a 8323 // widening multiply by splatting to smaller element size. 8324 unsigned EltBits = VT.getScalarSizeInBits(); 8325 unsigned ScalarBits = Op1.getValueSizeInBits(); 8326 // Make sure we're getting all element bits from the scalar register. 8327 // FIXME: Support implicit sign extension of vmv.v.x? 8328 if (ScalarBits < EltBits) 8329 return SDValue(); 8330 8331 // If the LHS is a sign extend, try to use vwmul. 8332 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 8333 // Can use vwmul. 8334 } else { 8335 // Otherwise try to use vwmulu or vwmulsu. 8336 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8337 if (DAG.MaskedValueIsZero(Op1, Mask)) 8338 IsVWMULSU = IsSignExt; 8339 else 8340 return SDValue(); 8341 } 8342 8343 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8344 DAG.getUNDEF(NarrowVT), Op1, VL); 8345 } else 8346 return SDValue(); 8347 8348 Op0 = Op0.getOperand(0); 8349 8350 // Re-introduce narrower extends if needed. 8351 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 8352 if (Op0.getValueType() != NarrowVT) 8353 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8354 // vwmulsu requires second operand to be zero extended. 8355 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 8356 if (Op1.getValueType() != NarrowVT) 8357 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8358 8359 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 8360 if (!IsVWMULSU) 8361 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 8362 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 8363 } 8364 8365 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 8366 switch (Op.getOpcode()) { 8367 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 8368 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 8369 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 8370 case ISD::FCEIL: return RISCVFPRndMode::RUP; 8371 case ISD::FROUND: return RISCVFPRndMode::RMM; 8372 } 8373 8374 return RISCVFPRndMode::Invalid; 8375 } 8376 8377 // Fold 8378 // (fp_to_int (froundeven X)) -> fcvt X, rne 8379 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 8380 // (fp_to_int (ffloor X)) -> fcvt X, rdn 8381 // (fp_to_int (fceil X)) -> fcvt X, rup 8382 // (fp_to_int (fround X)) -> fcvt X, rmm 8383 static SDValue performFP_TO_INTCombine(SDNode *N, 8384 TargetLowering::DAGCombinerInfo &DCI, 8385 const RISCVSubtarget &Subtarget) { 8386 SelectionDAG &DAG = DCI.DAG; 8387 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8388 MVT XLenVT = Subtarget.getXLenVT(); 8389 8390 // Only handle XLen or i32 types. Other types narrower than XLen will 8391 // eventually be legalized to XLenVT. 8392 EVT VT = N->getValueType(0); 8393 if (VT != MVT::i32 && VT != XLenVT) 8394 return SDValue(); 8395 8396 SDValue Src = N->getOperand(0); 8397 8398 // Ensure the FP type is also legal. 8399 if (!TLI.isTypeLegal(Src.getValueType())) 8400 return SDValue(); 8401 8402 // Don't do this for f16 with Zfhmin and not Zfh. 8403 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8404 return SDValue(); 8405 8406 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8407 if (FRM == RISCVFPRndMode::Invalid) 8408 return SDValue(); 8409 8410 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8411 8412 unsigned Opc; 8413 if (VT == XLenVT) 8414 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8415 else 8416 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8417 8418 SDLoc DL(N); 8419 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 8420 DAG.getTargetConstant(FRM, DL, XLenVT)); 8421 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 8422 } 8423 8424 // Fold 8425 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 8426 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 8427 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8428 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8429 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8430 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8431 TargetLowering::DAGCombinerInfo &DCI, 8432 const RISCVSubtarget &Subtarget) { 8433 SelectionDAG &DAG = DCI.DAG; 8434 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8435 MVT XLenVT = Subtarget.getXLenVT(); 8436 8437 // Only handle XLen types. Other types narrower than XLen will eventually be 8438 // legalized to XLenVT. 8439 EVT DstVT = N->getValueType(0); 8440 if (DstVT != XLenVT) 8441 return SDValue(); 8442 8443 SDValue Src = N->getOperand(0); 8444 8445 // Ensure the FP type is also legal. 8446 if (!TLI.isTypeLegal(Src.getValueType())) 8447 return SDValue(); 8448 8449 // Don't do this for f16 with Zfhmin and not Zfh. 8450 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8451 return SDValue(); 8452 8453 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8454 8455 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8456 if (FRM == RISCVFPRndMode::Invalid) 8457 return SDValue(); 8458 8459 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8460 8461 unsigned Opc; 8462 if (SatVT == DstVT) 8463 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8464 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8465 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8466 else 8467 return SDValue(); 8468 // FIXME: Support other SatVTs by clamping before or after the conversion. 8469 8470 Src = Src.getOperand(0); 8471 8472 SDLoc DL(N); 8473 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8474 DAG.getTargetConstant(FRM, DL, XLenVT)); 8475 8476 // RISCV FP-to-int conversions saturate to the destination register size, but 8477 // don't produce 0 for nan. 8478 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8479 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8480 } 8481 8482 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is 8483 // smaller than XLenVT. 8484 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG, 8485 const RISCVSubtarget &Subtarget) { 8486 assert(Subtarget.hasStdExtZbkb() && "Unexpected extension"); 8487 8488 SDValue Src = N->getOperand(0); 8489 if (Src.getOpcode() != ISD::BSWAP) 8490 return SDValue(); 8491 8492 EVT VT = N->getValueType(0); 8493 if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() || 8494 !isPowerOf2_32(VT.getSizeInBits())) 8495 return SDValue(); 8496 8497 SDLoc DL(N); 8498 return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0), 8499 DAG.getConstant(7, DL, VT)); 8500 } 8501 8502 // Convert from one FMA opcode to another based on whether we are negating the 8503 // multiply result and/or the accumulator. 8504 // NOTE: Only supports RVV operations with VL. 8505 static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc) { 8506 assert((NegMul || NegAcc) && "Not negating anything?"); 8507 8508 // Negating the multiply result changes ADD<->SUB and toggles 'N'. 8509 if (NegMul) { 8510 // clang-format off 8511 switch (Opcode) { 8512 default: llvm_unreachable("Unexpected opcode"); 8513 case RISCVISD::VFMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break; 8514 case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFMADD_VL; break; 8515 case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFMSUB_VL; break; 8516 case RISCVISD::VFMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break; 8517 } 8518 // clang-format on 8519 } 8520 8521 // Negating the accumulator changes ADD<->SUB. 8522 if (NegAcc) { 8523 // clang-format off 8524 switch (Opcode) { 8525 default: llvm_unreachable("Unexpected opcode"); 8526 case RISCVISD::VFMADD_VL: Opcode = RISCVISD::VFMSUB_VL; break; 8527 case RISCVISD::VFMSUB_VL: Opcode = RISCVISD::VFMADD_VL; break; 8528 case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break; 8529 case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break; 8530 } 8531 // clang-format on 8532 } 8533 8534 return Opcode; 8535 } 8536 8537 // Combine (sra (shl X, 32), 32 - C) -> (shl (sext_inreg X, i32), C) 8538 // FIXME: Should this be a generic combine? There's a similar combine on X86. 8539 // 8540 // Also try these folds where an add or sub is in the middle. 8541 // (sra (add (shl X, 32), C1), 32 - C) -> (shl (sext_inreg (add X, C1), C) 8542 // (sra (sub C1, (shl X, 32)), 32 - C) -> (shl (sext_inreg (sub C1, X), C) 8543 static SDValue performSRACombine(SDNode *N, SelectionDAG &DAG, 8544 const RISCVSubtarget &Subtarget) { 8545 assert(N->getOpcode() == ISD::SRA && "Unexpected opcode"); 8546 8547 if (N->getValueType(0) != MVT::i64 || !Subtarget.is64Bit()) 8548 return SDValue(); 8549 8550 auto *ShAmtC = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8551 if (!ShAmtC || ShAmtC->getZExtValue() > 32) 8552 return SDValue(); 8553 8554 SDValue N0 = N->getOperand(0); 8555 8556 SDValue Shl; 8557 ConstantSDNode *AddC = nullptr; 8558 8559 // We might have an ADD or SUB between the SRA and SHL. 8560 bool IsAdd = N0.getOpcode() == ISD::ADD; 8561 if ((IsAdd || N0.getOpcode() == ISD::SUB)) { 8562 if (!N0.hasOneUse()) 8563 return SDValue(); 8564 // Other operand needs to be a constant we can modify. 8565 AddC = dyn_cast<ConstantSDNode>(N0.getOperand(IsAdd ? 1 : 0)); 8566 if (!AddC) 8567 return SDValue(); 8568 8569 // AddC needs to have at least 32 trailing zeros. 8570 if (AddC->getAPIntValue().countTrailingZeros() < 32) 8571 return SDValue(); 8572 8573 Shl = N0.getOperand(IsAdd ? 0 : 1); 8574 } else { 8575 // Not an ADD or SUB. 8576 Shl = N0; 8577 } 8578 8579 // Look for a shift left by 32. 8580 if (Shl.getOpcode() != ISD::SHL || !Shl.hasOneUse() || 8581 !isa<ConstantSDNode>(Shl.getOperand(1)) || 8582 Shl.getConstantOperandVal(1) != 32) 8583 return SDValue(); 8584 8585 SDLoc DL(N); 8586 SDValue In = Shl.getOperand(0); 8587 8588 // If we looked through an ADD or SUB, we need to rebuild it with the shifted 8589 // constant. 8590 if (AddC) { 8591 SDValue ShiftedAddC = 8592 DAG.getConstant(AddC->getAPIntValue().lshr(32), DL, MVT::i64); 8593 if (IsAdd) 8594 In = DAG.getNode(ISD::ADD, DL, MVT::i64, In, ShiftedAddC); 8595 else 8596 In = DAG.getNode(ISD::SUB, DL, MVT::i64, ShiftedAddC, In); 8597 } 8598 8599 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, In, 8600 DAG.getValueType(MVT::i32)); 8601 if (ShAmtC->getZExtValue() == 32) 8602 return SExt; 8603 8604 return DAG.getNode( 8605 ISD::SHL, DL, MVT::i64, SExt, 8606 DAG.getConstant(32 - ShAmtC->getZExtValue(), DL, MVT::i64)); 8607 } 8608 8609 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8610 DAGCombinerInfo &DCI) const { 8611 SelectionDAG &DAG = DCI.DAG; 8612 8613 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8614 // bits are demanded. N will be added to the Worklist if it was not deleted. 8615 // Caller should return SDValue(N, 0) if this returns true. 8616 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8617 SDValue Op = N->getOperand(OpNo); 8618 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8619 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8620 return false; 8621 8622 if (N->getOpcode() != ISD::DELETED_NODE) 8623 DCI.AddToWorklist(N); 8624 return true; 8625 }; 8626 8627 switch (N->getOpcode()) { 8628 default: 8629 break; 8630 case RISCVISD::SplitF64: { 8631 SDValue Op0 = N->getOperand(0); 8632 // If the input to SplitF64 is just BuildPairF64 then the operation is 8633 // redundant. Instead, use BuildPairF64's operands directly. 8634 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8635 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8636 8637 if (Op0->isUndef()) { 8638 SDValue Lo = DAG.getUNDEF(MVT::i32); 8639 SDValue Hi = DAG.getUNDEF(MVT::i32); 8640 return DCI.CombineTo(N, Lo, Hi); 8641 } 8642 8643 SDLoc DL(N); 8644 8645 // It's cheaper to materialise two 32-bit integers than to load a double 8646 // from the constant pool and transfer it to integer registers through the 8647 // stack. 8648 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8649 APInt V = C->getValueAPF().bitcastToAPInt(); 8650 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8651 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8652 return DCI.CombineTo(N, Lo, Hi); 8653 } 8654 8655 // This is a target-specific version of a DAGCombine performed in 8656 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8657 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8658 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8659 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8660 !Op0.getNode()->hasOneUse()) 8661 break; 8662 SDValue NewSplitF64 = 8663 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8664 Op0.getOperand(0)); 8665 SDValue Lo = NewSplitF64.getValue(0); 8666 SDValue Hi = NewSplitF64.getValue(1); 8667 APInt SignBit = APInt::getSignMask(32); 8668 if (Op0.getOpcode() == ISD::FNEG) { 8669 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8670 DAG.getConstant(SignBit, DL, MVT::i32)); 8671 return DCI.CombineTo(N, Lo, NewHi); 8672 } 8673 assert(Op0.getOpcode() == ISD::FABS); 8674 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8675 DAG.getConstant(~SignBit, DL, MVT::i32)); 8676 return DCI.CombineTo(N, Lo, NewHi); 8677 } 8678 case RISCVISD::SLLW: 8679 case RISCVISD::SRAW: 8680 case RISCVISD::SRLW: { 8681 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8682 if (SimplifyDemandedLowBitsHelper(0, 32) || 8683 SimplifyDemandedLowBitsHelper(1, 5)) 8684 return SDValue(N, 0); 8685 8686 break; 8687 } 8688 case ISD::ROTR: 8689 case ISD::ROTL: 8690 case RISCVISD::RORW: 8691 case RISCVISD::ROLW: { 8692 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8693 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8694 if (SimplifyDemandedLowBitsHelper(0, 32) || 8695 SimplifyDemandedLowBitsHelper(1, 5)) 8696 return SDValue(N, 0); 8697 } 8698 8699 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8700 } 8701 case RISCVISD::CLZW: 8702 case RISCVISD::CTZW: { 8703 // Only the lower 32 bits of the first operand are read 8704 if (SimplifyDemandedLowBitsHelper(0, 32)) 8705 return SDValue(N, 0); 8706 break; 8707 } 8708 case RISCVISD::GREV: 8709 case RISCVISD::GORC: { 8710 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8711 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8712 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8713 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8714 return SDValue(N, 0); 8715 8716 return combineGREVI_GORCI(N, DAG); 8717 } 8718 case RISCVISD::GREVW: 8719 case RISCVISD::GORCW: { 8720 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8721 if (SimplifyDemandedLowBitsHelper(0, 32) || 8722 SimplifyDemandedLowBitsHelper(1, 5)) 8723 return SDValue(N, 0); 8724 8725 break; 8726 } 8727 case RISCVISD::SHFL: 8728 case RISCVISD::UNSHFL: { 8729 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8730 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8731 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8732 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8733 return SDValue(N, 0); 8734 8735 break; 8736 } 8737 case RISCVISD::SHFLW: 8738 case RISCVISD::UNSHFLW: { 8739 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8740 if (SimplifyDemandedLowBitsHelper(0, 32) || 8741 SimplifyDemandedLowBitsHelper(1, 4)) 8742 return SDValue(N, 0); 8743 8744 break; 8745 } 8746 case RISCVISD::BCOMPRESSW: 8747 case RISCVISD::BDECOMPRESSW: { 8748 // Only the lower 32 bits of LHS and RHS are read. 8749 if (SimplifyDemandedLowBitsHelper(0, 32) || 8750 SimplifyDemandedLowBitsHelper(1, 32)) 8751 return SDValue(N, 0); 8752 8753 break; 8754 } 8755 case RISCVISD::FSR: 8756 case RISCVISD::FSL: 8757 case RISCVISD::FSRW: 8758 case RISCVISD::FSLW: { 8759 bool IsWInstruction = 8760 N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW; 8761 unsigned BitWidth = 8762 IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits(); 8763 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8764 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 8765 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1)) 8766 return SDValue(N, 0); 8767 8768 break; 8769 } 8770 case RISCVISD::FMV_X_ANYEXTH: 8771 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8772 SDLoc DL(N); 8773 SDValue Op0 = N->getOperand(0); 8774 MVT VT = N->getSimpleValueType(0); 8775 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8776 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8777 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8778 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8779 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8780 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8781 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8782 assert(Op0.getOperand(0).getValueType() == VT && 8783 "Unexpected value type!"); 8784 return Op0.getOperand(0); 8785 } 8786 8787 // This is a target-specific version of a DAGCombine performed in 8788 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8789 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8790 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8791 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8792 !Op0.getNode()->hasOneUse()) 8793 break; 8794 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8795 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8796 APInt SignBit = APInt::getSignMask(FPBits).sext(VT.getSizeInBits()); 8797 if (Op0.getOpcode() == ISD::FNEG) 8798 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8799 DAG.getConstant(SignBit, DL, VT)); 8800 8801 assert(Op0.getOpcode() == ISD::FABS); 8802 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8803 DAG.getConstant(~SignBit, DL, VT)); 8804 } 8805 case ISD::ADD: 8806 return performADDCombine(N, DAG, Subtarget); 8807 case ISD::SUB: 8808 return performSUBCombine(N, DAG); 8809 case ISD::AND: 8810 return performANDCombine(N, DAG, Subtarget); 8811 case ISD::OR: 8812 return performORCombine(N, DAG, Subtarget); 8813 case ISD::XOR: 8814 return performXORCombine(N, DAG); 8815 case ISD::FADD: 8816 case ISD::UMAX: 8817 case ISD::UMIN: 8818 case ISD::SMAX: 8819 case ISD::SMIN: 8820 case ISD::FMAXNUM: 8821 case ISD::FMINNUM: 8822 return combineBinOpToReduce(N, DAG); 8823 case ISD::SIGN_EXTEND_INREG: 8824 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 8825 case ISD::ZERO_EXTEND: 8826 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8827 // type legalization. This is safe because fp_to_uint produces poison if 8828 // it overflows. 8829 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8830 SDValue Src = N->getOperand(0); 8831 if (Src.getOpcode() == ISD::FP_TO_UINT && 8832 isTypeLegal(Src.getOperand(0).getValueType())) 8833 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8834 Src.getOperand(0)); 8835 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8836 isTypeLegal(Src.getOperand(1).getValueType())) { 8837 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8838 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8839 Src.getOperand(0), Src.getOperand(1)); 8840 DCI.CombineTo(N, Res); 8841 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8842 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8843 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8844 } 8845 } 8846 return SDValue(); 8847 case RISCVISD::SELECT_CC: { 8848 // Transform 8849 SDValue LHS = N->getOperand(0); 8850 SDValue RHS = N->getOperand(1); 8851 SDValue TrueV = N->getOperand(3); 8852 SDValue FalseV = N->getOperand(4); 8853 8854 // If the True and False values are the same, we don't need a select_cc. 8855 if (TrueV == FalseV) 8856 return TrueV; 8857 8858 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8859 if (!ISD::isIntEqualitySetCC(CCVal)) 8860 break; 8861 8862 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8863 // (select_cc X, Y, lt, trueV, falseV) 8864 // Sometimes the setcc is introduced after select_cc has been formed. 8865 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8866 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8867 // If we're looking for eq 0 instead of ne 0, we need to invert the 8868 // condition. 8869 bool Invert = CCVal == ISD::SETEQ; 8870 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8871 if (Invert) 8872 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8873 8874 SDLoc DL(N); 8875 RHS = LHS.getOperand(1); 8876 LHS = LHS.getOperand(0); 8877 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8878 8879 SDValue TargetCC = DAG.getCondCode(CCVal); 8880 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8881 {LHS, RHS, TargetCC, TrueV, FalseV}); 8882 } 8883 8884 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8885 // (select_cc X, Y, eq/ne, trueV, falseV) 8886 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8887 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8888 {LHS.getOperand(0), LHS.getOperand(1), 8889 N->getOperand(2), TrueV, FalseV}); 8890 // (select_cc X, 1, setne, trueV, falseV) -> 8891 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8892 // This can occur when legalizing some floating point comparisons. 8893 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8894 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8895 SDLoc DL(N); 8896 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8897 SDValue TargetCC = DAG.getCondCode(CCVal); 8898 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8899 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8900 {LHS, RHS, TargetCC, TrueV, FalseV}); 8901 } 8902 8903 break; 8904 } 8905 case RISCVISD::BR_CC: { 8906 SDValue LHS = N->getOperand(1); 8907 SDValue RHS = N->getOperand(2); 8908 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8909 if (!ISD::isIntEqualitySetCC(CCVal)) 8910 break; 8911 8912 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8913 // (br_cc X, Y, lt, dest) 8914 // Sometimes the setcc is introduced after br_cc has been formed. 8915 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8916 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8917 // If we're looking for eq 0 instead of ne 0, we need to invert the 8918 // condition. 8919 bool Invert = CCVal == ISD::SETEQ; 8920 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8921 if (Invert) 8922 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8923 8924 SDLoc DL(N); 8925 RHS = LHS.getOperand(1); 8926 LHS = LHS.getOperand(0); 8927 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8928 8929 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8930 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8931 N->getOperand(4)); 8932 } 8933 8934 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8935 // (br_cc X, Y, eq/ne, trueV, falseV) 8936 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8937 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8938 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8939 N->getOperand(3), N->getOperand(4)); 8940 8941 // (br_cc X, 1, setne, br_cc) -> 8942 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8943 // This can occur when legalizing some floating point comparisons. 8944 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8945 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8946 SDLoc DL(N); 8947 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8948 SDValue TargetCC = DAG.getCondCode(CCVal); 8949 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8950 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8951 N->getOperand(0), LHS, RHS, TargetCC, 8952 N->getOperand(4)); 8953 } 8954 break; 8955 } 8956 case ISD::BITREVERSE: 8957 return performBITREVERSECombine(N, DAG, Subtarget); 8958 case ISD::FP_TO_SINT: 8959 case ISD::FP_TO_UINT: 8960 return performFP_TO_INTCombine(N, DCI, Subtarget); 8961 case ISD::FP_TO_SINT_SAT: 8962 case ISD::FP_TO_UINT_SAT: 8963 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8964 case ISD::FCOPYSIGN: { 8965 EVT VT = N->getValueType(0); 8966 if (!VT.isVector()) 8967 break; 8968 // There is a form of VFSGNJ which injects the negated sign of its second 8969 // operand. Try and bubble any FNEG up after the extend/round to produce 8970 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8971 // TRUNC=1. 8972 SDValue In2 = N->getOperand(1); 8973 // Avoid cases where the extend/round has multiple uses, as duplicating 8974 // those is typically more expensive than removing a fneg. 8975 if (!In2.hasOneUse()) 8976 break; 8977 if (In2.getOpcode() != ISD::FP_EXTEND && 8978 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8979 break; 8980 In2 = In2.getOperand(0); 8981 if (In2.getOpcode() != ISD::FNEG) 8982 break; 8983 SDLoc DL(N); 8984 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8985 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8986 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8987 } 8988 case ISD::MGATHER: 8989 case ISD::MSCATTER: 8990 case ISD::VP_GATHER: 8991 case ISD::VP_SCATTER: { 8992 if (!DCI.isBeforeLegalize()) 8993 break; 8994 SDValue Index, ScaleOp; 8995 bool IsIndexScaled = false; 8996 bool IsIndexSigned = false; 8997 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8998 Index = VPGSN->getIndex(); 8999 ScaleOp = VPGSN->getScale(); 9000 IsIndexScaled = VPGSN->isIndexScaled(); 9001 IsIndexSigned = VPGSN->isIndexSigned(); 9002 } else { 9003 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 9004 Index = MGSN->getIndex(); 9005 ScaleOp = MGSN->getScale(); 9006 IsIndexScaled = MGSN->isIndexScaled(); 9007 IsIndexSigned = MGSN->isIndexSigned(); 9008 } 9009 EVT IndexVT = Index.getValueType(); 9010 MVT XLenVT = Subtarget.getXLenVT(); 9011 // RISCV indexed loads only support the "unsigned unscaled" addressing 9012 // mode, so anything else must be manually legalized. 9013 bool NeedsIdxLegalization = 9014 IsIndexScaled || 9015 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 9016 if (!NeedsIdxLegalization) 9017 break; 9018 9019 SDLoc DL(N); 9020 9021 // Any index legalization should first promote to XLenVT, so we don't lose 9022 // bits when scaling. This may create an illegal index type so we let 9023 // LLVM's legalization take care of the splitting. 9024 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 9025 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 9026 IndexVT = IndexVT.changeVectorElementType(XLenVT); 9027 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 9028 DL, IndexVT, Index); 9029 } 9030 9031 if (IsIndexScaled) { 9032 // Manually scale the indices. 9033 // TODO: Sanitize the scale operand here? 9034 // TODO: For VP nodes, should we use VP_SHL here? 9035 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 9036 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 9037 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 9038 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 9039 ScaleOp = DAG.getTargetConstant(1, DL, ScaleOp.getValueType()); 9040 } 9041 9042 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_SCALED; 9043 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 9044 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 9045 {VPGN->getChain(), VPGN->getBasePtr(), Index, 9046 ScaleOp, VPGN->getMask(), 9047 VPGN->getVectorLength()}, 9048 VPGN->getMemOperand(), NewIndexTy); 9049 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 9050 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 9051 {VPSN->getChain(), VPSN->getValue(), 9052 VPSN->getBasePtr(), Index, ScaleOp, 9053 VPSN->getMask(), VPSN->getVectorLength()}, 9054 VPSN->getMemOperand(), NewIndexTy); 9055 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 9056 return DAG.getMaskedGather( 9057 N->getVTList(), MGN->getMemoryVT(), DL, 9058 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 9059 MGN->getBasePtr(), Index, ScaleOp}, 9060 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 9061 const auto *MSN = cast<MaskedScatterSDNode>(N); 9062 return DAG.getMaskedScatter( 9063 N->getVTList(), MSN->getMemoryVT(), DL, 9064 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 9065 Index, ScaleOp}, 9066 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 9067 } 9068 case RISCVISD::SRA_VL: 9069 case RISCVISD::SRL_VL: 9070 case RISCVISD::SHL_VL: { 9071 SDValue ShAmt = N->getOperand(1); 9072 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 9073 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 9074 SDLoc DL(N); 9075 SDValue VL = N->getOperand(3); 9076 EVT VT = N->getValueType(0); 9077 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 9078 ShAmt.getOperand(1), VL); 9079 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 9080 N->getOperand(2), N->getOperand(3)); 9081 } 9082 break; 9083 } 9084 case ISD::SRA: 9085 if (SDValue V = performSRACombine(N, DAG, Subtarget)) 9086 return V; 9087 LLVM_FALLTHROUGH; 9088 case ISD::SRL: 9089 case ISD::SHL: { 9090 SDValue ShAmt = N->getOperand(1); 9091 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 9092 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 9093 SDLoc DL(N); 9094 EVT VT = N->getValueType(0); 9095 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 9096 ShAmt.getOperand(1), 9097 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 9098 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 9099 } 9100 break; 9101 } 9102 case RISCVISD::ADD_VL: 9103 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 9104 return V; 9105 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 9106 case RISCVISD::SUB_VL: 9107 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 9108 case RISCVISD::VWADD_W_VL: 9109 case RISCVISD::VWADDU_W_VL: 9110 case RISCVISD::VWSUB_W_VL: 9111 case RISCVISD::VWSUBU_W_VL: 9112 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 9113 case RISCVISD::MUL_VL: 9114 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 9115 return V; 9116 // Mul is commutative. 9117 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 9118 case RISCVISD::VFMADD_VL: 9119 case RISCVISD::VFNMADD_VL: 9120 case RISCVISD::VFMSUB_VL: 9121 case RISCVISD::VFNMSUB_VL: { 9122 // Fold FNEG_VL into FMA opcodes. 9123 SDValue A = N->getOperand(0); 9124 SDValue B = N->getOperand(1); 9125 SDValue C = N->getOperand(2); 9126 SDValue Mask = N->getOperand(3); 9127 SDValue VL = N->getOperand(4); 9128 9129 auto invertIfNegative = [&Mask, &VL](SDValue &V) { 9130 if (V.getOpcode() == RISCVISD::FNEG_VL && V.getOperand(1) == Mask && 9131 V.getOperand(2) == VL) { 9132 // Return the negated input. 9133 V = V.getOperand(0); 9134 return true; 9135 } 9136 9137 return false; 9138 }; 9139 9140 bool NegA = invertIfNegative(A); 9141 bool NegB = invertIfNegative(B); 9142 bool NegC = invertIfNegative(C); 9143 9144 // If no operands are negated, we're done. 9145 if (!NegA && !NegB && !NegC) 9146 return SDValue(); 9147 9148 unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC); 9149 return DAG.getNode(NewOpcode, SDLoc(N), N->getValueType(0), A, B, C, Mask, 9150 VL); 9151 } 9152 case ISD::STORE: { 9153 auto *Store = cast<StoreSDNode>(N); 9154 SDValue Val = Store->getValue(); 9155 // Combine store of vmv.x.s to vse with VL of 1. 9156 // FIXME: Support FP. 9157 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 9158 SDValue Src = Val.getOperand(0); 9159 EVT VecVT = Src.getValueType(); 9160 EVT MemVT = Store->getMemoryVT(); 9161 // The memory VT and the element type must match. 9162 if (VecVT.getVectorElementType() == MemVT) { 9163 SDLoc DL(N); 9164 MVT MaskVT = getMaskTypeFor(VecVT); 9165 return DAG.getStoreVP( 9166 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 9167 DAG.getConstant(1, DL, MaskVT), 9168 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 9169 Store->getMemOperand(), Store->getAddressingMode(), 9170 Store->isTruncatingStore(), /*IsCompress*/ false); 9171 } 9172 } 9173 9174 break; 9175 } 9176 case ISD::SPLAT_VECTOR: { 9177 EVT VT = N->getValueType(0); 9178 // Only perform this combine on legal MVT types. 9179 if (!isTypeLegal(VT)) 9180 break; 9181 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 9182 DAG, Subtarget)) 9183 return Gather; 9184 break; 9185 } 9186 case RISCVISD::VMV_V_X_VL: { 9187 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 9188 // scalar input. 9189 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 9190 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 9191 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 9192 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 9193 return SDValue(N, 0); 9194 9195 break; 9196 } 9197 case ISD::INTRINSIC_WO_CHAIN: { 9198 unsigned IntNo = N->getConstantOperandVal(0); 9199 switch (IntNo) { 9200 // By default we do not combine any intrinsic. 9201 default: 9202 return SDValue(); 9203 case Intrinsic::riscv_vcpop: 9204 case Intrinsic::riscv_vcpop_mask: 9205 case Intrinsic::riscv_vfirst: 9206 case Intrinsic::riscv_vfirst_mask: { 9207 SDValue VL = N->getOperand(2); 9208 if (IntNo == Intrinsic::riscv_vcpop_mask || 9209 IntNo == Intrinsic::riscv_vfirst_mask) 9210 VL = N->getOperand(3); 9211 if (!isNullConstant(VL)) 9212 return SDValue(); 9213 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 9214 SDLoc DL(N); 9215 EVT VT = N->getValueType(0); 9216 if (IntNo == Intrinsic::riscv_vfirst || 9217 IntNo == Intrinsic::riscv_vfirst_mask) 9218 return DAG.getConstant(-1, DL, VT); 9219 return DAG.getConstant(0, DL, VT); 9220 } 9221 } 9222 } 9223 case ISD::BITCAST: { 9224 assert(Subtarget.useRVVForFixedLengthVectors()); 9225 SDValue N0 = N->getOperand(0); 9226 EVT VT = N->getValueType(0); 9227 EVT SrcVT = N0.getValueType(); 9228 // If this is a bitcast between a MVT::v4i1/v2i1/v1i1 and an illegal integer 9229 // type, widen both sides to avoid a trip through memory. 9230 if ((SrcVT == MVT::v1i1 || SrcVT == MVT::v2i1 || SrcVT == MVT::v4i1) && 9231 VT.isScalarInteger()) { 9232 unsigned NumConcats = 8 / SrcVT.getVectorNumElements(); 9233 SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT)); 9234 Ops[0] = N0; 9235 SDLoc DL(N); 9236 N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i1, Ops); 9237 N0 = DAG.getBitcast(MVT::i8, N0); 9238 return DAG.getNode(ISD::TRUNCATE, DL, VT, N0); 9239 } 9240 9241 return SDValue(); 9242 } 9243 } 9244 9245 return SDValue(); 9246 } 9247 9248 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 9249 const SDNode *N, CombineLevel Level) const { 9250 // The following folds are only desirable if `(OP _, c1 << c2)` can be 9251 // materialised in fewer instructions than `(OP _, c1)`: 9252 // 9253 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 9254 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 9255 SDValue N0 = N->getOperand(0); 9256 EVT Ty = N0.getValueType(); 9257 if (Ty.isScalarInteger() && 9258 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 9259 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 9260 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9261 if (C1 && C2) { 9262 const APInt &C1Int = C1->getAPIntValue(); 9263 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 9264 9265 // We can materialise `c1 << c2` into an add immediate, so it's "free", 9266 // and the combine should happen, to potentially allow further combines 9267 // later. 9268 if (ShiftedC1Int.getMinSignedBits() <= 64 && 9269 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 9270 return true; 9271 9272 // We can materialise `c1` in an add immediate, so it's "free", and the 9273 // combine should be prevented. 9274 if (C1Int.getMinSignedBits() <= 64 && 9275 isLegalAddImmediate(C1Int.getSExtValue())) 9276 return false; 9277 9278 // Neither constant will fit into an immediate, so find materialisation 9279 // costs. 9280 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 9281 Subtarget.getFeatureBits(), 9282 /*CompressionCost*/true); 9283 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 9284 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 9285 /*CompressionCost*/true); 9286 9287 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 9288 // combine should be prevented. 9289 if (C1Cost < ShiftedC1Cost) 9290 return false; 9291 } 9292 } 9293 return true; 9294 } 9295 9296 bool RISCVTargetLowering::targetShrinkDemandedConstant( 9297 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 9298 TargetLoweringOpt &TLO) const { 9299 // Delay this optimization as late as possible. 9300 if (!TLO.LegalOps) 9301 return false; 9302 9303 EVT VT = Op.getValueType(); 9304 if (VT.isVector()) 9305 return false; 9306 9307 // Only handle AND for now. 9308 if (Op.getOpcode() != ISD::AND) 9309 return false; 9310 9311 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 9312 if (!C) 9313 return false; 9314 9315 const APInt &Mask = C->getAPIntValue(); 9316 9317 // Clear all non-demanded bits initially. 9318 APInt ShrunkMask = Mask & DemandedBits; 9319 9320 // Try to make a smaller immediate by setting undemanded bits. 9321 9322 APInt ExpandedMask = Mask | ~DemandedBits; 9323 9324 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 9325 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 9326 }; 9327 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 9328 if (NewMask == Mask) 9329 return true; 9330 SDLoc DL(Op); 9331 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 9332 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 9333 return TLO.CombineTo(Op, NewOp); 9334 }; 9335 9336 // If the shrunk mask fits in sign extended 12 bits, let the target 9337 // independent code apply it. 9338 if (ShrunkMask.isSignedIntN(12)) 9339 return false; 9340 9341 // Preserve (and X, 0xffff) when zext.h is supported. 9342 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 9343 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 9344 if (IsLegalMask(NewMask)) 9345 return UseMask(NewMask); 9346 } 9347 9348 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 9349 if (VT == MVT::i64) { 9350 APInt NewMask = APInt(64, 0xffffffff); 9351 if (IsLegalMask(NewMask)) 9352 return UseMask(NewMask); 9353 } 9354 9355 // For the remaining optimizations, we need to be able to make a negative 9356 // number through a combination of mask and undemanded bits. 9357 if (!ExpandedMask.isNegative()) 9358 return false; 9359 9360 // What is the fewest number of bits we need to represent the negative number. 9361 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 9362 9363 // Try to make a 12 bit negative immediate. If that fails try to make a 32 9364 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 9365 APInt NewMask = ShrunkMask; 9366 if (MinSignedBits <= 12) 9367 NewMask.setBitsFrom(11); 9368 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 9369 NewMask.setBitsFrom(31); 9370 else 9371 return false; 9372 9373 // Check that our new mask is a subset of the demanded mask. 9374 assert(IsLegalMask(NewMask)); 9375 return UseMask(NewMask); 9376 } 9377 9378 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) { 9379 static const uint64_t GREVMasks[] = { 9380 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 9381 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 9382 9383 for (unsigned Stage = 0; Stage != 6; ++Stage) { 9384 unsigned Shift = 1 << Stage; 9385 if (ShAmt & Shift) { 9386 uint64_t Mask = GREVMasks[Stage]; 9387 uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask); 9388 if (IsGORC) 9389 Res |= x; 9390 x = Res; 9391 } 9392 } 9393 9394 return x; 9395 } 9396 9397 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 9398 KnownBits &Known, 9399 const APInt &DemandedElts, 9400 const SelectionDAG &DAG, 9401 unsigned Depth) const { 9402 unsigned BitWidth = Known.getBitWidth(); 9403 unsigned Opc = Op.getOpcode(); 9404 assert((Opc >= ISD::BUILTIN_OP_END || 9405 Opc == ISD::INTRINSIC_WO_CHAIN || 9406 Opc == ISD::INTRINSIC_W_CHAIN || 9407 Opc == ISD::INTRINSIC_VOID) && 9408 "Should use MaskedValueIsZero if you don't know whether Op" 9409 " is a target node!"); 9410 9411 Known.resetAll(); 9412 switch (Opc) { 9413 default: break; 9414 case RISCVISD::SELECT_CC: { 9415 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 9416 // If we don't know any bits, early out. 9417 if (Known.isUnknown()) 9418 break; 9419 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 9420 9421 // Only known if known in both the LHS and RHS. 9422 Known = KnownBits::commonBits(Known, Known2); 9423 break; 9424 } 9425 case RISCVISD::REMUW: { 9426 KnownBits Known2; 9427 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9428 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9429 // We only care about the lower 32 bits. 9430 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 9431 // Restore the original width by sign extending. 9432 Known = Known.sext(BitWidth); 9433 break; 9434 } 9435 case RISCVISD::DIVUW: { 9436 KnownBits Known2; 9437 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9438 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9439 // We only care about the lower 32 bits. 9440 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 9441 // Restore the original width by sign extending. 9442 Known = Known.sext(BitWidth); 9443 break; 9444 } 9445 case RISCVISD::CTZW: { 9446 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9447 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 9448 unsigned LowBits = Log2_32(PossibleTZ) + 1; 9449 Known.Zero.setBitsFrom(LowBits); 9450 break; 9451 } 9452 case RISCVISD::CLZW: { 9453 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9454 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 9455 unsigned LowBits = Log2_32(PossibleLZ) + 1; 9456 Known.Zero.setBitsFrom(LowBits); 9457 break; 9458 } 9459 case RISCVISD::GREV: 9460 case RISCVISD::GORC: { 9461 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 9462 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9463 unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1); 9464 bool IsGORC = Op.getOpcode() == RISCVISD::GORC; 9465 // To compute zeros, we need to invert the value and invert it back after. 9466 Known.Zero = 9467 ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC); 9468 Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC); 9469 } 9470 break; 9471 } 9472 case RISCVISD::READ_VLENB: { 9473 // We can use the minimum and maximum VLEN values to bound VLENB. We 9474 // know VLEN must be a power of two. 9475 const unsigned MinVLenB = Subtarget.getRealMinVLen() / 8; 9476 const unsigned MaxVLenB = Subtarget.getRealMaxVLen() / 8; 9477 assert(MinVLenB > 0 && "READ_VLENB without vector extension enabled?"); 9478 Known.Zero.setLowBits(Log2_32(MinVLenB)); 9479 Known.Zero.setBitsFrom(Log2_32(MaxVLenB)+1); 9480 if (MaxVLenB == MinVLenB) 9481 Known.One.setBit(Log2_32(MinVLenB)); 9482 break; 9483 } 9484 case ISD::INTRINSIC_W_CHAIN: 9485 case ISD::INTRINSIC_WO_CHAIN: { 9486 unsigned IntNo = 9487 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 9488 switch (IntNo) { 9489 default: 9490 // We can't do anything for most intrinsics. 9491 break; 9492 case Intrinsic::riscv_vsetvli: 9493 case Intrinsic::riscv_vsetvlimax: 9494 case Intrinsic::riscv_vsetvli_opt: 9495 case Intrinsic::riscv_vsetvlimax_opt: 9496 // Assume that VL output is positive and would fit in an int32_t. 9497 // TODO: VLEN might be capped at 16 bits in a future V spec update. 9498 if (BitWidth >= 32) 9499 Known.Zero.setBitsFrom(31); 9500 break; 9501 } 9502 break; 9503 } 9504 } 9505 } 9506 9507 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 9508 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 9509 unsigned Depth) const { 9510 switch (Op.getOpcode()) { 9511 default: 9512 break; 9513 case RISCVISD::SELECT_CC: { 9514 unsigned Tmp = 9515 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 9516 if (Tmp == 1) return 1; // Early out. 9517 unsigned Tmp2 = 9518 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 9519 return std::min(Tmp, Tmp2); 9520 } 9521 case RISCVISD::SLLW: 9522 case RISCVISD::SRAW: 9523 case RISCVISD::SRLW: 9524 case RISCVISD::DIVW: 9525 case RISCVISD::DIVUW: 9526 case RISCVISD::REMUW: 9527 case RISCVISD::ROLW: 9528 case RISCVISD::RORW: 9529 case RISCVISD::GREVW: 9530 case RISCVISD::GORCW: 9531 case RISCVISD::FSLW: 9532 case RISCVISD::FSRW: 9533 case RISCVISD::SHFLW: 9534 case RISCVISD::UNSHFLW: 9535 case RISCVISD::BCOMPRESSW: 9536 case RISCVISD::BDECOMPRESSW: 9537 case RISCVISD::BFPW: 9538 case RISCVISD::FCVT_W_RV64: 9539 case RISCVISD::FCVT_WU_RV64: 9540 case RISCVISD::STRICT_FCVT_W_RV64: 9541 case RISCVISD::STRICT_FCVT_WU_RV64: 9542 // TODO: As the result is sign-extended, this is conservatively correct. A 9543 // more precise answer could be calculated for SRAW depending on known 9544 // bits in the shift amount. 9545 return 33; 9546 case RISCVISD::SHFL: 9547 case RISCVISD::UNSHFL: { 9548 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 9549 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 9550 // will stay within the upper 32 bits. If there were more than 32 sign bits 9551 // before there will be at least 33 sign bits after. 9552 if (Op.getValueType() == MVT::i64 && 9553 isa<ConstantSDNode>(Op.getOperand(1)) && 9554 (Op.getConstantOperandVal(1) & 0x10) == 0) { 9555 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 9556 if (Tmp > 32) 9557 return 33; 9558 } 9559 break; 9560 } 9561 case RISCVISD::VMV_X_S: { 9562 // The number of sign bits of the scalar result is computed by obtaining the 9563 // element type of the input vector operand, subtracting its width from the 9564 // XLEN, and then adding one (sign bit within the element type). If the 9565 // element type is wider than XLen, the least-significant XLEN bits are 9566 // taken. 9567 unsigned XLen = Subtarget.getXLen(); 9568 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 9569 if (EltBits <= XLen) 9570 return XLen - EltBits + 1; 9571 break; 9572 } 9573 } 9574 9575 return 1; 9576 } 9577 9578 const Constant * 9579 RISCVTargetLowering::getTargetConstantFromLoad(LoadSDNode *Ld) const { 9580 assert(Ld && "Unexpected null LoadSDNode"); 9581 if (!ISD::isNormalLoad(Ld)) 9582 return nullptr; 9583 9584 SDValue Ptr = Ld->getBasePtr(); 9585 9586 // Only constant pools with no offset are supported. 9587 auto GetSupportedConstantPool = [](SDValue Ptr) -> ConstantPoolSDNode * { 9588 auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr); 9589 if (!CNode || CNode->isMachineConstantPoolEntry() || 9590 CNode->getOffset() != 0) 9591 return nullptr; 9592 9593 return CNode; 9594 }; 9595 9596 // Simple case, LLA. 9597 if (Ptr.getOpcode() == RISCVISD::LLA) { 9598 auto *CNode = GetSupportedConstantPool(Ptr); 9599 if (!CNode || CNode->getTargetFlags() != 0) 9600 return nullptr; 9601 9602 return CNode->getConstVal(); 9603 } 9604 9605 // Look for a HI and ADD_LO pair. 9606 if (Ptr.getOpcode() != RISCVISD::ADD_LO || 9607 Ptr.getOperand(0).getOpcode() != RISCVISD::HI) 9608 return nullptr; 9609 9610 auto *CNodeLo = GetSupportedConstantPool(Ptr.getOperand(1)); 9611 auto *CNodeHi = GetSupportedConstantPool(Ptr.getOperand(0).getOperand(0)); 9612 9613 if (!CNodeLo || CNodeLo->getTargetFlags() != RISCVII::MO_LO || 9614 !CNodeHi || CNodeHi->getTargetFlags() != RISCVII::MO_HI) 9615 return nullptr; 9616 9617 if (CNodeLo->getConstVal() != CNodeHi->getConstVal()) 9618 return nullptr; 9619 9620 return CNodeLo->getConstVal(); 9621 } 9622 9623 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 9624 MachineBasicBlock *BB) { 9625 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 9626 9627 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 9628 // Should the count have wrapped while it was being read, we need to try 9629 // again. 9630 // ... 9631 // read: 9632 // rdcycleh x3 # load high word of cycle 9633 // rdcycle x2 # load low word of cycle 9634 // rdcycleh x4 # load high word of cycle 9635 // bne x3, x4, read # check if high word reads match, otherwise try again 9636 // ... 9637 9638 MachineFunction &MF = *BB->getParent(); 9639 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9640 MachineFunction::iterator It = ++BB->getIterator(); 9641 9642 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9643 MF.insert(It, LoopMBB); 9644 9645 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9646 MF.insert(It, DoneMBB); 9647 9648 // Transfer the remainder of BB and its successor edges to DoneMBB. 9649 DoneMBB->splice(DoneMBB->begin(), BB, 9650 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9651 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 9652 9653 BB->addSuccessor(LoopMBB); 9654 9655 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9656 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9657 Register LoReg = MI.getOperand(0).getReg(); 9658 Register HiReg = MI.getOperand(1).getReg(); 9659 DebugLoc DL = MI.getDebugLoc(); 9660 9661 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 9662 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 9663 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9664 .addReg(RISCV::X0); 9665 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 9666 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 9667 .addReg(RISCV::X0); 9668 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 9669 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9670 .addReg(RISCV::X0); 9671 9672 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 9673 .addReg(HiReg) 9674 .addReg(ReadAgainReg) 9675 .addMBB(LoopMBB); 9676 9677 LoopMBB->addSuccessor(LoopMBB); 9678 LoopMBB->addSuccessor(DoneMBB); 9679 9680 MI.eraseFromParent(); 9681 9682 return DoneMBB; 9683 } 9684 9685 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9686 MachineBasicBlock *BB) { 9687 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9688 9689 MachineFunction &MF = *BB->getParent(); 9690 DebugLoc DL = MI.getDebugLoc(); 9691 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9692 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9693 Register LoReg = MI.getOperand(0).getReg(); 9694 Register HiReg = MI.getOperand(1).getReg(); 9695 Register SrcReg = MI.getOperand(2).getReg(); 9696 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9697 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9698 9699 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9700 RI); 9701 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9702 MachineMemOperand *MMOLo = 9703 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9704 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9705 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9706 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9707 .addFrameIndex(FI) 9708 .addImm(0) 9709 .addMemOperand(MMOLo); 9710 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9711 .addFrameIndex(FI) 9712 .addImm(4) 9713 .addMemOperand(MMOHi); 9714 MI.eraseFromParent(); // The pseudo instruction is gone now. 9715 return BB; 9716 } 9717 9718 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9719 MachineBasicBlock *BB) { 9720 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9721 "Unexpected instruction"); 9722 9723 MachineFunction &MF = *BB->getParent(); 9724 DebugLoc DL = MI.getDebugLoc(); 9725 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9726 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9727 Register DstReg = MI.getOperand(0).getReg(); 9728 Register LoReg = MI.getOperand(1).getReg(); 9729 Register HiReg = MI.getOperand(2).getReg(); 9730 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9731 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9732 9733 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9734 MachineMemOperand *MMOLo = 9735 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9736 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9737 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9738 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9739 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9740 .addFrameIndex(FI) 9741 .addImm(0) 9742 .addMemOperand(MMOLo); 9743 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9744 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9745 .addFrameIndex(FI) 9746 .addImm(4) 9747 .addMemOperand(MMOHi); 9748 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9749 MI.eraseFromParent(); // The pseudo instruction is gone now. 9750 return BB; 9751 } 9752 9753 static bool isSelectPseudo(MachineInstr &MI) { 9754 switch (MI.getOpcode()) { 9755 default: 9756 return false; 9757 case RISCV::Select_GPR_Using_CC_GPR: 9758 case RISCV::Select_FPR16_Using_CC_GPR: 9759 case RISCV::Select_FPR32_Using_CC_GPR: 9760 case RISCV::Select_FPR64_Using_CC_GPR: 9761 return true; 9762 } 9763 } 9764 9765 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9766 unsigned RelOpcode, unsigned EqOpcode, 9767 const RISCVSubtarget &Subtarget) { 9768 DebugLoc DL = MI.getDebugLoc(); 9769 Register DstReg = MI.getOperand(0).getReg(); 9770 Register Src1Reg = MI.getOperand(1).getReg(); 9771 Register Src2Reg = MI.getOperand(2).getReg(); 9772 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9773 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9774 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9775 9776 // Save the current FFLAGS. 9777 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9778 9779 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9780 .addReg(Src1Reg) 9781 .addReg(Src2Reg); 9782 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9783 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9784 9785 // Restore the FFLAGS. 9786 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9787 .addReg(SavedFFlags, RegState::Kill); 9788 9789 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9790 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9791 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9792 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9793 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9794 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9795 9796 // Erase the pseudoinstruction. 9797 MI.eraseFromParent(); 9798 return BB; 9799 } 9800 9801 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9802 MachineBasicBlock *BB, 9803 const RISCVSubtarget &Subtarget) { 9804 // To "insert" Select_* instructions, we actually have to insert the triangle 9805 // control-flow pattern. The incoming instructions know the destination vreg 9806 // to set, the condition code register to branch on, the true/false values to 9807 // select between, and the condcode to use to select the appropriate branch. 9808 // 9809 // We produce the following control flow: 9810 // HeadMBB 9811 // | \ 9812 // | IfFalseMBB 9813 // | / 9814 // TailMBB 9815 // 9816 // When we find a sequence of selects we attempt to optimize their emission 9817 // by sharing the control flow. Currently we only handle cases where we have 9818 // multiple selects with the exact same condition (same LHS, RHS and CC). 9819 // The selects may be interleaved with other instructions if the other 9820 // instructions meet some requirements we deem safe: 9821 // - They are debug instructions. Otherwise, 9822 // - They do not have side-effects, do not access memory and their inputs do 9823 // not depend on the results of the select pseudo-instructions. 9824 // The TrueV/FalseV operands of the selects cannot depend on the result of 9825 // previous selects in the sequence. 9826 // These conditions could be further relaxed. See the X86 target for a 9827 // related approach and more information. 9828 Register LHS = MI.getOperand(1).getReg(); 9829 Register RHS = MI.getOperand(2).getReg(); 9830 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9831 9832 SmallVector<MachineInstr *, 4> SelectDebugValues; 9833 SmallSet<Register, 4> SelectDests; 9834 SelectDests.insert(MI.getOperand(0).getReg()); 9835 9836 MachineInstr *LastSelectPseudo = &MI; 9837 9838 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9839 SequenceMBBI != E; ++SequenceMBBI) { 9840 if (SequenceMBBI->isDebugInstr()) 9841 continue; 9842 if (isSelectPseudo(*SequenceMBBI)) { 9843 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9844 SequenceMBBI->getOperand(2).getReg() != RHS || 9845 SequenceMBBI->getOperand(3).getImm() != CC || 9846 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9847 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9848 break; 9849 LastSelectPseudo = &*SequenceMBBI; 9850 SequenceMBBI->collectDebugValues(SelectDebugValues); 9851 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9852 } else { 9853 if (SequenceMBBI->hasUnmodeledSideEffects() || 9854 SequenceMBBI->mayLoadOrStore()) 9855 break; 9856 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9857 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9858 })) 9859 break; 9860 } 9861 } 9862 9863 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9864 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9865 DebugLoc DL = MI.getDebugLoc(); 9866 MachineFunction::iterator I = ++BB->getIterator(); 9867 9868 MachineBasicBlock *HeadMBB = BB; 9869 MachineFunction *F = BB->getParent(); 9870 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9871 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9872 9873 F->insert(I, IfFalseMBB); 9874 F->insert(I, TailMBB); 9875 9876 // Transfer debug instructions associated with the selects to TailMBB. 9877 for (MachineInstr *DebugInstr : SelectDebugValues) { 9878 TailMBB->push_back(DebugInstr->removeFromParent()); 9879 } 9880 9881 // Move all instructions after the sequence to TailMBB. 9882 TailMBB->splice(TailMBB->end(), HeadMBB, 9883 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9884 // Update machine-CFG edges by transferring all successors of the current 9885 // block to the new block which will contain the Phi nodes for the selects. 9886 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9887 // Set the successors for HeadMBB. 9888 HeadMBB->addSuccessor(IfFalseMBB); 9889 HeadMBB->addSuccessor(TailMBB); 9890 9891 // Insert appropriate branch. 9892 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9893 .addReg(LHS) 9894 .addReg(RHS) 9895 .addMBB(TailMBB); 9896 9897 // IfFalseMBB just falls through to TailMBB. 9898 IfFalseMBB->addSuccessor(TailMBB); 9899 9900 // Create PHIs for all of the select pseudo-instructions. 9901 auto SelectMBBI = MI.getIterator(); 9902 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9903 auto InsertionPoint = TailMBB->begin(); 9904 while (SelectMBBI != SelectEnd) { 9905 auto Next = std::next(SelectMBBI); 9906 if (isSelectPseudo(*SelectMBBI)) { 9907 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9908 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9909 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9910 .addReg(SelectMBBI->getOperand(4).getReg()) 9911 .addMBB(HeadMBB) 9912 .addReg(SelectMBBI->getOperand(5).getReg()) 9913 .addMBB(IfFalseMBB); 9914 SelectMBBI->eraseFromParent(); 9915 } 9916 SelectMBBI = Next; 9917 } 9918 9919 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9920 return TailMBB; 9921 } 9922 9923 MachineBasicBlock * 9924 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9925 MachineBasicBlock *BB) const { 9926 switch (MI.getOpcode()) { 9927 default: 9928 llvm_unreachable("Unexpected instr type to insert"); 9929 case RISCV::ReadCycleWide: 9930 assert(!Subtarget.is64Bit() && 9931 "ReadCycleWrite is only to be used on riscv32"); 9932 return emitReadCycleWidePseudo(MI, BB); 9933 case RISCV::Select_GPR_Using_CC_GPR: 9934 case RISCV::Select_FPR16_Using_CC_GPR: 9935 case RISCV::Select_FPR32_Using_CC_GPR: 9936 case RISCV::Select_FPR64_Using_CC_GPR: 9937 return emitSelectPseudo(MI, BB, Subtarget); 9938 case RISCV::BuildPairF64Pseudo: 9939 return emitBuildPairF64Pseudo(MI, BB); 9940 case RISCV::SplitF64Pseudo: 9941 return emitSplitF64Pseudo(MI, BB); 9942 case RISCV::PseudoQuietFLE_H: 9943 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9944 case RISCV::PseudoQuietFLT_H: 9945 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9946 case RISCV::PseudoQuietFLE_S: 9947 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9948 case RISCV::PseudoQuietFLT_S: 9949 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9950 case RISCV::PseudoQuietFLE_D: 9951 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9952 case RISCV::PseudoQuietFLT_D: 9953 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9954 } 9955 } 9956 9957 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9958 SDNode *Node) const { 9959 // Add FRM dependency to any instructions with dynamic rounding mode. 9960 unsigned Opc = MI.getOpcode(); 9961 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9962 if (Idx < 0) 9963 return; 9964 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9965 return; 9966 // If the instruction already reads FRM, don't add another read. 9967 if (MI.readsRegister(RISCV::FRM)) 9968 return; 9969 MI.addOperand( 9970 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9971 } 9972 9973 // Calling Convention Implementation. 9974 // The expectations for frontend ABI lowering vary from target to target. 9975 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 9976 // details, but this is a longer term goal. For now, we simply try to keep the 9977 // role of the frontend as simple and well-defined as possible. The rules can 9978 // be summarised as: 9979 // * Never split up large scalar arguments. We handle them here. 9980 // * If a hardfloat calling convention is being used, and the struct may be 9981 // passed in a pair of registers (fp+fp, int+fp), and both registers are 9982 // available, then pass as two separate arguments. If either the GPRs or FPRs 9983 // are exhausted, then pass according to the rule below. 9984 // * If a struct could never be passed in registers or directly in a stack 9985 // slot (as it is larger than 2*XLEN and the floating point rules don't 9986 // apply), then pass it using a pointer with the byval attribute. 9987 // * If a struct is less than 2*XLEN, then coerce to either a two-element 9988 // word-sized array or a 2*XLEN scalar (depending on alignment). 9989 // * The frontend can determine whether a struct is returned by reference or 9990 // not based on its size and fields. If it will be returned by reference, the 9991 // frontend must modify the prototype so a pointer with the sret annotation is 9992 // passed as the first argument. This is not necessary for large scalar 9993 // returns. 9994 // * Struct return values and varargs should be coerced to structs containing 9995 // register-size fields in the same situations they would be for fixed 9996 // arguments. 9997 9998 static const MCPhysReg ArgGPRs[] = { 9999 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 10000 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 10001 }; 10002 static const MCPhysReg ArgFPR16s[] = { 10003 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 10004 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 10005 }; 10006 static const MCPhysReg ArgFPR32s[] = { 10007 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 10008 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 10009 }; 10010 static const MCPhysReg ArgFPR64s[] = { 10011 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 10012 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 10013 }; 10014 // This is an interim calling convention and it may be changed in the future. 10015 static const MCPhysReg ArgVRs[] = { 10016 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 10017 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 10018 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 10019 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 10020 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 10021 RISCV::V20M2, RISCV::V22M2}; 10022 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 10023 RISCV::V20M4}; 10024 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 10025 10026 // Pass a 2*XLEN argument that has been split into two XLEN values through 10027 // registers or the stack as necessary. 10028 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 10029 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 10030 MVT ValVT2, MVT LocVT2, 10031 ISD::ArgFlagsTy ArgFlags2) { 10032 unsigned XLenInBytes = XLen / 8; 10033 if (Register Reg = State.AllocateReg(ArgGPRs)) { 10034 // At least one half can be passed via register. 10035 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 10036 VA1.getLocVT(), CCValAssign::Full)); 10037 } else { 10038 // Both halves must be passed on the stack, with proper alignment. 10039 Align StackAlign = 10040 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 10041 State.addLoc( 10042 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 10043 State.AllocateStack(XLenInBytes, StackAlign), 10044 VA1.getLocVT(), CCValAssign::Full)); 10045 State.addLoc(CCValAssign::getMem( 10046 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 10047 LocVT2, CCValAssign::Full)); 10048 return false; 10049 } 10050 10051 if (Register Reg = State.AllocateReg(ArgGPRs)) { 10052 // The second half can also be passed via register. 10053 State.addLoc( 10054 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 10055 } else { 10056 // The second half is passed via the stack, without additional alignment. 10057 State.addLoc(CCValAssign::getMem( 10058 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 10059 LocVT2, CCValAssign::Full)); 10060 } 10061 10062 return false; 10063 } 10064 10065 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 10066 Optional<unsigned> FirstMaskArgument, 10067 CCState &State, const RISCVTargetLowering &TLI) { 10068 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 10069 if (RC == &RISCV::VRRegClass) { 10070 // Assign the first mask argument to V0. 10071 // This is an interim calling convention and it may be changed in the 10072 // future. 10073 if (FirstMaskArgument && ValNo == *FirstMaskArgument) 10074 return State.AllocateReg(RISCV::V0); 10075 return State.AllocateReg(ArgVRs); 10076 } 10077 if (RC == &RISCV::VRM2RegClass) 10078 return State.AllocateReg(ArgVRM2s); 10079 if (RC == &RISCV::VRM4RegClass) 10080 return State.AllocateReg(ArgVRM4s); 10081 if (RC == &RISCV::VRM8RegClass) 10082 return State.AllocateReg(ArgVRM8s); 10083 llvm_unreachable("Unhandled register class for ValueType"); 10084 } 10085 10086 // Implements the RISC-V calling convention. Returns true upon failure. 10087 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 10088 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 10089 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 10090 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 10091 Optional<unsigned> FirstMaskArgument) { 10092 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 10093 assert(XLen == 32 || XLen == 64); 10094 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 10095 10096 // Any return value split in to more than two values can't be returned 10097 // directly. Vectors are returned via the available vector registers. 10098 if (!LocVT.isVector() && IsRet && ValNo > 1) 10099 return true; 10100 10101 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 10102 // variadic argument, or if no F16/F32 argument registers are available. 10103 bool UseGPRForF16_F32 = true; 10104 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 10105 // variadic argument, or if no F64 argument registers are available. 10106 bool UseGPRForF64 = true; 10107 10108 switch (ABI) { 10109 default: 10110 llvm_unreachable("Unexpected ABI"); 10111 case RISCVABI::ABI_ILP32: 10112 case RISCVABI::ABI_LP64: 10113 break; 10114 case RISCVABI::ABI_ILP32F: 10115 case RISCVABI::ABI_LP64F: 10116 UseGPRForF16_F32 = !IsFixed; 10117 break; 10118 case RISCVABI::ABI_ILP32D: 10119 case RISCVABI::ABI_LP64D: 10120 UseGPRForF16_F32 = !IsFixed; 10121 UseGPRForF64 = !IsFixed; 10122 break; 10123 } 10124 10125 // FPR16, FPR32, and FPR64 alias each other. 10126 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 10127 UseGPRForF16_F32 = true; 10128 UseGPRForF64 = true; 10129 } 10130 10131 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 10132 // similar local variables rather than directly checking against the target 10133 // ABI. 10134 10135 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 10136 LocVT = XLenVT; 10137 LocInfo = CCValAssign::BCvt; 10138 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 10139 LocVT = MVT::i64; 10140 LocInfo = CCValAssign::BCvt; 10141 } 10142 10143 // If this is a variadic argument, the RISC-V calling convention requires 10144 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 10145 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 10146 // be used regardless of whether the original argument was split during 10147 // legalisation or not. The argument will not be passed by registers if the 10148 // original type is larger than 2*XLEN, so the register alignment rule does 10149 // not apply. 10150 unsigned TwoXLenInBytes = (2 * XLen) / 8; 10151 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 10152 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 10153 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 10154 // Skip 'odd' register if necessary. 10155 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 10156 State.AllocateReg(ArgGPRs); 10157 } 10158 10159 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 10160 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 10161 State.getPendingArgFlags(); 10162 10163 assert(PendingLocs.size() == PendingArgFlags.size() && 10164 "PendingLocs and PendingArgFlags out of sync"); 10165 10166 // Handle passing f64 on RV32D with a soft float ABI or when floating point 10167 // registers are exhausted. 10168 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 10169 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 10170 "Can't lower f64 if it is split"); 10171 // Depending on available argument GPRS, f64 may be passed in a pair of 10172 // GPRs, split between a GPR and the stack, or passed completely on the 10173 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 10174 // cases. 10175 Register Reg = State.AllocateReg(ArgGPRs); 10176 LocVT = MVT::i32; 10177 if (!Reg) { 10178 unsigned StackOffset = State.AllocateStack(8, Align(8)); 10179 State.addLoc( 10180 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10181 return false; 10182 } 10183 if (!State.AllocateReg(ArgGPRs)) 10184 State.AllocateStack(4, Align(4)); 10185 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10186 return false; 10187 } 10188 10189 // Fixed-length vectors are located in the corresponding scalable-vector 10190 // container types. 10191 if (ValVT.isFixedLengthVector()) 10192 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10193 10194 // Split arguments might be passed indirectly, so keep track of the pending 10195 // values. Split vectors are passed via a mix of registers and indirectly, so 10196 // treat them as we would any other argument. 10197 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 10198 LocVT = XLenVT; 10199 LocInfo = CCValAssign::Indirect; 10200 PendingLocs.push_back( 10201 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 10202 PendingArgFlags.push_back(ArgFlags); 10203 if (!ArgFlags.isSplitEnd()) { 10204 return false; 10205 } 10206 } 10207 10208 // If the split argument only had two elements, it should be passed directly 10209 // in registers or on the stack. 10210 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 10211 PendingLocs.size() <= 2) { 10212 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 10213 // Apply the normal calling convention rules to the first half of the 10214 // split argument. 10215 CCValAssign VA = PendingLocs[0]; 10216 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 10217 PendingLocs.clear(); 10218 PendingArgFlags.clear(); 10219 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 10220 ArgFlags); 10221 } 10222 10223 // Allocate to a register if possible, or else a stack slot. 10224 Register Reg; 10225 unsigned StoreSizeBytes = XLen / 8; 10226 Align StackAlign = Align(XLen / 8); 10227 10228 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 10229 Reg = State.AllocateReg(ArgFPR16s); 10230 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 10231 Reg = State.AllocateReg(ArgFPR32s); 10232 else if (ValVT == MVT::f64 && !UseGPRForF64) 10233 Reg = State.AllocateReg(ArgFPR64s); 10234 else if (ValVT.isVector()) { 10235 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 10236 if (!Reg) { 10237 // For return values, the vector must be passed fully via registers or 10238 // via the stack. 10239 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 10240 // but we're using all of them. 10241 if (IsRet) 10242 return true; 10243 // Try using a GPR to pass the address 10244 if ((Reg = State.AllocateReg(ArgGPRs))) { 10245 LocVT = XLenVT; 10246 LocInfo = CCValAssign::Indirect; 10247 } else if (ValVT.isScalableVector()) { 10248 LocVT = XLenVT; 10249 LocInfo = CCValAssign::Indirect; 10250 } else { 10251 // Pass fixed-length vectors on the stack. 10252 LocVT = ValVT; 10253 StoreSizeBytes = ValVT.getStoreSize(); 10254 // Align vectors to their element sizes, being careful for vXi1 10255 // vectors. 10256 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10257 } 10258 } 10259 } else { 10260 Reg = State.AllocateReg(ArgGPRs); 10261 } 10262 10263 unsigned StackOffset = 10264 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 10265 10266 // If we reach this point and PendingLocs is non-empty, we must be at the 10267 // end of a split argument that must be passed indirectly. 10268 if (!PendingLocs.empty()) { 10269 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 10270 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 10271 10272 for (auto &It : PendingLocs) { 10273 if (Reg) 10274 It.convertToReg(Reg); 10275 else 10276 It.convertToMem(StackOffset); 10277 State.addLoc(It); 10278 } 10279 PendingLocs.clear(); 10280 PendingArgFlags.clear(); 10281 return false; 10282 } 10283 10284 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 10285 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 10286 "Expected an XLenVT or vector types at this stage"); 10287 10288 if (Reg) { 10289 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10290 return false; 10291 } 10292 10293 // When a floating-point value is passed on the stack, no bit-conversion is 10294 // needed. 10295 if (ValVT.isFloatingPoint()) { 10296 LocVT = ValVT; 10297 LocInfo = CCValAssign::Full; 10298 } 10299 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10300 return false; 10301 } 10302 10303 template <typename ArgTy> 10304 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 10305 for (const auto &ArgIdx : enumerate(Args)) { 10306 MVT ArgVT = ArgIdx.value().VT; 10307 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 10308 return ArgIdx.index(); 10309 } 10310 return None; 10311 } 10312 10313 void RISCVTargetLowering::analyzeInputArgs( 10314 MachineFunction &MF, CCState &CCInfo, 10315 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 10316 RISCVCCAssignFn Fn) const { 10317 unsigned NumArgs = Ins.size(); 10318 FunctionType *FType = MF.getFunction().getFunctionType(); 10319 10320 Optional<unsigned> FirstMaskArgument; 10321 if (Subtarget.hasVInstructions()) 10322 FirstMaskArgument = preAssignMask(Ins); 10323 10324 for (unsigned i = 0; i != NumArgs; ++i) { 10325 MVT ArgVT = Ins[i].VT; 10326 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 10327 10328 Type *ArgTy = nullptr; 10329 if (IsRet) 10330 ArgTy = FType->getReturnType(); 10331 else if (Ins[i].isOrigArg()) 10332 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 10333 10334 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10335 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10336 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 10337 FirstMaskArgument)) { 10338 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 10339 << EVT(ArgVT).getEVTString() << '\n'); 10340 llvm_unreachable(nullptr); 10341 } 10342 } 10343 } 10344 10345 void RISCVTargetLowering::analyzeOutputArgs( 10346 MachineFunction &MF, CCState &CCInfo, 10347 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 10348 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 10349 unsigned NumArgs = Outs.size(); 10350 10351 Optional<unsigned> FirstMaskArgument; 10352 if (Subtarget.hasVInstructions()) 10353 FirstMaskArgument = preAssignMask(Outs); 10354 10355 for (unsigned i = 0; i != NumArgs; i++) { 10356 MVT ArgVT = Outs[i].VT; 10357 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10358 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 10359 10360 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10361 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10362 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 10363 FirstMaskArgument)) { 10364 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 10365 << EVT(ArgVT).getEVTString() << "\n"); 10366 llvm_unreachable(nullptr); 10367 } 10368 } 10369 } 10370 10371 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 10372 // values. 10373 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 10374 const CCValAssign &VA, const SDLoc &DL, 10375 const RISCVSubtarget &Subtarget) { 10376 switch (VA.getLocInfo()) { 10377 default: 10378 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10379 case CCValAssign::Full: 10380 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 10381 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 10382 break; 10383 case CCValAssign::BCvt: 10384 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10385 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 10386 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10387 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 10388 else 10389 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 10390 break; 10391 } 10392 return Val; 10393 } 10394 10395 // The caller is responsible for loading the full value if the argument is 10396 // passed with CCValAssign::Indirect. 10397 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 10398 const CCValAssign &VA, const SDLoc &DL, 10399 const RISCVTargetLowering &TLI) { 10400 MachineFunction &MF = DAG.getMachineFunction(); 10401 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10402 EVT LocVT = VA.getLocVT(); 10403 SDValue Val; 10404 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 10405 Register VReg = RegInfo.createVirtualRegister(RC); 10406 RegInfo.addLiveIn(VA.getLocReg(), VReg); 10407 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 10408 10409 if (VA.getLocInfo() == CCValAssign::Indirect) 10410 return Val; 10411 10412 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 10413 } 10414 10415 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 10416 const CCValAssign &VA, const SDLoc &DL, 10417 const RISCVSubtarget &Subtarget) { 10418 EVT LocVT = VA.getLocVT(); 10419 10420 switch (VA.getLocInfo()) { 10421 default: 10422 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10423 case CCValAssign::Full: 10424 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 10425 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 10426 break; 10427 case CCValAssign::BCvt: 10428 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10429 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 10430 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10431 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 10432 else 10433 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 10434 break; 10435 } 10436 return Val; 10437 } 10438 10439 // The caller is responsible for loading the full value if the argument is 10440 // passed with CCValAssign::Indirect. 10441 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 10442 const CCValAssign &VA, const SDLoc &DL) { 10443 MachineFunction &MF = DAG.getMachineFunction(); 10444 MachineFrameInfo &MFI = MF.getFrameInfo(); 10445 EVT LocVT = VA.getLocVT(); 10446 EVT ValVT = VA.getValVT(); 10447 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 10448 if (ValVT.isScalableVector()) { 10449 // When the value is a scalable vector, we save the pointer which points to 10450 // the scalable vector value in the stack. The ValVT will be the pointer 10451 // type, instead of the scalable vector type. 10452 ValVT = LocVT; 10453 } 10454 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 10455 /*IsImmutable=*/true); 10456 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 10457 SDValue Val; 10458 10459 ISD::LoadExtType ExtType; 10460 switch (VA.getLocInfo()) { 10461 default: 10462 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10463 case CCValAssign::Full: 10464 case CCValAssign::Indirect: 10465 case CCValAssign::BCvt: 10466 ExtType = ISD::NON_EXTLOAD; 10467 break; 10468 } 10469 Val = DAG.getExtLoad( 10470 ExtType, DL, LocVT, Chain, FIN, 10471 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 10472 return Val; 10473 } 10474 10475 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 10476 const CCValAssign &VA, const SDLoc &DL) { 10477 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 10478 "Unexpected VA"); 10479 MachineFunction &MF = DAG.getMachineFunction(); 10480 MachineFrameInfo &MFI = MF.getFrameInfo(); 10481 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10482 10483 if (VA.isMemLoc()) { 10484 // f64 is passed on the stack. 10485 int FI = 10486 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 10487 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10488 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 10489 MachinePointerInfo::getFixedStack(MF, FI)); 10490 } 10491 10492 assert(VA.isRegLoc() && "Expected register VA assignment"); 10493 10494 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10495 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 10496 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 10497 SDValue Hi; 10498 if (VA.getLocReg() == RISCV::X17) { 10499 // Second half of f64 is passed on the stack. 10500 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 10501 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10502 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 10503 MachinePointerInfo::getFixedStack(MF, FI)); 10504 } else { 10505 // Second half of f64 is passed in another GPR. 10506 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10507 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 10508 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 10509 } 10510 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 10511 } 10512 10513 // FastCC has less than 1% performance improvement for some particular 10514 // benchmark. But theoretically, it may has benenfit for some cases. 10515 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 10516 unsigned ValNo, MVT ValVT, MVT LocVT, 10517 CCValAssign::LocInfo LocInfo, 10518 ISD::ArgFlagsTy ArgFlags, CCState &State, 10519 bool IsFixed, bool IsRet, Type *OrigTy, 10520 const RISCVTargetLowering &TLI, 10521 Optional<unsigned> FirstMaskArgument) { 10522 10523 // X5 and X6 might be used for save-restore libcall. 10524 static const MCPhysReg GPRList[] = { 10525 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 10526 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 10527 RISCV::X29, RISCV::X30, RISCV::X31}; 10528 10529 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10530 if (unsigned Reg = State.AllocateReg(GPRList)) { 10531 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10532 return false; 10533 } 10534 } 10535 10536 if (LocVT == MVT::f16) { 10537 static const MCPhysReg FPR16List[] = { 10538 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 10539 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 10540 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 10541 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 10542 if (unsigned Reg = State.AllocateReg(FPR16List)) { 10543 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10544 return false; 10545 } 10546 } 10547 10548 if (LocVT == MVT::f32) { 10549 static const MCPhysReg FPR32List[] = { 10550 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 10551 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 10552 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 10553 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 10554 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10555 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10556 return false; 10557 } 10558 } 10559 10560 if (LocVT == MVT::f64) { 10561 static const MCPhysReg FPR64List[] = { 10562 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 10563 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 10564 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 10565 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 10566 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10567 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10568 return false; 10569 } 10570 } 10571 10572 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 10573 unsigned Offset4 = State.AllocateStack(4, Align(4)); 10574 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 10575 return false; 10576 } 10577 10578 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 10579 unsigned Offset5 = State.AllocateStack(8, Align(8)); 10580 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 10581 return false; 10582 } 10583 10584 if (LocVT.isVector()) { 10585 if (unsigned Reg = 10586 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 10587 // Fixed-length vectors are located in the corresponding scalable-vector 10588 // container types. 10589 if (ValVT.isFixedLengthVector()) 10590 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10591 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10592 } else { 10593 // Try and pass the address via a "fast" GPR. 10594 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 10595 LocInfo = CCValAssign::Indirect; 10596 LocVT = TLI.getSubtarget().getXLenVT(); 10597 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 10598 } else if (ValVT.isFixedLengthVector()) { 10599 auto StackAlign = 10600 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10601 unsigned StackOffset = 10602 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 10603 State.addLoc( 10604 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10605 } else { 10606 // Can't pass scalable vectors on the stack. 10607 return true; 10608 } 10609 } 10610 10611 return false; 10612 } 10613 10614 return true; // CC didn't match. 10615 } 10616 10617 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 10618 CCValAssign::LocInfo LocInfo, 10619 ISD::ArgFlagsTy ArgFlags, CCState &State) { 10620 10621 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10622 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 10623 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 10624 static const MCPhysReg GPRList[] = { 10625 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 10626 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 10627 if (unsigned Reg = State.AllocateReg(GPRList)) { 10628 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10629 return false; 10630 } 10631 } 10632 10633 if (LocVT == MVT::f32) { 10634 // Pass in STG registers: F1, ..., F6 10635 // fs0 ... fs5 10636 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 10637 RISCV::F18_F, RISCV::F19_F, 10638 RISCV::F20_F, RISCV::F21_F}; 10639 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10640 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10641 return false; 10642 } 10643 } 10644 10645 if (LocVT == MVT::f64) { 10646 // Pass in STG registers: D1, ..., D6 10647 // fs6 ... fs11 10648 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 10649 RISCV::F24_D, RISCV::F25_D, 10650 RISCV::F26_D, RISCV::F27_D}; 10651 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10652 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10653 return false; 10654 } 10655 } 10656 10657 report_fatal_error("No registers left in GHC calling convention"); 10658 return true; 10659 } 10660 10661 // Transform physical registers into virtual registers. 10662 SDValue RISCVTargetLowering::LowerFormalArguments( 10663 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 10664 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 10665 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 10666 10667 MachineFunction &MF = DAG.getMachineFunction(); 10668 10669 switch (CallConv) { 10670 default: 10671 report_fatal_error("Unsupported calling convention"); 10672 case CallingConv::C: 10673 case CallingConv::Fast: 10674 break; 10675 case CallingConv::GHC: 10676 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10677 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10678 report_fatal_error( 10679 "GHC calling convention requires the F and D instruction set extensions"); 10680 } 10681 10682 const Function &Func = MF.getFunction(); 10683 if (Func.hasFnAttribute("interrupt")) { 10684 if (!Func.arg_empty()) 10685 report_fatal_error( 10686 "Functions with the interrupt attribute cannot have arguments!"); 10687 10688 StringRef Kind = 10689 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10690 10691 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10692 report_fatal_error( 10693 "Function interrupt attribute argument not supported!"); 10694 } 10695 10696 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10697 MVT XLenVT = Subtarget.getXLenVT(); 10698 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10699 // Used with vargs to acumulate store chains. 10700 std::vector<SDValue> OutChains; 10701 10702 // Assign locations to all of the incoming arguments. 10703 SmallVector<CCValAssign, 16> ArgLocs; 10704 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10705 10706 if (CallConv == CallingConv::GHC) 10707 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10708 else 10709 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10710 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10711 : CC_RISCV); 10712 10713 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10714 CCValAssign &VA = ArgLocs[i]; 10715 SDValue ArgValue; 10716 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10717 // case. 10718 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10719 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10720 else if (VA.isRegLoc()) 10721 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10722 else 10723 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10724 10725 if (VA.getLocInfo() == CCValAssign::Indirect) { 10726 // If the original argument was split and passed by reference (e.g. i128 10727 // on RV32), we need to load all parts of it here (using the same 10728 // address). Vectors may be partly split to registers and partly to the 10729 // stack, in which case the base address is partly offset and subsequent 10730 // stores are relative to that. 10731 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10732 MachinePointerInfo())); 10733 unsigned ArgIndex = Ins[i].OrigArgIndex; 10734 unsigned ArgPartOffset = Ins[i].PartOffset; 10735 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10736 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10737 CCValAssign &PartVA = ArgLocs[i + 1]; 10738 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10739 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10740 if (PartVA.getValVT().isScalableVector()) 10741 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10742 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10743 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10744 MachinePointerInfo())); 10745 ++i; 10746 } 10747 continue; 10748 } 10749 InVals.push_back(ArgValue); 10750 } 10751 10752 if (IsVarArg) { 10753 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10754 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10755 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10756 MachineFrameInfo &MFI = MF.getFrameInfo(); 10757 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10758 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10759 10760 // Offset of the first variable argument from stack pointer, and size of 10761 // the vararg save area. For now, the varargs save area is either zero or 10762 // large enough to hold a0-a7. 10763 int VaArgOffset, VarArgsSaveSize; 10764 10765 // If all registers are allocated, then all varargs must be passed on the 10766 // stack and we don't need to save any argregs. 10767 if (ArgRegs.size() == Idx) { 10768 VaArgOffset = CCInfo.getNextStackOffset(); 10769 VarArgsSaveSize = 0; 10770 } else { 10771 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10772 VaArgOffset = -VarArgsSaveSize; 10773 } 10774 10775 // Record the frame index of the first variable argument 10776 // which is a value necessary to VASTART. 10777 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10778 RVFI->setVarArgsFrameIndex(FI); 10779 10780 // If saving an odd number of registers then create an extra stack slot to 10781 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10782 // offsets to even-numbered registered remain 2*XLEN-aligned. 10783 if (Idx % 2) { 10784 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10785 VarArgsSaveSize += XLenInBytes; 10786 } 10787 10788 // Copy the integer registers that may have been used for passing varargs 10789 // to the vararg save area. 10790 for (unsigned I = Idx; I < ArgRegs.size(); 10791 ++I, VaArgOffset += XLenInBytes) { 10792 const Register Reg = RegInfo.createVirtualRegister(RC); 10793 RegInfo.addLiveIn(ArgRegs[I], Reg); 10794 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10795 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10796 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10797 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10798 MachinePointerInfo::getFixedStack(MF, FI)); 10799 cast<StoreSDNode>(Store.getNode()) 10800 ->getMemOperand() 10801 ->setValue((Value *)nullptr); 10802 OutChains.push_back(Store); 10803 } 10804 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10805 } 10806 10807 // All stores are grouped in one node to allow the matching between 10808 // the size of Ins and InVals. This only happens for vararg functions. 10809 if (!OutChains.empty()) { 10810 OutChains.push_back(Chain); 10811 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10812 } 10813 10814 return Chain; 10815 } 10816 10817 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10818 /// for tail call optimization. 10819 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10820 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10821 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10822 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10823 10824 auto &Callee = CLI.Callee; 10825 auto CalleeCC = CLI.CallConv; 10826 auto &Outs = CLI.Outs; 10827 auto &Caller = MF.getFunction(); 10828 auto CallerCC = Caller.getCallingConv(); 10829 10830 // Exception-handling functions need a special set of instructions to 10831 // indicate a return to the hardware. Tail-calling another function would 10832 // probably break this. 10833 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10834 // should be expanded as new function attributes are introduced. 10835 if (Caller.hasFnAttribute("interrupt")) 10836 return false; 10837 10838 // Do not tail call opt if the stack is used to pass parameters. 10839 if (CCInfo.getNextStackOffset() != 0) 10840 return false; 10841 10842 // Do not tail call opt if any parameters need to be passed indirectly. 10843 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10844 // passed indirectly. So the address of the value will be passed in a 10845 // register, or if not available, then the address is put on the stack. In 10846 // order to pass indirectly, space on the stack often needs to be allocated 10847 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10848 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10849 // are passed CCValAssign::Indirect. 10850 for (auto &VA : ArgLocs) 10851 if (VA.getLocInfo() == CCValAssign::Indirect) 10852 return false; 10853 10854 // Do not tail call opt if either caller or callee uses struct return 10855 // semantics. 10856 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10857 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10858 if (IsCallerStructRet || IsCalleeStructRet) 10859 return false; 10860 10861 // Externally-defined functions with weak linkage should not be 10862 // tail-called. The behaviour of branch instructions in this situation (as 10863 // used for tail calls) is implementation-defined, so we cannot rely on the 10864 // linker replacing the tail call with a return. 10865 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10866 const GlobalValue *GV = G->getGlobal(); 10867 if (GV->hasExternalWeakLinkage()) 10868 return false; 10869 } 10870 10871 // The callee has to preserve all registers the caller needs to preserve. 10872 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10873 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10874 if (CalleeCC != CallerCC) { 10875 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10876 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10877 return false; 10878 } 10879 10880 // Byval parameters hand the function a pointer directly into the stack area 10881 // we want to reuse during a tail call. Working around this *is* possible 10882 // but less efficient and uglier in LowerCall. 10883 for (auto &Arg : Outs) 10884 if (Arg.Flags.isByVal()) 10885 return false; 10886 10887 return true; 10888 } 10889 10890 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10891 return DAG.getDataLayout().getPrefTypeAlign( 10892 VT.getTypeForEVT(*DAG.getContext())); 10893 } 10894 10895 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10896 // and output parameter nodes. 10897 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10898 SmallVectorImpl<SDValue> &InVals) const { 10899 SelectionDAG &DAG = CLI.DAG; 10900 SDLoc &DL = CLI.DL; 10901 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10902 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10903 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10904 SDValue Chain = CLI.Chain; 10905 SDValue Callee = CLI.Callee; 10906 bool &IsTailCall = CLI.IsTailCall; 10907 CallingConv::ID CallConv = CLI.CallConv; 10908 bool IsVarArg = CLI.IsVarArg; 10909 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10910 MVT XLenVT = Subtarget.getXLenVT(); 10911 10912 MachineFunction &MF = DAG.getMachineFunction(); 10913 10914 // Analyze the operands of the call, assigning locations to each operand. 10915 SmallVector<CCValAssign, 16> ArgLocs; 10916 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10917 10918 if (CallConv == CallingConv::GHC) 10919 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10920 else 10921 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10922 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10923 : CC_RISCV); 10924 10925 // Check if it's really possible to do a tail call. 10926 if (IsTailCall) 10927 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10928 10929 if (IsTailCall) 10930 ++NumTailCalls; 10931 else if (CLI.CB && CLI.CB->isMustTailCall()) 10932 report_fatal_error("failed to perform tail call elimination on a call " 10933 "site marked musttail"); 10934 10935 // Get a count of how many bytes are to be pushed on the stack. 10936 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10937 10938 // Create local copies for byval args 10939 SmallVector<SDValue, 8> ByValArgs; 10940 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10941 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10942 if (!Flags.isByVal()) 10943 continue; 10944 10945 SDValue Arg = OutVals[i]; 10946 unsigned Size = Flags.getByValSize(); 10947 Align Alignment = Flags.getNonZeroByValAlign(); 10948 10949 int FI = 10950 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10951 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10952 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10953 10954 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10955 /*IsVolatile=*/false, 10956 /*AlwaysInline=*/false, IsTailCall, 10957 MachinePointerInfo(), MachinePointerInfo()); 10958 ByValArgs.push_back(FIPtr); 10959 } 10960 10961 if (!IsTailCall) 10962 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10963 10964 // Copy argument values to their designated locations. 10965 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10966 SmallVector<SDValue, 8> MemOpChains; 10967 SDValue StackPtr; 10968 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10969 CCValAssign &VA = ArgLocs[i]; 10970 SDValue ArgValue = OutVals[i]; 10971 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10972 10973 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10974 bool IsF64OnRV32DSoftABI = 10975 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 10976 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 10977 SDValue SplitF64 = DAG.getNode( 10978 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 10979 SDValue Lo = SplitF64.getValue(0); 10980 SDValue Hi = SplitF64.getValue(1); 10981 10982 Register RegLo = VA.getLocReg(); 10983 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 10984 10985 if (RegLo == RISCV::X17) { 10986 // Second half of f64 is passed on the stack. 10987 // Work out the address of the stack slot. 10988 if (!StackPtr.getNode()) 10989 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10990 // Emit the store. 10991 MemOpChains.push_back( 10992 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 10993 } else { 10994 // Second half of f64 is passed in another GPR. 10995 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10996 Register RegHigh = RegLo + 1; 10997 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 10998 } 10999 continue; 11000 } 11001 11002 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 11003 // as any other MemLoc. 11004 11005 // Promote the value if needed. 11006 // For now, only handle fully promoted and indirect arguments. 11007 if (VA.getLocInfo() == CCValAssign::Indirect) { 11008 // Store the argument in a stack slot and pass its address. 11009 Align StackAlign = 11010 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 11011 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 11012 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 11013 // If the original argument was split (e.g. i128), we need 11014 // to store the required parts of it here (and pass just one address). 11015 // Vectors may be partly split to registers and partly to the stack, in 11016 // which case the base address is partly offset and subsequent stores are 11017 // relative to that. 11018 unsigned ArgIndex = Outs[i].OrigArgIndex; 11019 unsigned ArgPartOffset = Outs[i].PartOffset; 11020 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 11021 // Calculate the total size to store. We don't have access to what we're 11022 // actually storing other than performing the loop and collecting the 11023 // info. 11024 SmallVector<std::pair<SDValue, SDValue>> Parts; 11025 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 11026 SDValue PartValue = OutVals[i + 1]; 11027 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 11028 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 11029 EVT PartVT = PartValue.getValueType(); 11030 if (PartVT.isScalableVector()) 11031 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 11032 StoredSize += PartVT.getStoreSize(); 11033 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 11034 Parts.push_back(std::make_pair(PartValue, Offset)); 11035 ++i; 11036 } 11037 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 11038 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 11039 MemOpChains.push_back( 11040 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 11041 MachinePointerInfo::getFixedStack(MF, FI))); 11042 for (const auto &Part : Parts) { 11043 SDValue PartValue = Part.first; 11044 SDValue PartOffset = Part.second; 11045 SDValue Address = 11046 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 11047 MemOpChains.push_back( 11048 DAG.getStore(Chain, DL, PartValue, Address, 11049 MachinePointerInfo::getFixedStack(MF, FI))); 11050 } 11051 ArgValue = SpillSlot; 11052 } else { 11053 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 11054 } 11055 11056 // Use local copy if it is a byval arg. 11057 if (Flags.isByVal()) 11058 ArgValue = ByValArgs[j++]; 11059 11060 if (VA.isRegLoc()) { 11061 // Queue up the argument copies and emit them at the end. 11062 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 11063 } else { 11064 assert(VA.isMemLoc() && "Argument not register or memory"); 11065 assert(!IsTailCall && "Tail call not allowed if stack is used " 11066 "for passing parameters"); 11067 11068 // Work out the address of the stack slot. 11069 if (!StackPtr.getNode()) 11070 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 11071 SDValue Address = 11072 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 11073 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 11074 11075 // Emit the store. 11076 MemOpChains.push_back( 11077 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 11078 } 11079 } 11080 11081 // Join the stores, which are independent of one another. 11082 if (!MemOpChains.empty()) 11083 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 11084 11085 SDValue Glue; 11086 11087 // Build a sequence of copy-to-reg nodes, chained and glued together. 11088 for (auto &Reg : RegsToPass) { 11089 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 11090 Glue = Chain.getValue(1); 11091 } 11092 11093 // Validate that none of the argument registers have been marked as 11094 // reserved, if so report an error. Do the same for the return address if this 11095 // is not a tailcall. 11096 validateCCReservedRegs(RegsToPass, MF); 11097 if (!IsTailCall && 11098 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 11099 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11100 MF.getFunction(), 11101 "Return address register required, but has been reserved."}); 11102 11103 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 11104 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 11105 // split it and then direct call can be matched by PseudoCALL. 11106 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 11107 const GlobalValue *GV = S->getGlobal(); 11108 11109 unsigned OpFlags = RISCVII::MO_CALL; 11110 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 11111 OpFlags = RISCVII::MO_PLT; 11112 11113 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 11114 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 11115 unsigned OpFlags = RISCVII::MO_CALL; 11116 11117 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 11118 nullptr)) 11119 OpFlags = RISCVII::MO_PLT; 11120 11121 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 11122 } 11123 11124 // The first call operand is the chain and the second is the target address. 11125 SmallVector<SDValue, 8> Ops; 11126 Ops.push_back(Chain); 11127 Ops.push_back(Callee); 11128 11129 // Add argument registers to the end of the list so that they are 11130 // known live into the call. 11131 for (auto &Reg : RegsToPass) 11132 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 11133 11134 if (!IsTailCall) { 11135 // Add a register mask operand representing the call-preserved registers. 11136 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11137 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 11138 assert(Mask && "Missing call preserved mask for calling convention"); 11139 Ops.push_back(DAG.getRegisterMask(Mask)); 11140 } 11141 11142 // Glue the call to the argument copies, if any. 11143 if (Glue.getNode()) 11144 Ops.push_back(Glue); 11145 11146 // Emit the call. 11147 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 11148 11149 if (IsTailCall) { 11150 MF.getFrameInfo().setHasTailCall(); 11151 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 11152 } 11153 11154 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 11155 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 11156 Glue = Chain.getValue(1); 11157 11158 // Mark the end of the call, which is glued to the call itself. 11159 Chain = DAG.getCALLSEQ_END(Chain, 11160 DAG.getConstant(NumBytes, DL, PtrVT, true), 11161 DAG.getConstant(0, DL, PtrVT, true), 11162 Glue, DL); 11163 Glue = Chain.getValue(1); 11164 11165 // Assign locations to each value returned by this call. 11166 SmallVector<CCValAssign, 16> RVLocs; 11167 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 11168 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 11169 11170 // Copy all of the result registers out of their specified physreg. 11171 for (auto &VA : RVLocs) { 11172 // Copy the value out 11173 SDValue RetValue = 11174 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 11175 // Glue the RetValue to the end of the call sequence 11176 Chain = RetValue.getValue(1); 11177 Glue = RetValue.getValue(2); 11178 11179 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 11180 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 11181 SDValue RetValue2 = 11182 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 11183 Chain = RetValue2.getValue(1); 11184 Glue = RetValue2.getValue(2); 11185 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 11186 RetValue2); 11187 } 11188 11189 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 11190 11191 InVals.push_back(RetValue); 11192 } 11193 11194 return Chain; 11195 } 11196 11197 bool RISCVTargetLowering::CanLowerReturn( 11198 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 11199 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 11200 SmallVector<CCValAssign, 16> RVLocs; 11201 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 11202 11203 Optional<unsigned> FirstMaskArgument; 11204 if (Subtarget.hasVInstructions()) 11205 FirstMaskArgument = preAssignMask(Outs); 11206 11207 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 11208 MVT VT = Outs[i].VT; 11209 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 11210 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 11211 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 11212 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 11213 *this, FirstMaskArgument)) 11214 return false; 11215 } 11216 return true; 11217 } 11218 11219 SDValue 11220 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 11221 bool IsVarArg, 11222 const SmallVectorImpl<ISD::OutputArg> &Outs, 11223 const SmallVectorImpl<SDValue> &OutVals, 11224 const SDLoc &DL, SelectionDAG &DAG) const { 11225 const MachineFunction &MF = DAG.getMachineFunction(); 11226 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 11227 11228 // Stores the assignment of the return value to a location. 11229 SmallVector<CCValAssign, 16> RVLocs; 11230 11231 // Info about the registers and stack slot. 11232 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 11233 *DAG.getContext()); 11234 11235 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 11236 nullptr, CC_RISCV); 11237 11238 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 11239 report_fatal_error("GHC functions return void only"); 11240 11241 SDValue Glue; 11242 SmallVector<SDValue, 4> RetOps(1, Chain); 11243 11244 // Copy the result values into the output registers. 11245 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 11246 SDValue Val = OutVals[i]; 11247 CCValAssign &VA = RVLocs[i]; 11248 assert(VA.isRegLoc() && "Can only return in registers!"); 11249 11250 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 11251 // Handle returning f64 on RV32D with a soft float ABI. 11252 assert(VA.isRegLoc() && "Expected return via registers"); 11253 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 11254 DAG.getVTList(MVT::i32, MVT::i32), Val); 11255 SDValue Lo = SplitF64.getValue(0); 11256 SDValue Hi = SplitF64.getValue(1); 11257 Register RegLo = VA.getLocReg(); 11258 assert(RegLo < RISCV::X31 && "Invalid register pair"); 11259 Register RegHi = RegLo + 1; 11260 11261 if (STI.isRegisterReservedByUser(RegLo) || 11262 STI.isRegisterReservedByUser(RegHi)) 11263 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11264 MF.getFunction(), 11265 "Return value register required, but has been reserved."}); 11266 11267 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 11268 Glue = Chain.getValue(1); 11269 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 11270 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 11271 Glue = Chain.getValue(1); 11272 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 11273 } else { 11274 // Handle a 'normal' return. 11275 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 11276 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 11277 11278 if (STI.isRegisterReservedByUser(VA.getLocReg())) 11279 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11280 MF.getFunction(), 11281 "Return value register required, but has been reserved."}); 11282 11283 // Guarantee that all emitted copies are stuck together. 11284 Glue = Chain.getValue(1); 11285 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 11286 } 11287 } 11288 11289 RetOps[0] = Chain; // Update chain. 11290 11291 // Add the glue node if we have it. 11292 if (Glue.getNode()) { 11293 RetOps.push_back(Glue); 11294 } 11295 11296 unsigned RetOpc = RISCVISD::RET_FLAG; 11297 // Interrupt service routines use different return instructions. 11298 const Function &Func = DAG.getMachineFunction().getFunction(); 11299 if (Func.hasFnAttribute("interrupt")) { 11300 if (!Func.getReturnType()->isVoidTy()) 11301 report_fatal_error( 11302 "Functions with the interrupt attribute must have void return type!"); 11303 11304 MachineFunction &MF = DAG.getMachineFunction(); 11305 StringRef Kind = 11306 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 11307 11308 if (Kind == "user") 11309 RetOpc = RISCVISD::URET_FLAG; 11310 else if (Kind == "supervisor") 11311 RetOpc = RISCVISD::SRET_FLAG; 11312 else 11313 RetOpc = RISCVISD::MRET_FLAG; 11314 } 11315 11316 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 11317 } 11318 11319 void RISCVTargetLowering::validateCCReservedRegs( 11320 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 11321 MachineFunction &MF) const { 11322 const Function &F = MF.getFunction(); 11323 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 11324 11325 if (llvm::any_of(Regs, [&STI](auto Reg) { 11326 return STI.isRegisterReservedByUser(Reg.first); 11327 })) 11328 F.getContext().diagnose(DiagnosticInfoUnsupported{ 11329 F, "Argument register required, but has been reserved."}); 11330 } 11331 11332 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 11333 return CI->isTailCall(); 11334 } 11335 11336 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 11337 #define NODE_NAME_CASE(NODE) \ 11338 case RISCVISD::NODE: \ 11339 return "RISCVISD::" #NODE; 11340 // clang-format off 11341 switch ((RISCVISD::NodeType)Opcode) { 11342 case RISCVISD::FIRST_NUMBER: 11343 break; 11344 NODE_NAME_CASE(RET_FLAG) 11345 NODE_NAME_CASE(URET_FLAG) 11346 NODE_NAME_CASE(SRET_FLAG) 11347 NODE_NAME_CASE(MRET_FLAG) 11348 NODE_NAME_CASE(CALL) 11349 NODE_NAME_CASE(SELECT_CC) 11350 NODE_NAME_CASE(BR_CC) 11351 NODE_NAME_CASE(BuildPairF64) 11352 NODE_NAME_CASE(SplitF64) 11353 NODE_NAME_CASE(TAIL) 11354 NODE_NAME_CASE(ADD_LO) 11355 NODE_NAME_CASE(HI) 11356 NODE_NAME_CASE(LLA) 11357 NODE_NAME_CASE(ADD_TPREL) 11358 NODE_NAME_CASE(LA) 11359 NODE_NAME_CASE(LA_TLS_IE) 11360 NODE_NAME_CASE(LA_TLS_GD) 11361 NODE_NAME_CASE(MULHSU) 11362 NODE_NAME_CASE(SLLW) 11363 NODE_NAME_CASE(SRAW) 11364 NODE_NAME_CASE(SRLW) 11365 NODE_NAME_CASE(DIVW) 11366 NODE_NAME_CASE(DIVUW) 11367 NODE_NAME_CASE(REMUW) 11368 NODE_NAME_CASE(ROLW) 11369 NODE_NAME_CASE(RORW) 11370 NODE_NAME_CASE(CLZW) 11371 NODE_NAME_CASE(CTZW) 11372 NODE_NAME_CASE(FSLW) 11373 NODE_NAME_CASE(FSRW) 11374 NODE_NAME_CASE(FSL) 11375 NODE_NAME_CASE(FSR) 11376 NODE_NAME_CASE(FMV_H_X) 11377 NODE_NAME_CASE(FMV_X_ANYEXTH) 11378 NODE_NAME_CASE(FMV_X_SIGNEXTH) 11379 NODE_NAME_CASE(FMV_W_X_RV64) 11380 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 11381 NODE_NAME_CASE(FCVT_X) 11382 NODE_NAME_CASE(FCVT_XU) 11383 NODE_NAME_CASE(FCVT_W_RV64) 11384 NODE_NAME_CASE(FCVT_WU_RV64) 11385 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 11386 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 11387 NODE_NAME_CASE(READ_CYCLE_WIDE) 11388 NODE_NAME_CASE(GREV) 11389 NODE_NAME_CASE(GREVW) 11390 NODE_NAME_CASE(GORC) 11391 NODE_NAME_CASE(GORCW) 11392 NODE_NAME_CASE(SHFL) 11393 NODE_NAME_CASE(SHFLW) 11394 NODE_NAME_CASE(UNSHFL) 11395 NODE_NAME_CASE(UNSHFLW) 11396 NODE_NAME_CASE(BFP) 11397 NODE_NAME_CASE(BFPW) 11398 NODE_NAME_CASE(BCOMPRESS) 11399 NODE_NAME_CASE(BCOMPRESSW) 11400 NODE_NAME_CASE(BDECOMPRESS) 11401 NODE_NAME_CASE(BDECOMPRESSW) 11402 NODE_NAME_CASE(VMV_V_X_VL) 11403 NODE_NAME_CASE(VFMV_V_F_VL) 11404 NODE_NAME_CASE(VMV_X_S) 11405 NODE_NAME_CASE(VMV_S_X_VL) 11406 NODE_NAME_CASE(VFMV_S_F_VL) 11407 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 11408 NODE_NAME_CASE(READ_VLENB) 11409 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 11410 NODE_NAME_CASE(VSLIDEUP_VL) 11411 NODE_NAME_CASE(VSLIDE1UP_VL) 11412 NODE_NAME_CASE(VSLIDEDOWN_VL) 11413 NODE_NAME_CASE(VSLIDE1DOWN_VL) 11414 NODE_NAME_CASE(VID_VL) 11415 NODE_NAME_CASE(VFNCVT_ROD_VL) 11416 NODE_NAME_CASE(VECREDUCE_ADD_VL) 11417 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 11418 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 11419 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 11420 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 11421 NODE_NAME_CASE(VECREDUCE_AND_VL) 11422 NODE_NAME_CASE(VECREDUCE_OR_VL) 11423 NODE_NAME_CASE(VECREDUCE_XOR_VL) 11424 NODE_NAME_CASE(VECREDUCE_FADD_VL) 11425 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 11426 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 11427 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 11428 NODE_NAME_CASE(ADD_VL) 11429 NODE_NAME_CASE(AND_VL) 11430 NODE_NAME_CASE(MUL_VL) 11431 NODE_NAME_CASE(OR_VL) 11432 NODE_NAME_CASE(SDIV_VL) 11433 NODE_NAME_CASE(SHL_VL) 11434 NODE_NAME_CASE(SREM_VL) 11435 NODE_NAME_CASE(SRA_VL) 11436 NODE_NAME_CASE(SRL_VL) 11437 NODE_NAME_CASE(SUB_VL) 11438 NODE_NAME_CASE(UDIV_VL) 11439 NODE_NAME_CASE(UREM_VL) 11440 NODE_NAME_CASE(XOR_VL) 11441 NODE_NAME_CASE(SADDSAT_VL) 11442 NODE_NAME_CASE(UADDSAT_VL) 11443 NODE_NAME_CASE(SSUBSAT_VL) 11444 NODE_NAME_CASE(USUBSAT_VL) 11445 NODE_NAME_CASE(FADD_VL) 11446 NODE_NAME_CASE(FSUB_VL) 11447 NODE_NAME_CASE(FMUL_VL) 11448 NODE_NAME_CASE(FDIV_VL) 11449 NODE_NAME_CASE(FNEG_VL) 11450 NODE_NAME_CASE(FABS_VL) 11451 NODE_NAME_CASE(FSQRT_VL) 11452 NODE_NAME_CASE(VFMADD_VL) 11453 NODE_NAME_CASE(VFNMADD_VL) 11454 NODE_NAME_CASE(VFMSUB_VL) 11455 NODE_NAME_CASE(VFNMSUB_VL) 11456 NODE_NAME_CASE(FCOPYSIGN_VL) 11457 NODE_NAME_CASE(SMIN_VL) 11458 NODE_NAME_CASE(SMAX_VL) 11459 NODE_NAME_CASE(UMIN_VL) 11460 NODE_NAME_CASE(UMAX_VL) 11461 NODE_NAME_CASE(FMINNUM_VL) 11462 NODE_NAME_CASE(FMAXNUM_VL) 11463 NODE_NAME_CASE(MULHS_VL) 11464 NODE_NAME_CASE(MULHU_VL) 11465 NODE_NAME_CASE(FP_TO_SINT_VL) 11466 NODE_NAME_CASE(FP_TO_UINT_VL) 11467 NODE_NAME_CASE(SINT_TO_FP_VL) 11468 NODE_NAME_CASE(UINT_TO_FP_VL) 11469 NODE_NAME_CASE(FP_EXTEND_VL) 11470 NODE_NAME_CASE(FP_ROUND_VL) 11471 NODE_NAME_CASE(VWMUL_VL) 11472 NODE_NAME_CASE(VWMULU_VL) 11473 NODE_NAME_CASE(VWMULSU_VL) 11474 NODE_NAME_CASE(VWADD_VL) 11475 NODE_NAME_CASE(VWADDU_VL) 11476 NODE_NAME_CASE(VWSUB_VL) 11477 NODE_NAME_CASE(VWSUBU_VL) 11478 NODE_NAME_CASE(VWADD_W_VL) 11479 NODE_NAME_CASE(VWADDU_W_VL) 11480 NODE_NAME_CASE(VWSUB_W_VL) 11481 NODE_NAME_CASE(VWSUBU_W_VL) 11482 NODE_NAME_CASE(SETCC_VL) 11483 NODE_NAME_CASE(VSELECT_VL) 11484 NODE_NAME_CASE(VP_MERGE_VL) 11485 NODE_NAME_CASE(VMAND_VL) 11486 NODE_NAME_CASE(VMOR_VL) 11487 NODE_NAME_CASE(VMXOR_VL) 11488 NODE_NAME_CASE(VMCLR_VL) 11489 NODE_NAME_CASE(VMSET_VL) 11490 NODE_NAME_CASE(VRGATHER_VX_VL) 11491 NODE_NAME_CASE(VRGATHER_VV_VL) 11492 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 11493 NODE_NAME_CASE(VSEXT_VL) 11494 NODE_NAME_CASE(VZEXT_VL) 11495 NODE_NAME_CASE(VCPOP_VL) 11496 NODE_NAME_CASE(READ_CSR) 11497 NODE_NAME_CASE(WRITE_CSR) 11498 NODE_NAME_CASE(SWAP_CSR) 11499 } 11500 // clang-format on 11501 return nullptr; 11502 #undef NODE_NAME_CASE 11503 } 11504 11505 /// getConstraintType - Given a constraint letter, return the type of 11506 /// constraint it is for this target. 11507 RISCVTargetLowering::ConstraintType 11508 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 11509 if (Constraint.size() == 1) { 11510 switch (Constraint[0]) { 11511 default: 11512 break; 11513 case 'f': 11514 return C_RegisterClass; 11515 case 'I': 11516 case 'J': 11517 case 'K': 11518 return C_Immediate; 11519 case 'A': 11520 return C_Memory; 11521 case 'S': // A symbolic address 11522 return C_Other; 11523 } 11524 } else { 11525 if (Constraint == "vr" || Constraint == "vm") 11526 return C_RegisterClass; 11527 } 11528 return TargetLowering::getConstraintType(Constraint); 11529 } 11530 11531 std::pair<unsigned, const TargetRegisterClass *> 11532 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11533 StringRef Constraint, 11534 MVT VT) const { 11535 // First, see if this is a constraint that directly corresponds to a 11536 // RISCV register class. 11537 if (Constraint.size() == 1) { 11538 switch (Constraint[0]) { 11539 case 'r': 11540 // TODO: Support fixed vectors up to XLen for P extension? 11541 if (VT.isVector()) 11542 break; 11543 return std::make_pair(0U, &RISCV::GPRRegClass); 11544 case 'f': 11545 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 11546 return std::make_pair(0U, &RISCV::FPR16RegClass); 11547 if (Subtarget.hasStdExtF() && VT == MVT::f32) 11548 return std::make_pair(0U, &RISCV::FPR32RegClass); 11549 if (Subtarget.hasStdExtD() && VT == MVT::f64) 11550 return std::make_pair(0U, &RISCV::FPR64RegClass); 11551 break; 11552 default: 11553 break; 11554 } 11555 } else if (Constraint == "vr") { 11556 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 11557 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11558 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 11559 return std::make_pair(0U, RC); 11560 } 11561 } else if (Constraint == "vm") { 11562 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 11563 return std::make_pair(0U, &RISCV::VMV0RegClass); 11564 } 11565 11566 // Clang will correctly decode the usage of register name aliases into their 11567 // official names. However, other frontends like `rustc` do not. This allows 11568 // users of these frontends to use the ABI names for registers in LLVM-style 11569 // register constraints. 11570 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 11571 .Case("{zero}", RISCV::X0) 11572 .Case("{ra}", RISCV::X1) 11573 .Case("{sp}", RISCV::X2) 11574 .Case("{gp}", RISCV::X3) 11575 .Case("{tp}", RISCV::X4) 11576 .Case("{t0}", RISCV::X5) 11577 .Case("{t1}", RISCV::X6) 11578 .Case("{t2}", RISCV::X7) 11579 .Cases("{s0}", "{fp}", RISCV::X8) 11580 .Case("{s1}", RISCV::X9) 11581 .Case("{a0}", RISCV::X10) 11582 .Case("{a1}", RISCV::X11) 11583 .Case("{a2}", RISCV::X12) 11584 .Case("{a3}", RISCV::X13) 11585 .Case("{a4}", RISCV::X14) 11586 .Case("{a5}", RISCV::X15) 11587 .Case("{a6}", RISCV::X16) 11588 .Case("{a7}", RISCV::X17) 11589 .Case("{s2}", RISCV::X18) 11590 .Case("{s3}", RISCV::X19) 11591 .Case("{s4}", RISCV::X20) 11592 .Case("{s5}", RISCV::X21) 11593 .Case("{s6}", RISCV::X22) 11594 .Case("{s7}", RISCV::X23) 11595 .Case("{s8}", RISCV::X24) 11596 .Case("{s9}", RISCV::X25) 11597 .Case("{s10}", RISCV::X26) 11598 .Case("{s11}", RISCV::X27) 11599 .Case("{t3}", RISCV::X28) 11600 .Case("{t4}", RISCV::X29) 11601 .Case("{t5}", RISCV::X30) 11602 .Case("{t6}", RISCV::X31) 11603 .Default(RISCV::NoRegister); 11604 if (XRegFromAlias != RISCV::NoRegister) 11605 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 11606 11607 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 11608 // TableGen record rather than the AsmName to choose registers for InlineAsm 11609 // constraints, plus we want to match those names to the widest floating point 11610 // register type available, manually select floating point registers here. 11611 // 11612 // The second case is the ABI name of the register, so that frontends can also 11613 // use the ABI names in register constraint lists. 11614 if (Subtarget.hasStdExtF()) { 11615 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 11616 .Cases("{f0}", "{ft0}", RISCV::F0_F) 11617 .Cases("{f1}", "{ft1}", RISCV::F1_F) 11618 .Cases("{f2}", "{ft2}", RISCV::F2_F) 11619 .Cases("{f3}", "{ft3}", RISCV::F3_F) 11620 .Cases("{f4}", "{ft4}", RISCV::F4_F) 11621 .Cases("{f5}", "{ft5}", RISCV::F5_F) 11622 .Cases("{f6}", "{ft6}", RISCV::F6_F) 11623 .Cases("{f7}", "{ft7}", RISCV::F7_F) 11624 .Cases("{f8}", "{fs0}", RISCV::F8_F) 11625 .Cases("{f9}", "{fs1}", RISCV::F9_F) 11626 .Cases("{f10}", "{fa0}", RISCV::F10_F) 11627 .Cases("{f11}", "{fa1}", RISCV::F11_F) 11628 .Cases("{f12}", "{fa2}", RISCV::F12_F) 11629 .Cases("{f13}", "{fa3}", RISCV::F13_F) 11630 .Cases("{f14}", "{fa4}", RISCV::F14_F) 11631 .Cases("{f15}", "{fa5}", RISCV::F15_F) 11632 .Cases("{f16}", "{fa6}", RISCV::F16_F) 11633 .Cases("{f17}", "{fa7}", RISCV::F17_F) 11634 .Cases("{f18}", "{fs2}", RISCV::F18_F) 11635 .Cases("{f19}", "{fs3}", RISCV::F19_F) 11636 .Cases("{f20}", "{fs4}", RISCV::F20_F) 11637 .Cases("{f21}", "{fs5}", RISCV::F21_F) 11638 .Cases("{f22}", "{fs6}", RISCV::F22_F) 11639 .Cases("{f23}", "{fs7}", RISCV::F23_F) 11640 .Cases("{f24}", "{fs8}", RISCV::F24_F) 11641 .Cases("{f25}", "{fs9}", RISCV::F25_F) 11642 .Cases("{f26}", "{fs10}", RISCV::F26_F) 11643 .Cases("{f27}", "{fs11}", RISCV::F27_F) 11644 .Cases("{f28}", "{ft8}", RISCV::F28_F) 11645 .Cases("{f29}", "{ft9}", RISCV::F29_F) 11646 .Cases("{f30}", "{ft10}", RISCV::F30_F) 11647 .Cases("{f31}", "{ft11}", RISCV::F31_F) 11648 .Default(RISCV::NoRegister); 11649 if (FReg != RISCV::NoRegister) { 11650 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 11651 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 11652 unsigned RegNo = FReg - RISCV::F0_F; 11653 unsigned DReg = RISCV::F0_D + RegNo; 11654 return std::make_pair(DReg, &RISCV::FPR64RegClass); 11655 } 11656 if (VT == MVT::f32 || VT == MVT::Other) 11657 return std::make_pair(FReg, &RISCV::FPR32RegClass); 11658 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 11659 unsigned RegNo = FReg - RISCV::F0_F; 11660 unsigned HReg = RISCV::F0_H + RegNo; 11661 return std::make_pair(HReg, &RISCV::FPR16RegClass); 11662 } 11663 } 11664 } 11665 11666 if (Subtarget.hasVInstructions()) { 11667 Register VReg = StringSwitch<Register>(Constraint.lower()) 11668 .Case("{v0}", RISCV::V0) 11669 .Case("{v1}", RISCV::V1) 11670 .Case("{v2}", RISCV::V2) 11671 .Case("{v3}", RISCV::V3) 11672 .Case("{v4}", RISCV::V4) 11673 .Case("{v5}", RISCV::V5) 11674 .Case("{v6}", RISCV::V6) 11675 .Case("{v7}", RISCV::V7) 11676 .Case("{v8}", RISCV::V8) 11677 .Case("{v9}", RISCV::V9) 11678 .Case("{v10}", RISCV::V10) 11679 .Case("{v11}", RISCV::V11) 11680 .Case("{v12}", RISCV::V12) 11681 .Case("{v13}", RISCV::V13) 11682 .Case("{v14}", RISCV::V14) 11683 .Case("{v15}", RISCV::V15) 11684 .Case("{v16}", RISCV::V16) 11685 .Case("{v17}", RISCV::V17) 11686 .Case("{v18}", RISCV::V18) 11687 .Case("{v19}", RISCV::V19) 11688 .Case("{v20}", RISCV::V20) 11689 .Case("{v21}", RISCV::V21) 11690 .Case("{v22}", RISCV::V22) 11691 .Case("{v23}", RISCV::V23) 11692 .Case("{v24}", RISCV::V24) 11693 .Case("{v25}", RISCV::V25) 11694 .Case("{v26}", RISCV::V26) 11695 .Case("{v27}", RISCV::V27) 11696 .Case("{v28}", RISCV::V28) 11697 .Case("{v29}", RISCV::V29) 11698 .Case("{v30}", RISCV::V30) 11699 .Case("{v31}", RISCV::V31) 11700 .Default(RISCV::NoRegister); 11701 if (VReg != RISCV::NoRegister) { 11702 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11703 return std::make_pair(VReg, &RISCV::VMRegClass); 11704 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11705 return std::make_pair(VReg, &RISCV::VRRegClass); 11706 for (const auto *RC : 11707 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11708 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11709 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11710 return std::make_pair(VReg, RC); 11711 } 11712 } 11713 } 11714 } 11715 11716 std::pair<Register, const TargetRegisterClass *> Res = 11717 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11718 11719 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11720 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11721 // Subtarget into account. 11722 if (Res.second == &RISCV::GPRF16RegClass || 11723 Res.second == &RISCV::GPRF32RegClass || 11724 Res.second == &RISCV::GPRF64RegClass) 11725 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11726 11727 return Res; 11728 } 11729 11730 unsigned 11731 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11732 // Currently only support length 1 constraints. 11733 if (ConstraintCode.size() == 1) { 11734 switch (ConstraintCode[0]) { 11735 case 'A': 11736 return InlineAsm::Constraint_A; 11737 default: 11738 break; 11739 } 11740 } 11741 11742 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11743 } 11744 11745 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11746 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11747 SelectionDAG &DAG) const { 11748 // Currently only support length 1 constraints. 11749 if (Constraint.length() == 1) { 11750 switch (Constraint[0]) { 11751 case 'I': 11752 // Validate & create a 12-bit signed immediate operand. 11753 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11754 uint64_t CVal = C->getSExtValue(); 11755 if (isInt<12>(CVal)) 11756 Ops.push_back( 11757 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11758 } 11759 return; 11760 case 'J': 11761 // Validate & create an integer zero operand. 11762 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11763 if (C->getZExtValue() == 0) 11764 Ops.push_back( 11765 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11766 return; 11767 case 'K': 11768 // Validate & create a 5-bit unsigned immediate operand. 11769 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11770 uint64_t CVal = C->getZExtValue(); 11771 if (isUInt<5>(CVal)) 11772 Ops.push_back( 11773 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11774 } 11775 return; 11776 case 'S': 11777 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11778 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11779 GA->getValueType(0))); 11780 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11781 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11782 BA->getValueType(0))); 11783 } 11784 return; 11785 default: 11786 break; 11787 } 11788 } 11789 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11790 } 11791 11792 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11793 Instruction *Inst, 11794 AtomicOrdering Ord) const { 11795 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 11796 return Builder.CreateFence(Ord); 11797 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 11798 return Builder.CreateFence(AtomicOrdering::Release); 11799 return nullptr; 11800 } 11801 11802 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11803 Instruction *Inst, 11804 AtomicOrdering Ord) const { 11805 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11806 return Builder.CreateFence(AtomicOrdering::Acquire); 11807 return nullptr; 11808 } 11809 11810 TargetLowering::AtomicExpansionKind 11811 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11812 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11813 // point operations can't be used in an lr/sc sequence without breaking the 11814 // forward-progress guarantee. 11815 if (AI->isFloatingPointOperation()) 11816 return AtomicExpansionKind::CmpXChg; 11817 11818 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11819 if (Size == 8 || Size == 16) 11820 return AtomicExpansionKind::MaskedIntrinsic; 11821 return AtomicExpansionKind::None; 11822 } 11823 11824 static Intrinsic::ID 11825 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11826 if (XLen == 32) { 11827 switch (BinOp) { 11828 default: 11829 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11830 case AtomicRMWInst::Xchg: 11831 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11832 case AtomicRMWInst::Add: 11833 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11834 case AtomicRMWInst::Sub: 11835 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11836 case AtomicRMWInst::Nand: 11837 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11838 case AtomicRMWInst::Max: 11839 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11840 case AtomicRMWInst::Min: 11841 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11842 case AtomicRMWInst::UMax: 11843 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11844 case AtomicRMWInst::UMin: 11845 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11846 } 11847 } 11848 11849 if (XLen == 64) { 11850 switch (BinOp) { 11851 default: 11852 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11853 case AtomicRMWInst::Xchg: 11854 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11855 case AtomicRMWInst::Add: 11856 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11857 case AtomicRMWInst::Sub: 11858 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11859 case AtomicRMWInst::Nand: 11860 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11861 case AtomicRMWInst::Max: 11862 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11863 case AtomicRMWInst::Min: 11864 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11865 case AtomicRMWInst::UMax: 11866 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11867 case AtomicRMWInst::UMin: 11868 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11869 } 11870 } 11871 11872 llvm_unreachable("Unexpected XLen\n"); 11873 } 11874 11875 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11876 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11877 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11878 unsigned XLen = Subtarget.getXLen(); 11879 Value *Ordering = 11880 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11881 Type *Tys[] = {AlignedAddr->getType()}; 11882 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11883 AI->getModule(), 11884 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11885 11886 if (XLen == 64) { 11887 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11888 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11889 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11890 } 11891 11892 Value *Result; 11893 11894 // Must pass the shift amount needed to sign extend the loaded value prior 11895 // to performing a signed comparison for min/max. ShiftAmt is the number of 11896 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11897 // is the number of bits to left+right shift the value in order to 11898 // sign-extend. 11899 if (AI->getOperation() == AtomicRMWInst::Min || 11900 AI->getOperation() == AtomicRMWInst::Max) { 11901 const DataLayout &DL = AI->getModule()->getDataLayout(); 11902 unsigned ValWidth = 11903 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11904 Value *SextShamt = 11905 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11906 Result = Builder.CreateCall(LrwOpScwLoop, 11907 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11908 } else { 11909 Result = 11910 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11911 } 11912 11913 if (XLen == 64) 11914 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11915 return Result; 11916 } 11917 11918 TargetLowering::AtomicExpansionKind 11919 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11920 AtomicCmpXchgInst *CI) const { 11921 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11922 if (Size == 8 || Size == 16) 11923 return AtomicExpansionKind::MaskedIntrinsic; 11924 return AtomicExpansionKind::None; 11925 } 11926 11927 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11928 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11929 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11930 unsigned XLen = Subtarget.getXLen(); 11931 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11932 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11933 if (XLen == 64) { 11934 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11935 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11936 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11937 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11938 } 11939 Type *Tys[] = {AlignedAddr->getType()}; 11940 Function *MaskedCmpXchg = 11941 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11942 Value *Result = Builder.CreateCall( 11943 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11944 if (XLen == 64) 11945 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11946 return Result; 11947 } 11948 11949 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT, 11950 EVT DataVT) const { 11951 return false; 11952 } 11953 11954 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11955 EVT VT) const { 11956 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11957 return false; 11958 11959 switch (FPVT.getSimpleVT().SimpleTy) { 11960 case MVT::f16: 11961 return Subtarget.hasStdExtZfh(); 11962 case MVT::f32: 11963 return Subtarget.hasStdExtF(); 11964 case MVT::f64: 11965 return Subtarget.hasStdExtD(); 11966 default: 11967 return false; 11968 } 11969 } 11970 11971 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11972 // If we are using the small code model, we can reduce size of jump table 11973 // entry to 4 bytes. 11974 if (Subtarget.is64Bit() && !isPositionIndependent() && 11975 getTargetMachine().getCodeModel() == CodeModel::Small) { 11976 return MachineJumpTableInfo::EK_Custom32; 11977 } 11978 return TargetLowering::getJumpTableEncoding(); 11979 } 11980 11981 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 11982 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 11983 unsigned uid, MCContext &Ctx) const { 11984 assert(Subtarget.is64Bit() && !isPositionIndependent() && 11985 getTargetMachine().getCodeModel() == CodeModel::Small); 11986 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 11987 } 11988 11989 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 11990 EVT VT) const { 11991 VT = VT.getScalarType(); 11992 11993 if (!VT.isSimple()) 11994 return false; 11995 11996 switch (VT.getSimpleVT().SimpleTy) { 11997 case MVT::f16: 11998 return Subtarget.hasStdExtZfh(); 11999 case MVT::f32: 12000 return Subtarget.hasStdExtF(); 12001 case MVT::f64: 12002 return Subtarget.hasStdExtD(); 12003 default: 12004 break; 12005 } 12006 12007 return false; 12008 } 12009 12010 Register RISCVTargetLowering::getExceptionPointerRegister( 12011 const Constant *PersonalityFn) const { 12012 return RISCV::X10; 12013 } 12014 12015 Register RISCVTargetLowering::getExceptionSelectorRegister( 12016 const Constant *PersonalityFn) const { 12017 return RISCV::X11; 12018 } 12019 12020 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 12021 // Return false to suppress the unnecessary extensions if the LibCall 12022 // arguments or return value is f32 type for LP64 ABI. 12023 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 12024 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 12025 return false; 12026 12027 return true; 12028 } 12029 12030 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 12031 if (Subtarget.is64Bit() && Type == MVT::i32) 12032 return true; 12033 12034 return IsSigned; 12035 } 12036 12037 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 12038 SDValue C) const { 12039 // Check integral scalar types. 12040 if (VT.isScalarInteger()) { 12041 // Omit the optimization if the sub target has the M extension and the data 12042 // size exceeds XLen. 12043 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 12044 return false; 12045 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 12046 // Break the MUL to a SLLI and an ADD/SUB. 12047 const APInt &Imm = ConstNode->getAPIntValue(); 12048 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 12049 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 12050 return true; 12051 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 12052 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 12053 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 12054 (Imm - 8).isPowerOf2())) 12055 return true; 12056 // Omit the following optimization if the sub target has the M extension 12057 // and the data size >= XLen. 12058 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 12059 return false; 12060 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 12061 // a pair of LUI/ADDI. 12062 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 12063 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 12064 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 12065 (1 - ImmS).isPowerOf2()) 12066 return true; 12067 } 12068 } 12069 } 12070 12071 return false; 12072 } 12073 12074 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 12075 SDValue ConstNode) const { 12076 // Let the DAGCombiner decide for vectors. 12077 EVT VT = AddNode.getValueType(); 12078 if (VT.isVector()) 12079 return true; 12080 12081 // Let the DAGCombiner decide for larger types. 12082 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 12083 return true; 12084 12085 // It is worse if c1 is simm12 while c1*c2 is not. 12086 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 12087 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 12088 const APInt &C1 = C1Node->getAPIntValue(); 12089 const APInt &C2 = C2Node->getAPIntValue(); 12090 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 12091 return false; 12092 12093 // Default to true and let the DAGCombiner decide. 12094 return true; 12095 } 12096 12097 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 12098 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 12099 bool *Fast) const { 12100 if (!VT.isVector()) { 12101 if (Fast) 12102 *Fast = false; 12103 return Subtarget.enableUnalignedScalarMem(); 12104 } 12105 12106 // All vector implementations must support element alignment 12107 EVT ElemVT = VT.getVectorElementType(); 12108 if (Alignment >= ElemVT.getStoreSize()) { 12109 if (Fast) 12110 *Fast = true; 12111 return true; 12112 } 12113 12114 return false; 12115 } 12116 12117 bool RISCVTargetLowering::splitValueIntoRegisterParts( 12118 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 12119 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 12120 bool IsABIRegCopy = CC.has_value(); 12121 EVT ValueVT = Val.getValueType(); 12122 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 12123 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 12124 // and cast to f32. 12125 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 12126 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 12127 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 12128 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 12129 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 12130 Parts[0] = Val; 12131 return true; 12132 } 12133 12134 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 12135 LLVMContext &Context = *DAG.getContext(); 12136 EVT ValueEltVT = ValueVT.getVectorElementType(); 12137 EVT PartEltVT = PartVT.getVectorElementType(); 12138 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 12139 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 12140 if (PartVTBitSize % ValueVTBitSize == 0) { 12141 assert(PartVTBitSize >= ValueVTBitSize); 12142 // If the element types are different, bitcast to the same element type of 12143 // PartVT first. 12144 // Give an example here, we want copy a <vscale x 1 x i8> value to 12145 // <vscale x 4 x i16>. 12146 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 12147 // subvector, then we can bitcast to <vscale x 4 x i16>. 12148 if (ValueEltVT != PartEltVT) { 12149 if (PartVTBitSize > ValueVTBitSize) { 12150 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 12151 assert(Count != 0 && "The number of element should not be zero."); 12152 EVT SameEltTypeVT = 12153 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 12154 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 12155 DAG.getUNDEF(SameEltTypeVT), Val, 12156 DAG.getVectorIdxConstant(0, DL)); 12157 } 12158 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 12159 } else { 12160 Val = 12161 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 12162 Val, DAG.getVectorIdxConstant(0, DL)); 12163 } 12164 Parts[0] = Val; 12165 return true; 12166 } 12167 } 12168 return false; 12169 } 12170 12171 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 12172 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 12173 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 12174 bool IsABIRegCopy = CC.has_value(); 12175 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 12176 SDValue Val = Parts[0]; 12177 12178 // Cast the f32 to i32, truncate to i16, and cast back to f16. 12179 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 12180 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 12181 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 12182 return Val; 12183 } 12184 12185 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 12186 LLVMContext &Context = *DAG.getContext(); 12187 SDValue Val = Parts[0]; 12188 EVT ValueEltVT = ValueVT.getVectorElementType(); 12189 EVT PartEltVT = PartVT.getVectorElementType(); 12190 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 12191 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 12192 if (PartVTBitSize % ValueVTBitSize == 0) { 12193 assert(PartVTBitSize >= ValueVTBitSize); 12194 EVT SameEltTypeVT = ValueVT; 12195 // If the element types are different, convert it to the same element type 12196 // of PartVT. 12197 // Give an example here, we want copy a <vscale x 1 x i8> value from 12198 // <vscale x 4 x i16>. 12199 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 12200 // then we can extract <vscale x 1 x i8>. 12201 if (ValueEltVT != PartEltVT) { 12202 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 12203 assert(Count != 0 && "The number of element should not be zero."); 12204 SameEltTypeVT = 12205 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 12206 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 12207 } 12208 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 12209 DAG.getVectorIdxConstant(0, DL)); 12210 return Val; 12211 } 12212 } 12213 return SDValue(); 12214 } 12215 12216 SDValue 12217 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 12218 SelectionDAG &DAG, 12219 SmallVectorImpl<SDNode *> &Created) const { 12220 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 12221 if (isIntDivCheap(N->getValueType(0), Attr)) 12222 return SDValue(N, 0); // Lower SDIV as SDIV 12223 12224 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 12225 "Unexpected divisor!"); 12226 12227 // Conditional move is needed, so do the transformation iff Zbt is enabled. 12228 if (!Subtarget.hasStdExtZbt()) 12229 return SDValue(); 12230 12231 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 12232 // Besides, more critical path instructions will be generated when dividing 12233 // by 2. So we keep using the original DAGs for these cases. 12234 unsigned Lg2 = Divisor.countTrailingZeros(); 12235 if (Lg2 == 1 || Lg2 >= 12) 12236 return SDValue(); 12237 12238 // fold (sdiv X, pow2) 12239 EVT VT = N->getValueType(0); 12240 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 12241 return SDValue(); 12242 12243 SDLoc DL(N); 12244 SDValue N0 = N->getOperand(0); 12245 SDValue Zero = DAG.getConstant(0, DL, VT); 12246 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 12247 12248 // Add (N0 < 0) ? Pow2 - 1 : 0; 12249 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 12250 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 12251 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 12252 12253 Created.push_back(Cmp.getNode()); 12254 Created.push_back(Add.getNode()); 12255 Created.push_back(Sel.getNode()); 12256 12257 // Divide by pow2. 12258 SDValue SRA = 12259 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 12260 12261 // If we're dividing by a positive value, we're done. Otherwise, we must 12262 // negate the result. 12263 if (Divisor.isNonNegative()) 12264 return SRA; 12265 12266 Created.push_back(SRA.getNode()); 12267 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 12268 } 12269 12270 #define GET_REGISTER_MATCHER 12271 #include "RISCVGenAsmMatcher.inc" 12272 12273 Register 12274 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 12275 const MachineFunction &MF) const { 12276 Register Reg = MatchRegisterAltName(RegName); 12277 if (Reg == RISCV::NoRegister) 12278 Reg = MatchRegisterName(RegName); 12279 if (Reg == RISCV::NoRegister) 12280 report_fatal_error( 12281 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 12282 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 12283 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 12284 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 12285 StringRef(RegName) + "\".")); 12286 return Reg; 12287 } 12288 12289 namespace llvm { 12290 namespace RISCVVIntrinsicsTable { 12291 12292 #define GET_RISCVVIntrinsicsTable_IMPL 12293 #include "RISCVGenSearchableTables.inc" 12294 12295 } // namespace RISCVVIntrinsicsTable 12296 12297 } // namespace llvm 12298