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() && !Subtarget.hasStdExtZmmul()) { 219 setOperationAction({ISD::MUL, ISD::MULHS, ISD::MULHU}, XLenVT, Expand); 220 } else { 221 if (Subtarget.is64Bit()) { 222 setOperationAction(ISD::MUL, {MVT::i32, MVT::i128}, Custom); 223 } else { 224 setOperationAction(ISD::MUL, MVT::i64, Custom); 225 } 226 } 227 228 if (!Subtarget.hasStdExtM()) { 229 setOperationAction({ISD::SDIV, ISD::UDIV, ISD::SREM, ISD::UREM}, 230 XLenVT, Expand); 231 } else { 232 if (Subtarget.is64Bit()) { 233 setOperationAction({ISD::SDIV, ISD::UDIV, ISD::UREM}, 234 {MVT::i8, MVT::i16, MVT::i32}, Custom); 235 } 236 } 237 238 setOperationAction( 239 {ISD::SDIVREM, ISD::UDIVREM, ISD::SMUL_LOHI, ISD::UMUL_LOHI}, XLenVT, 240 Expand); 241 242 setOperationAction({ISD::SHL_PARTS, ISD::SRL_PARTS, ISD::SRA_PARTS}, XLenVT, 243 Custom); 244 245 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 246 Subtarget.hasStdExtZbkb()) { 247 if (Subtarget.is64Bit()) 248 setOperationAction({ISD::ROTL, ISD::ROTR}, MVT::i32, Custom); 249 } else { 250 setOperationAction({ISD::ROTL, ISD::ROTR}, XLenVT, Expand); 251 } 252 253 if (Subtarget.hasStdExtZbp()) { 254 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 255 // more combining. 256 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, XLenVT, Custom); 257 258 // BSWAP i8 doesn't exist. 259 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 260 261 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i16, Custom); 262 263 if (Subtarget.is64Bit()) 264 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i32, Custom); 265 } else { 266 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 267 // pattern match it directly in isel. 268 setOperationAction(ISD::BSWAP, XLenVT, 269 (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) 270 ? Legal 271 : Expand); 272 // Zbkb can use rev8+brev8 to implement bitreverse. 273 setOperationAction(ISD::BITREVERSE, XLenVT, 274 Subtarget.hasStdExtZbkb() ? Custom : Expand); 275 } 276 277 if (Subtarget.hasStdExtZbb()) { 278 setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, XLenVT, 279 Legal); 280 281 if (Subtarget.is64Bit()) 282 setOperationAction( 283 {ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF}, 284 MVT::i32, Custom); 285 } else { 286 setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP}, XLenVT, Expand); 287 288 if (Subtarget.is64Bit()) 289 setOperationAction(ISD::ABS, MVT::i32, Custom); 290 } 291 292 if (Subtarget.hasStdExtZbt()) { 293 setOperationAction({ISD::FSHL, ISD::FSHR}, XLenVT, Custom); 294 setOperationAction(ISD::SELECT, XLenVT, Legal); 295 296 if (Subtarget.is64Bit()) 297 setOperationAction({ISD::FSHL, ISD::FSHR}, MVT::i32, Custom); 298 } else { 299 setOperationAction(ISD::SELECT, XLenVT, Custom); 300 } 301 302 static const unsigned FPLegalNodeTypes[] = { 303 ISD::FMINNUM, ISD::FMAXNUM, ISD::LRINT, 304 ISD::LLRINT, ISD::LROUND, ISD::LLROUND, 305 ISD::STRICT_LRINT, ISD::STRICT_LLRINT, ISD::STRICT_LROUND, 306 ISD::STRICT_LLROUND, ISD::STRICT_FMA, ISD::STRICT_FADD, 307 ISD::STRICT_FSUB, ISD::STRICT_FMUL, ISD::STRICT_FDIV, 308 ISD::STRICT_FSQRT, ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS}; 309 310 static const ISD::CondCode FPCCToExpand[] = { 311 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 312 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 313 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 314 315 static const unsigned FPOpToExpand[] = { 316 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 317 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 318 319 if (Subtarget.hasStdExtZfh()) 320 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 321 322 if (Subtarget.hasStdExtZfh()) { 323 setOperationAction(FPLegalNodeTypes, MVT::f16, Legal); 324 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 325 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 326 setCondCodeAction(FPCCToExpand, MVT::f16, Expand); 327 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 328 setOperationAction(ISD::SELECT, MVT::f16, Custom); 329 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 330 331 setOperationAction({ISD::FREM, ISD::FCEIL, ISD::FFLOOR, ISD::FNEARBYINT, 332 ISD::FRINT, ISD::FROUND, ISD::FROUNDEVEN, ISD::FTRUNC, 333 ISD::FPOW, ISD::FPOWI, ISD::FCOS, ISD::FSIN, 334 ISD::FSINCOS, ISD::FEXP, ISD::FEXP2, ISD::FLOG, 335 ISD::FLOG2, ISD::FLOG10}, 336 MVT::f16, Promote); 337 338 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 339 // complete support for all operations in LegalizeDAG. 340 341 // We need to custom promote this. 342 if (Subtarget.is64Bit()) 343 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 344 } 345 346 if (Subtarget.hasStdExtF()) { 347 setOperationAction(FPLegalNodeTypes, MVT::f32, Legal); 348 setCondCodeAction(FPCCToExpand, MVT::f32, Expand); 349 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 350 setOperationAction(ISD::SELECT, MVT::f32, Custom); 351 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 352 setOperationAction(FPOpToExpand, MVT::f32, Expand); 353 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 354 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 355 } 356 357 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 358 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 359 360 if (Subtarget.hasStdExtD()) { 361 setOperationAction(FPLegalNodeTypes, MVT::f64, Legal); 362 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 363 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 364 setCondCodeAction(FPCCToExpand, MVT::f64, Expand); 365 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 366 setOperationAction(ISD::SELECT, MVT::f64, Custom); 367 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 368 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 369 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 370 setOperationAction(FPOpToExpand, 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 static const unsigned IntegerVecReduceOps[] = { 462 ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, 463 ISD::VECREDUCE_XOR, ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 464 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}; 465 466 static const unsigned FloatingPointVecReduceOps[] = { 467 ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, ISD::VECREDUCE_FMIN, 468 ISD::VECREDUCE_FMAX}; 469 470 if (!Subtarget.is64Bit()) { 471 // We must custom-lower certain vXi64 operations on RV32 due to the vector 472 // element type being illegal. 473 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 474 MVT::i64, Custom); 475 476 setOperationAction(IntegerVecReduceOps, MVT::i64, Custom); 477 478 setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 479 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, 480 ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN, 481 ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN}, 482 MVT::i64, Custom); 483 } 484 485 for (MVT VT : BoolVecVTs) { 486 if (!isTypeLegal(VT)) 487 continue; 488 489 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 490 491 // Mask VTs are custom-expanded into a series of standard nodes 492 setOperationAction({ISD::TRUNCATE, ISD::CONCAT_VECTORS, 493 ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 494 VT, Custom); 495 496 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 497 Custom); 498 499 setOperationAction(ISD::SELECT, VT, Custom); 500 setOperationAction( 501 {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT, 502 Expand); 503 504 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom); 505 506 setOperationAction( 507 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 508 Custom); 509 510 setOperationAction( 511 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 512 Custom); 513 514 // RVV has native int->float & float->int conversions where the 515 // element type sizes are within one power-of-two of each other. Any 516 // wider distances between type sizes have to be lowered as sequences 517 // which progressively narrow the gap in stages. 518 setOperationAction( 519 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 520 VT, Custom); 521 522 // Expand all extending loads to types larger than this, and truncating 523 // stores from types larger than this. 524 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 525 setTruncStoreAction(OtherVT, VT, Expand); 526 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 527 VT, Expand); 528 } 529 530 setOperationAction( 531 {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_TRUNCATE, ISD::VP_SETCC}, VT, 532 Custom); 533 setOperationAction(ISD::VECTOR_REVERSE, VT, Custom); 534 535 setOperationPromotedToType( 536 ISD::VECTOR_SPLICE, VT, 537 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount())); 538 } 539 540 for (MVT VT : IntVecVTs) { 541 if (!isTypeLegal(VT)) 542 continue; 543 544 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 545 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 546 547 // Vectors implement MULHS/MULHU. 548 setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand); 549 550 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 551 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) 552 setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand); 553 554 setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT, 555 Legal); 556 557 setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand); 558 559 setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP, ISD::BSWAP}, VT, 560 Expand); 561 562 setOperationAction(ISD::BSWAP, VT, Expand); 563 564 // Custom-lower extensions and truncations from/to mask types. 565 setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, 566 VT, Custom); 567 568 // RVV has native int->float & float->int conversions where the 569 // element type sizes are within one power-of-two of each other. Any 570 // wider distances between type sizes have to be lowered as sequences 571 // which progressively narrow the gap in stages. 572 setOperationAction( 573 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 574 VT, Custom); 575 576 setOperationAction( 577 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal); 578 579 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 580 // nodes which truncate by one power of two at a time. 581 setOperationAction(ISD::TRUNCATE, VT, Custom); 582 583 // Custom-lower insert/extract operations to simplify patterns. 584 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 585 Custom); 586 587 // Custom-lower reduction operations to set up the corresponding custom 588 // nodes' operands. 589 setOperationAction(IntegerVecReduceOps, VT, Custom); 590 591 setOperationAction(IntegerVPOps, VT, Custom); 592 593 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 594 595 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 596 VT, Custom); 597 598 setOperationAction( 599 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 600 Custom); 601 602 setOperationAction( 603 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 604 VT, Custom); 605 606 setOperationAction(ISD::SELECT, VT, Custom); 607 setOperationAction(ISD::SELECT_CC, VT, Expand); 608 609 setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom); 610 611 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 612 setTruncStoreAction(VT, OtherVT, Expand); 613 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 614 VT, Expand); 615 } 616 617 // Splice 618 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 619 620 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 621 // type that can represent the value exactly. 622 if (VT.getVectorElementType() != MVT::i64) { 623 MVT FloatEltVT = 624 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 625 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 626 if (isTypeLegal(FloatVT)) { 627 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 628 Custom); 629 } 630 } 631 } 632 633 // Expand various CCs to best match the RVV ISA, which natively supports UNE 634 // but no other unordered comparisons, and supports all ordered comparisons 635 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 636 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 637 // and we pattern-match those back to the "original", swapping operands once 638 // more. This way we catch both operations and both "vf" and "fv" forms with 639 // fewer patterns. 640 static const ISD::CondCode VFPCCToExpand[] = { 641 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 642 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 643 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 644 }; 645 646 // Sets common operation actions on RVV floating-point vector types. 647 const auto SetCommonVFPActions = [&](MVT VT) { 648 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 649 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 650 // sizes are within one power-of-two of each other. Therefore conversions 651 // between vXf16 and vXf64 must be lowered as sequences which convert via 652 // vXf32. 653 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 654 // Custom-lower insert/extract operations to simplify patterns. 655 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 656 Custom); 657 // Expand various condition codes (explained above). 658 setCondCodeAction(VFPCCToExpand, VT, Expand); 659 660 setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal); 661 662 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 663 VT, Custom); 664 665 setOperationAction(FloatingPointVecReduceOps, VT, Custom); 666 667 // Expand FP operations that need libcalls. 668 setOperationAction(ISD::FREM, VT, Expand); 669 setOperationAction(ISD::FPOW, VT, Expand); 670 setOperationAction(ISD::FCOS, VT, Expand); 671 setOperationAction(ISD::FSIN, VT, Expand); 672 setOperationAction(ISD::FSINCOS, VT, Expand); 673 setOperationAction(ISD::FEXP, VT, Expand); 674 setOperationAction(ISD::FEXP2, VT, Expand); 675 setOperationAction(ISD::FLOG, VT, Expand); 676 setOperationAction(ISD::FLOG2, VT, Expand); 677 setOperationAction(ISD::FLOG10, VT, Expand); 678 setOperationAction(ISD::FRINT, VT, Expand); 679 setOperationAction(ISD::FNEARBYINT, VT, Expand); 680 681 setOperationAction(ISD::VECREDUCE_FADD, VT, Custom); 682 setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom); 683 setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom); 684 setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom); 685 686 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 687 688 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 689 690 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 691 VT, Custom); 692 693 setOperationAction( 694 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 695 Custom); 696 697 setOperationAction(ISD::SELECT, VT, Custom); 698 setOperationAction(ISD::SELECT_CC, VT, Expand); 699 700 setOperationAction( 701 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 702 VT, Custom); 703 704 setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom); 705 706 setOperationAction(FloatingPointVPOps, VT, Custom); 707 }; 708 709 // Sets common extload/truncstore actions on RVV floating-point vector 710 // types. 711 const auto SetCommonVFPExtLoadTruncStoreActions = 712 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 713 for (auto SmallVT : SmallerVTs) { 714 setTruncStoreAction(VT, SmallVT, Expand); 715 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 716 } 717 }; 718 719 if (Subtarget.hasVInstructionsF16()) { 720 for (MVT VT : F16VecVTs) { 721 if (!isTypeLegal(VT)) 722 continue; 723 SetCommonVFPActions(VT); 724 } 725 } 726 727 if (Subtarget.hasVInstructionsF32()) { 728 for (MVT VT : F32VecVTs) { 729 if (!isTypeLegal(VT)) 730 continue; 731 SetCommonVFPActions(VT); 732 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 733 } 734 } 735 736 if (Subtarget.hasVInstructionsF64()) { 737 for (MVT VT : F64VecVTs) { 738 if (!isTypeLegal(VT)) 739 continue; 740 SetCommonVFPActions(VT); 741 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 742 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 743 } 744 } 745 746 if (Subtarget.useRVVForFixedLengthVectors()) { 747 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 748 if (!useRVVForFixedLengthVectorVT(VT)) 749 continue; 750 751 // By default everything must be expanded. 752 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 753 setOperationAction(Op, VT, Expand); 754 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 755 setTruncStoreAction(VT, OtherVT, Expand); 756 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, 757 OtherVT, VT, Expand); 758 } 759 760 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 761 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 762 Custom); 763 764 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT, 765 Custom); 766 767 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 768 VT, Custom); 769 770 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 771 772 setOperationAction(ISD::SETCC, VT, Custom); 773 774 setOperationAction(ISD::SELECT, VT, Custom); 775 776 setOperationAction(ISD::TRUNCATE, VT, Custom); 777 778 setOperationAction(ISD::BITCAST, VT, Custom); 779 780 setOperationAction( 781 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 782 Custom); 783 784 setOperationAction( 785 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 786 Custom); 787 788 setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, 789 ISD::FP_TO_UINT}, 790 VT, Custom); 791 792 // Operations below are different for between masks and other vectors. 793 if (VT.getVectorElementType() == MVT::i1) { 794 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND, 795 ISD::OR, ISD::XOR}, 796 VT, Custom); 797 798 setOperationAction( 799 {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_TRUNCATE}, 800 VT, Custom); 801 continue; 802 } 803 804 // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to 805 // it before type legalization for i64 vectors on RV32. It will then be 806 // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle. 807 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 808 // improvements first. 809 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 810 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 811 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 812 } 813 814 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 815 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 816 817 setOperationAction( 818 {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom); 819 820 setOperationAction( 821 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 822 Custom); 823 824 setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR, 825 ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV, 826 ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL}, 827 VT, Custom); 828 829 setOperationAction( 830 {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom); 831 832 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 833 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) 834 setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom); 835 836 setOperationAction( 837 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, 838 Custom); 839 840 setOperationAction(ISD::VSELECT, VT, Custom); 841 setOperationAction(ISD::SELECT_CC, VT, Expand); 842 843 setOperationAction( 844 {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom); 845 846 // Custom-lower reduction operations to set up the corresponding custom 847 // nodes' operands. 848 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX, 849 ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX, 850 ISD::VECREDUCE_UMIN}, 851 VT, Custom); 852 853 setOperationAction(IntegerVPOps, VT, Custom); 854 855 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 856 // type that can represent the value exactly. 857 if (VT.getVectorElementType() != MVT::i64) { 858 MVT FloatEltVT = 859 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 860 EVT FloatVT = 861 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 862 if (isTypeLegal(FloatVT)) 863 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 864 Custom); 865 } 866 } 867 868 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 869 if (!useRVVForFixedLengthVectorVT(VT)) 870 continue; 871 872 // By default everything must be expanded. 873 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 874 setOperationAction(Op, VT, Expand); 875 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 876 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 877 setTruncStoreAction(VT, OtherVT, Expand); 878 } 879 880 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 881 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 882 Custom); 883 884 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS, 885 ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT, 886 ISD::EXTRACT_VECTOR_ELT}, 887 VT, Custom); 888 889 setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE, 890 ISD::MGATHER, ISD::MSCATTER}, 891 VT, Custom); 892 893 setOperationAction( 894 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 895 Custom); 896 897 setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV, 898 ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT, 899 ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM}, 900 VT, Custom); 901 902 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 903 904 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 905 VT, Custom); 906 907 setCondCodeAction(VFPCCToExpand, VT, Expand); 908 909 setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom); 910 setOperationAction(ISD::SELECT_CC, VT, Expand); 911 912 setOperationAction(ISD::BITCAST, VT, Custom); 913 914 setOperationAction(FloatingPointVecReduceOps, VT, Custom); 915 916 setOperationAction(FloatingPointVPOps, VT, Custom); 917 } 918 919 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 920 setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64}, 921 Custom); 922 if (Subtarget.hasStdExtZfh()) 923 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 924 if (Subtarget.hasStdExtF()) 925 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 926 if (Subtarget.hasStdExtD()) 927 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 928 } 929 } 930 931 // Function alignments. 932 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 933 setMinFunctionAlignment(FunctionAlignment); 934 setPrefFunctionAlignment(FunctionAlignment); 935 936 setMinimumJumpTableEntries(5); 937 938 // Jumps are expensive, compared to logic 939 setJumpIsExpensive(); 940 941 setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND, 942 ISD::OR, ISD::XOR, ISD::SETCC}); 943 if (Subtarget.is64Bit()) 944 setTargetDAGCombine(ISD::SRA); 945 946 if (Subtarget.hasStdExtF()) 947 setTargetDAGCombine({ISD::FADD, ISD::FMAXNUM, ISD::FMINNUM}); 948 949 if (Subtarget.hasStdExtZbp()) 950 setTargetDAGCombine({ISD::ROTL, ISD::ROTR}); 951 952 if (Subtarget.hasStdExtZbb()) 953 setTargetDAGCombine({ISD::UMAX, ISD::UMIN, ISD::SMAX, ISD::SMIN}); 954 955 if (Subtarget.hasStdExtZbkb()) 956 setTargetDAGCombine(ISD::BITREVERSE); 957 if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb()) 958 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 959 if (Subtarget.hasStdExtF()) 960 setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT, 961 ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}); 962 if (Subtarget.hasVInstructions()) 963 setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER, 964 ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL, 965 ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR}); 966 if (Subtarget.useRVVForFixedLengthVectors()) 967 setTargetDAGCombine(ISD::BITCAST); 968 969 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 970 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 971 } 972 973 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 974 LLVMContext &Context, 975 EVT VT) const { 976 if (!VT.isVector()) 977 return getPointerTy(DL); 978 if (Subtarget.hasVInstructions() && 979 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 980 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 981 return VT.changeVectorElementTypeToInteger(); 982 } 983 984 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 985 return Subtarget.getXLenVT(); 986 } 987 988 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 989 const CallInst &I, 990 MachineFunction &MF, 991 unsigned Intrinsic) const { 992 auto &DL = I.getModule()->getDataLayout(); 993 switch (Intrinsic) { 994 default: 995 return false; 996 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 997 case Intrinsic::riscv_masked_atomicrmw_add_i32: 998 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 999 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 1000 case Intrinsic::riscv_masked_atomicrmw_max_i32: 1001 case Intrinsic::riscv_masked_atomicrmw_min_i32: 1002 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 1003 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 1004 case Intrinsic::riscv_masked_cmpxchg_i32: 1005 Info.opc = ISD::INTRINSIC_W_CHAIN; 1006 Info.memVT = MVT::i32; 1007 Info.ptrVal = I.getArgOperand(0); 1008 Info.offset = 0; 1009 Info.align = Align(4); 1010 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 1011 MachineMemOperand::MOVolatile; 1012 return true; 1013 case Intrinsic::riscv_masked_strided_load: 1014 Info.opc = ISD::INTRINSIC_W_CHAIN; 1015 Info.ptrVal = I.getArgOperand(1); 1016 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 1017 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 1018 Info.size = MemoryLocation::UnknownSize; 1019 Info.flags |= MachineMemOperand::MOLoad; 1020 return true; 1021 case Intrinsic::riscv_masked_strided_store: 1022 Info.opc = ISD::INTRINSIC_VOID; 1023 Info.ptrVal = I.getArgOperand(1); 1024 Info.memVT = 1025 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 1026 Info.align = Align( 1027 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 1028 8); 1029 Info.size = MemoryLocation::UnknownSize; 1030 Info.flags |= MachineMemOperand::MOStore; 1031 return true; 1032 case Intrinsic::riscv_seg2_load: 1033 case Intrinsic::riscv_seg3_load: 1034 case Intrinsic::riscv_seg4_load: 1035 case Intrinsic::riscv_seg5_load: 1036 case Intrinsic::riscv_seg6_load: 1037 case Intrinsic::riscv_seg7_load: 1038 case Intrinsic::riscv_seg8_load: 1039 Info.opc = ISD::INTRINSIC_W_CHAIN; 1040 Info.ptrVal = I.getArgOperand(0); 1041 Info.memVT = 1042 getValueType(DL, I.getType()->getStructElementType(0)->getScalarType()); 1043 Info.align = 1044 Align(DL.getTypeSizeInBits( 1045 I.getType()->getStructElementType(0)->getScalarType()) / 1046 8); 1047 Info.size = MemoryLocation::UnknownSize; 1048 Info.flags |= MachineMemOperand::MOLoad; 1049 return true; 1050 } 1051 } 1052 1053 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1054 const AddrMode &AM, Type *Ty, 1055 unsigned AS, 1056 Instruction *I) const { 1057 // No global is ever allowed as a base. 1058 if (AM.BaseGV) 1059 return false; 1060 1061 // RVV instructions only support register addressing. 1062 if (Subtarget.hasVInstructions() && isa<VectorType>(Ty)) 1063 return AM.HasBaseReg && AM.Scale == 0 && !AM.BaseOffs; 1064 1065 // Require a 12-bit signed offset. 1066 if (!isInt<12>(AM.BaseOffs)) 1067 return false; 1068 1069 switch (AM.Scale) { 1070 case 0: // "r+i" or just "i", depending on HasBaseReg. 1071 break; 1072 case 1: 1073 if (!AM.HasBaseReg) // allow "r+i". 1074 break; 1075 return false; // disallow "r+r" or "r+r+i". 1076 default: 1077 return false; 1078 } 1079 1080 return true; 1081 } 1082 1083 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1084 return isInt<12>(Imm); 1085 } 1086 1087 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1088 return isInt<12>(Imm); 1089 } 1090 1091 // On RV32, 64-bit integers are split into their high and low parts and held 1092 // in two different registers, so the trunc is free since the low register can 1093 // just be used. 1094 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1095 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1096 return false; 1097 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1098 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1099 return (SrcBits == 64 && DestBits == 32); 1100 } 1101 1102 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1103 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1104 !SrcVT.isInteger() || !DstVT.isInteger()) 1105 return false; 1106 unsigned SrcBits = SrcVT.getSizeInBits(); 1107 unsigned DestBits = DstVT.getSizeInBits(); 1108 return (SrcBits == 64 && DestBits == 32); 1109 } 1110 1111 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1112 // Zexts are free if they can be combined with a load. 1113 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1114 // poorly with type legalization of compares preferring sext. 1115 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1116 EVT MemVT = LD->getMemoryVT(); 1117 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1118 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1119 LD->getExtensionType() == ISD::ZEXTLOAD)) 1120 return true; 1121 } 1122 1123 return TargetLowering::isZExtFree(Val, VT2); 1124 } 1125 1126 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1127 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1128 } 1129 1130 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const { 1131 return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32); 1132 } 1133 1134 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1135 return Subtarget.hasStdExtZbb(); 1136 } 1137 1138 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1139 return Subtarget.hasStdExtZbb(); 1140 } 1141 1142 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1143 EVT VT = Y.getValueType(); 1144 1145 // FIXME: Support vectors once we have tests. 1146 if (VT.isVector()) 1147 return false; 1148 1149 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1150 Subtarget.hasStdExtZbkb()) && 1151 !isa<ConstantSDNode>(Y); 1152 } 1153 1154 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const { 1155 // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position. 1156 auto *C = dyn_cast<ConstantSDNode>(Y); 1157 return C && C->getAPIntValue().ule(10); 1158 } 1159 1160 bool RISCVTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm, 1161 Type *Ty) const { 1162 assert(Ty->isIntegerTy()); 1163 1164 unsigned BitSize = Ty->getIntegerBitWidth(); 1165 if (BitSize > Subtarget.getXLen()) 1166 return false; 1167 1168 // Fast path, assume 32-bit immediates are cheap. 1169 int64_t Val = Imm.getSExtValue(); 1170 if (isInt<32>(Val)) 1171 return true; 1172 1173 // A constant pool entry may be more aligned thant he load we're trying to 1174 // replace. If we don't support unaligned scalar mem, prefer the constant 1175 // pool. 1176 // TODO: Can the caller pass down the alignment? 1177 if (!Subtarget.enableUnalignedScalarMem()) 1178 return true; 1179 1180 // Prefer to keep the load if it would require many instructions. 1181 // This uses the same threshold we use for constant pools but doesn't 1182 // check useConstantPoolForLargeInts. 1183 // TODO: Should we keep the load only when we're definitely going to emit a 1184 // constant pool? 1185 1186 RISCVMatInt::InstSeq Seq = 1187 RISCVMatInt::generateInstSeq(Val, Subtarget.getFeatureBits()); 1188 return Seq.size() <= Subtarget.getMaxBuildIntsCost(); 1189 } 1190 1191 bool RISCVTargetLowering:: 1192 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 1193 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y, 1194 unsigned OldShiftOpcode, unsigned NewShiftOpcode, 1195 SelectionDAG &DAG) const { 1196 // One interesting pattern that we'd want to form is 'bit extract': 1197 // ((1 >> Y) & 1) ==/!= 0 1198 // But we also need to be careful not to try to reverse that fold. 1199 1200 // Is this '((1 >> Y) & 1)'? 1201 if (XC && OldShiftOpcode == ISD::SRL && XC->isOne()) 1202 return false; // Keep the 'bit extract' pattern. 1203 1204 // Will this be '((1 >> Y) & 1)' after the transform? 1205 if (NewShiftOpcode == ISD::SRL && CC->isOne()) 1206 return true; // Do form the 'bit extract' pattern. 1207 1208 // If 'X' is a constant, and we transform, then we will immediately 1209 // try to undo the fold, thus causing endless combine loop. 1210 // So only do the transform if X is not a constant. This matches the default 1211 // implementation of this function. 1212 return !XC; 1213 } 1214 1215 /// Check if sinking \p I's operands to I's basic block is profitable, because 1216 /// the operands can be folded into a target instruction, e.g. 1217 /// splats of scalars can fold into vector instructions. 1218 bool RISCVTargetLowering::shouldSinkOperands( 1219 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1220 using namespace llvm::PatternMatch; 1221 1222 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1223 return false; 1224 1225 auto IsSinker = [&](Instruction *I, int Operand) { 1226 switch (I->getOpcode()) { 1227 case Instruction::Add: 1228 case Instruction::Sub: 1229 case Instruction::Mul: 1230 case Instruction::And: 1231 case Instruction::Or: 1232 case Instruction::Xor: 1233 case Instruction::FAdd: 1234 case Instruction::FSub: 1235 case Instruction::FMul: 1236 case Instruction::FDiv: 1237 case Instruction::ICmp: 1238 case Instruction::FCmp: 1239 return true; 1240 case Instruction::Shl: 1241 case Instruction::LShr: 1242 case Instruction::AShr: 1243 case Instruction::UDiv: 1244 case Instruction::SDiv: 1245 case Instruction::URem: 1246 case Instruction::SRem: 1247 return Operand == 1; 1248 case Instruction::Call: 1249 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1250 switch (II->getIntrinsicID()) { 1251 case Intrinsic::fma: 1252 case Intrinsic::vp_fma: 1253 return Operand == 0 || Operand == 1; 1254 // FIXME: Our patterns can only match vx/vf instructions when the splat 1255 // it on the RHS, because TableGen doesn't recognize our VP operations 1256 // as commutative. 1257 case Intrinsic::vp_add: 1258 case Intrinsic::vp_mul: 1259 case Intrinsic::vp_and: 1260 case Intrinsic::vp_or: 1261 case Intrinsic::vp_xor: 1262 case Intrinsic::vp_fadd: 1263 case Intrinsic::vp_fmul: 1264 case Intrinsic::vp_shl: 1265 case Intrinsic::vp_lshr: 1266 case Intrinsic::vp_ashr: 1267 case Intrinsic::vp_udiv: 1268 case Intrinsic::vp_sdiv: 1269 case Intrinsic::vp_urem: 1270 case Intrinsic::vp_srem: 1271 return Operand == 1; 1272 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1273 // explicit patterns for both LHS and RHS (as 'vr' versions). 1274 case Intrinsic::vp_sub: 1275 case Intrinsic::vp_fsub: 1276 case Intrinsic::vp_fdiv: 1277 return Operand == 0 || Operand == 1; 1278 default: 1279 return false; 1280 } 1281 } 1282 return false; 1283 default: 1284 return false; 1285 } 1286 }; 1287 1288 for (auto OpIdx : enumerate(I->operands())) { 1289 if (!IsSinker(I, OpIdx.index())) 1290 continue; 1291 1292 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1293 // Make sure we are not already sinking this operand 1294 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1295 continue; 1296 1297 // We are looking for a splat that can be sunk. 1298 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1299 m_Undef(), m_ZeroMask()))) 1300 continue; 1301 1302 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1303 // and vector registers 1304 for (Use &U : Op->uses()) { 1305 Instruction *Insn = cast<Instruction>(U.getUser()); 1306 if (!IsSinker(Insn, U.getOperandNo())) 1307 return false; 1308 } 1309 1310 Ops.push_back(&Op->getOperandUse(0)); 1311 Ops.push_back(&OpIdx.value()); 1312 } 1313 return true; 1314 } 1315 1316 bool RISCVTargetLowering::shouldScalarizeBinop(SDValue VecOp) const { 1317 unsigned Opc = VecOp.getOpcode(); 1318 1319 // Assume target opcodes can't be scalarized. 1320 // TODO - do we have any exceptions? 1321 if (Opc >= ISD::BUILTIN_OP_END) 1322 return false; 1323 1324 // If the vector op is not supported, try to convert to scalar. 1325 EVT VecVT = VecOp.getValueType(); 1326 if (!isOperationLegalOrCustomOrPromote(Opc, VecVT)) 1327 return true; 1328 1329 // If the vector op is supported, but the scalar op is not, the transform may 1330 // not be worthwhile. 1331 EVT ScalarVT = VecVT.getScalarType(); 1332 return isOperationLegalOrCustomOrPromote(Opc, ScalarVT); 1333 } 1334 1335 bool RISCVTargetLowering::isOffsetFoldingLegal( 1336 const GlobalAddressSDNode *GA) const { 1337 // In order to maximise the opportunity for common subexpression elimination, 1338 // keep a separate ADD node for the global address offset instead of folding 1339 // it in the global address node. Later peephole optimisations may choose to 1340 // fold it back in when profitable. 1341 return false; 1342 } 1343 1344 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1345 bool ForCodeSize) const { 1346 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1347 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1348 return false; 1349 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1350 return false; 1351 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1352 return false; 1353 return Imm.isZero(); 1354 } 1355 1356 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1357 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1358 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1359 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1360 } 1361 1362 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1363 CallingConv::ID CC, 1364 EVT VT) const { 1365 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1366 // We might still end up using a GPR but that will be decided based on ABI. 1367 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1368 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1369 return MVT::f32; 1370 1371 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1372 } 1373 1374 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1375 CallingConv::ID CC, 1376 EVT VT) const { 1377 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1378 // We might still end up using a GPR but that will be decided based on ABI. 1379 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1380 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1381 return 1; 1382 1383 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1384 } 1385 1386 // Changes the condition code and swaps operands if necessary, so the SetCC 1387 // operation matches one of the comparisons supported directly by branches 1388 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1389 // with 1/-1. 1390 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1391 ISD::CondCode &CC, SelectionDAG &DAG) { 1392 // If this is a single bit test that can't be handled by ANDI, shift the 1393 // bit to be tested to the MSB and perform a signed compare with 0. 1394 if (isIntEqualitySetCC(CC) && isNullConstant(RHS) && 1395 LHS.getOpcode() == ISD::AND && LHS.hasOneUse() && 1396 isa<ConstantSDNode>(LHS.getOperand(1))) { 1397 uint64_t Mask = LHS.getConstantOperandVal(1); 1398 if (isPowerOf2_64(Mask) && !isInt<12>(Mask)) { 1399 CC = CC == ISD::SETEQ ? ISD::SETGE : ISD::SETLT; 1400 unsigned ShAmt = LHS.getValueSizeInBits() - 1 - Log2_64(Mask); 1401 LHS = LHS.getOperand(0); 1402 if (ShAmt != 0) 1403 LHS = DAG.getNode(ISD::SHL, DL, LHS.getValueType(), LHS, 1404 DAG.getConstant(ShAmt, DL, LHS.getValueType())); 1405 return; 1406 } 1407 } 1408 1409 // Convert X > -1 to X >= 0. 1410 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1411 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1412 CC = ISD::SETGE; 1413 return; 1414 } 1415 // Convert X < 1 to 0 >= X. 1416 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1417 RHS = LHS; 1418 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1419 CC = ISD::SETGE; 1420 return; 1421 } 1422 1423 switch (CC) { 1424 default: 1425 break; 1426 case ISD::SETGT: 1427 case ISD::SETLE: 1428 case ISD::SETUGT: 1429 case ISD::SETULE: 1430 CC = ISD::getSetCCSwappedOperands(CC); 1431 std::swap(LHS, RHS); 1432 break; 1433 } 1434 } 1435 1436 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1437 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1438 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1439 if (VT.getVectorElementType() == MVT::i1) 1440 KnownSize *= 8; 1441 1442 switch (KnownSize) { 1443 default: 1444 llvm_unreachable("Invalid LMUL."); 1445 case 8: 1446 return RISCVII::VLMUL::LMUL_F8; 1447 case 16: 1448 return RISCVII::VLMUL::LMUL_F4; 1449 case 32: 1450 return RISCVII::VLMUL::LMUL_F2; 1451 case 64: 1452 return RISCVII::VLMUL::LMUL_1; 1453 case 128: 1454 return RISCVII::VLMUL::LMUL_2; 1455 case 256: 1456 return RISCVII::VLMUL::LMUL_4; 1457 case 512: 1458 return RISCVII::VLMUL::LMUL_8; 1459 } 1460 } 1461 1462 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1463 switch (LMul) { 1464 default: 1465 llvm_unreachable("Invalid LMUL."); 1466 case RISCVII::VLMUL::LMUL_F8: 1467 case RISCVII::VLMUL::LMUL_F4: 1468 case RISCVII::VLMUL::LMUL_F2: 1469 case RISCVII::VLMUL::LMUL_1: 1470 return RISCV::VRRegClassID; 1471 case RISCVII::VLMUL::LMUL_2: 1472 return RISCV::VRM2RegClassID; 1473 case RISCVII::VLMUL::LMUL_4: 1474 return RISCV::VRM4RegClassID; 1475 case RISCVII::VLMUL::LMUL_8: 1476 return RISCV::VRM8RegClassID; 1477 } 1478 } 1479 1480 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1481 RISCVII::VLMUL LMUL = getLMUL(VT); 1482 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1483 LMUL == RISCVII::VLMUL::LMUL_F4 || 1484 LMUL == RISCVII::VLMUL::LMUL_F2 || 1485 LMUL == RISCVII::VLMUL::LMUL_1) { 1486 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1487 "Unexpected subreg numbering"); 1488 return RISCV::sub_vrm1_0 + Index; 1489 } 1490 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1491 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1492 "Unexpected subreg numbering"); 1493 return RISCV::sub_vrm2_0 + Index; 1494 } 1495 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1496 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1497 "Unexpected subreg numbering"); 1498 return RISCV::sub_vrm4_0 + Index; 1499 } 1500 llvm_unreachable("Invalid vector type."); 1501 } 1502 1503 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1504 if (VT.getVectorElementType() == MVT::i1) 1505 return RISCV::VRRegClassID; 1506 return getRegClassIDForLMUL(getLMUL(VT)); 1507 } 1508 1509 // Attempt to decompose a subvector insert/extract between VecVT and 1510 // SubVecVT via subregister indices. Returns the subregister index that 1511 // can perform the subvector insert/extract with the given element index, as 1512 // well as the index corresponding to any leftover subvectors that must be 1513 // further inserted/extracted within the register class for SubVecVT. 1514 std::pair<unsigned, unsigned> 1515 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1516 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1517 const RISCVRegisterInfo *TRI) { 1518 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1519 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1520 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1521 "Register classes not ordered"); 1522 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1523 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1524 // Try to compose a subregister index that takes us from the incoming 1525 // LMUL>1 register class down to the outgoing one. At each step we half 1526 // the LMUL: 1527 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1528 // Note that this is not guaranteed to find a subregister index, such as 1529 // when we are extracting from one VR type to another. 1530 unsigned SubRegIdx = RISCV::NoSubRegister; 1531 for (const unsigned RCID : 1532 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1533 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1534 VecVT = VecVT.getHalfNumVectorElementsVT(); 1535 bool IsHi = 1536 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1537 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1538 getSubregIndexByMVT(VecVT, IsHi)); 1539 if (IsHi) 1540 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1541 } 1542 return {SubRegIdx, InsertExtractIdx}; 1543 } 1544 1545 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1546 // stores for those types. 1547 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1548 return !Subtarget.useRVVForFixedLengthVectors() || 1549 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1550 } 1551 1552 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1553 if (ScalarTy->isPointerTy()) 1554 return true; 1555 1556 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1557 ScalarTy->isIntegerTy(32)) 1558 return true; 1559 1560 if (ScalarTy->isIntegerTy(64)) 1561 return Subtarget.hasVInstructionsI64(); 1562 1563 if (ScalarTy->isHalfTy()) 1564 return Subtarget.hasVInstructionsF16(); 1565 if (ScalarTy->isFloatTy()) 1566 return Subtarget.hasVInstructionsF32(); 1567 if (ScalarTy->isDoubleTy()) 1568 return Subtarget.hasVInstructionsF64(); 1569 1570 return false; 1571 } 1572 1573 static SDValue getVLOperand(SDValue Op) { 1574 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1575 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1576 "Unexpected opcode"); 1577 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1578 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1579 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1580 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1581 if (!II) 1582 return SDValue(); 1583 return Op.getOperand(II->VLOperand + 1 + HasChain); 1584 } 1585 1586 static bool useRVVForFixedLengthVectorVT(MVT VT, 1587 const RISCVSubtarget &Subtarget) { 1588 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1589 if (!Subtarget.useRVVForFixedLengthVectors()) 1590 return false; 1591 1592 // We only support a set of vector types with a consistent maximum fixed size 1593 // across all supported vector element types to avoid legalization issues. 1594 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1595 // fixed-length vector type we support is 1024 bytes. 1596 if (VT.getFixedSizeInBits() > 1024 * 8) 1597 return false; 1598 1599 unsigned MinVLen = Subtarget.getRealMinVLen(); 1600 1601 MVT EltVT = VT.getVectorElementType(); 1602 1603 // Don't use RVV for vectors we cannot scalarize if required. 1604 switch (EltVT.SimpleTy) { 1605 // i1 is supported but has different rules. 1606 default: 1607 return false; 1608 case MVT::i1: 1609 // Masks can only use a single register. 1610 if (VT.getVectorNumElements() > MinVLen) 1611 return false; 1612 MinVLen /= 8; 1613 break; 1614 case MVT::i8: 1615 case MVT::i16: 1616 case MVT::i32: 1617 break; 1618 case MVT::i64: 1619 if (!Subtarget.hasVInstructionsI64()) 1620 return false; 1621 break; 1622 case MVT::f16: 1623 if (!Subtarget.hasVInstructionsF16()) 1624 return false; 1625 break; 1626 case MVT::f32: 1627 if (!Subtarget.hasVInstructionsF32()) 1628 return false; 1629 break; 1630 case MVT::f64: 1631 if (!Subtarget.hasVInstructionsF64()) 1632 return false; 1633 break; 1634 } 1635 1636 // Reject elements larger than ELEN. 1637 if (EltVT.getSizeInBits() > Subtarget.getELEN()) 1638 return false; 1639 1640 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1641 // Don't use RVV for types that don't fit. 1642 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1643 return false; 1644 1645 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1646 // the base fixed length RVV support in place. 1647 if (!VT.isPow2VectorType()) 1648 return false; 1649 1650 return true; 1651 } 1652 1653 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1654 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1655 } 1656 1657 // Return the largest legal scalable vector type that matches VT's element type. 1658 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1659 const RISCVSubtarget &Subtarget) { 1660 // This may be called before legal types are setup. 1661 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1662 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1663 "Expected legal fixed length vector!"); 1664 1665 unsigned MinVLen = Subtarget.getRealMinVLen(); 1666 unsigned MaxELen = Subtarget.getELEN(); 1667 1668 MVT EltVT = VT.getVectorElementType(); 1669 switch (EltVT.SimpleTy) { 1670 default: 1671 llvm_unreachable("unexpected element type for RVV container"); 1672 case MVT::i1: 1673 case MVT::i8: 1674 case MVT::i16: 1675 case MVT::i32: 1676 case MVT::i64: 1677 case MVT::f16: 1678 case MVT::f32: 1679 case MVT::f64: { 1680 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1681 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1682 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1683 unsigned NumElts = 1684 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1685 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1686 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1687 return MVT::getScalableVectorVT(EltVT, NumElts); 1688 } 1689 } 1690 } 1691 1692 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1693 const RISCVSubtarget &Subtarget) { 1694 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1695 Subtarget); 1696 } 1697 1698 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1699 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1700 } 1701 1702 // Grow V to consume an entire RVV register. 1703 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1704 const RISCVSubtarget &Subtarget) { 1705 assert(VT.isScalableVector() && 1706 "Expected to convert into a scalable vector!"); 1707 assert(V.getValueType().isFixedLengthVector() && 1708 "Expected a fixed length vector operand!"); 1709 SDLoc DL(V); 1710 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1711 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1712 } 1713 1714 // Shrink V so it's just big enough to maintain a VT's worth of data. 1715 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1716 const RISCVSubtarget &Subtarget) { 1717 assert(VT.isFixedLengthVector() && 1718 "Expected to convert into a fixed length vector!"); 1719 assert(V.getValueType().isScalableVector() && 1720 "Expected a scalable vector operand!"); 1721 SDLoc DL(V); 1722 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1723 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1724 } 1725 1726 /// Return the type of the mask type suitable for masking the provided 1727 /// vector type. This is simply an i1 element type vector of the same 1728 /// (possibly scalable) length. 1729 static MVT getMaskTypeFor(MVT VecVT) { 1730 assert(VecVT.isVector()); 1731 ElementCount EC = VecVT.getVectorElementCount(); 1732 return MVT::getVectorVT(MVT::i1, EC); 1733 } 1734 1735 /// Creates an all ones mask suitable for masking a vector of type VecTy with 1736 /// vector length VL. . 1737 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL, 1738 SelectionDAG &DAG) { 1739 MVT MaskVT = getMaskTypeFor(VecVT); 1740 return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1741 } 1742 1743 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1744 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1745 // the vector type that it is contained in. 1746 static std::pair<SDValue, SDValue> 1747 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1748 const RISCVSubtarget &Subtarget) { 1749 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1750 MVT XLenVT = Subtarget.getXLenVT(); 1751 SDValue VL = VecVT.isFixedLengthVector() 1752 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1753 : DAG.getRegister(RISCV::X0, XLenVT); 1754 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 1755 return {Mask, VL}; 1756 } 1757 1758 // As above but assuming the given type is a scalable vector type. 1759 static std::pair<SDValue, SDValue> 1760 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1761 const RISCVSubtarget &Subtarget) { 1762 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1763 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1764 } 1765 1766 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1767 // of either is (currently) supported. This can get us into an infinite loop 1768 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1769 // as a ..., etc. 1770 // Until either (or both) of these can reliably lower any node, reporting that 1771 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1772 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1773 // which is not desirable. 1774 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1775 EVT VT, unsigned DefinedValues) const { 1776 return false; 1777 } 1778 1779 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1780 const RISCVSubtarget &Subtarget) { 1781 // RISCV FP-to-int conversions saturate to the destination register size, but 1782 // don't produce 0 for nan. We can use a conversion instruction and fix the 1783 // nan case with a compare and a select. 1784 SDValue Src = Op.getOperand(0); 1785 1786 EVT DstVT = Op.getValueType(); 1787 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1788 1789 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1790 unsigned Opc; 1791 if (SatVT == DstVT) 1792 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1793 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1794 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1795 else 1796 return SDValue(); 1797 // FIXME: Support other SatVTs by clamping before or after the conversion. 1798 1799 SDLoc DL(Op); 1800 SDValue FpToInt = DAG.getNode( 1801 Opc, DL, DstVT, Src, 1802 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1803 1804 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1805 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1806 } 1807 1808 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1809 // and back. Taking care to avoid converting values that are nan or already 1810 // correct. 1811 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1812 // have FRM dependencies modeled yet. 1813 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1814 MVT VT = Op.getSimpleValueType(); 1815 assert(VT.isVector() && "Unexpected type"); 1816 1817 SDLoc DL(Op); 1818 1819 // Freeze the source since we are increasing the number of uses. 1820 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1821 1822 // Truncate to integer and convert back to FP. 1823 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1824 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1825 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1826 1827 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1828 1829 if (Op.getOpcode() == ISD::FCEIL) { 1830 // If the truncated value is the greater than or equal to the original 1831 // value, we've computed the ceil. Otherwise, we went the wrong way and 1832 // need to increase by 1. 1833 // FIXME: This should use a masked operation. Handle here or in isel? 1834 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1835 DAG.getConstantFP(1.0, DL, VT)); 1836 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1837 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1838 } else if (Op.getOpcode() == ISD::FFLOOR) { 1839 // If the truncated value is the less than or equal to the original value, 1840 // we've computed the floor. Otherwise, we went the wrong way and need to 1841 // decrease by 1. 1842 // FIXME: This should use a masked operation. Handle here or in isel? 1843 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1844 DAG.getConstantFP(1.0, DL, VT)); 1845 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1846 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1847 } 1848 1849 // Restore the original sign so that -0.0 is preserved. 1850 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1851 1852 // Determine the largest integer that can be represented exactly. This and 1853 // values larger than it don't have any fractional bits so don't need to 1854 // be converted. 1855 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1856 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1857 APFloat MaxVal = APFloat(FltSem); 1858 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1859 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1860 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1861 1862 // If abs(Src) was larger than MaxVal or nan, keep it. 1863 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1864 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1865 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1866 } 1867 1868 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1869 // This mode isn't supported in vector hardware on RISCV. But as long as we 1870 // aren't compiling with trapping math, we can emulate this with 1871 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1872 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1873 // dependencies modeled yet. 1874 // FIXME: Use masked operations to avoid final merge. 1875 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1876 MVT VT = Op.getSimpleValueType(); 1877 assert(VT.isVector() && "Unexpected type"); 1878 1879 SDLoc DL(Op); 1880 1881 // Freeze the source since we are increasing the number of uses. 1882 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1883 1884 // We do the conversion on the absolute value and fix the sign at the end. 1885 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1886 1887 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1888 bool Ignored; 1889 APFloat Point5Pred = APFloat(0.5f); 1890 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1891 Point5Pred.next(/*nextDown*/ true); 1892 1893 // Add the adjustment. 1894 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1895 DAG.getConstantFP(Point5Pred, DL, VT)); 1896 1897 // Truncate to integer and convert back to fp. 1898 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1899 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1900 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1901 1902 // Restore the original sign. 1903 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1904 1905 // Determine the largest integer that can be represented exactly. This and 1906 // values larger than it don't have any fractional bits so don't need to 1907 // be converted. 1908 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1909 APFloat MaxVal = APFloat(FltSem); 1910 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1911 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1912 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1913 1914 // If abs(Src) was larger than MaxVal or nan, keep it. 1915 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1916 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1917 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1918 } 1919 1920 struct VIDSequence { 1921 int64_t StepNumerator; 1922 unsigned StepDenominator; 1923 int64_t Addend; 1924 }; 1925 1926 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1927 // to the (non-zero) step S and start value X. This can be then lowered as the 1928 // RVV sequence (VID * S) + X, for example. 1929 // The step S is represented as an integer numerator divided by a positive 1930 // denominator. Note that the implementation currently only identifies 1931 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1932 // cannot detect 2/3, for example. 1933 // Note that this method will also match potentially unappealing index 1934 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1935 // determine whether this is worth generating code for. 1936 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1937 unsigned NumElts = Op.getNumOperands(); 1938 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1939 if (!Op.getValueType().isInteger()) 1940 return None; 1941 1942 Optional<unsigned> SeqStepDenom; 1943 Optional<int64_t> SeqStepNum, SeqAddend; 1944 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1945 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1946 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1947 // Assume undef elements match the sequence; we just have to be careful 1948 // when interpolating across them. 1949 if (Op.getOperand(Idx).isUndef()) 1950 continue; 1951 // The BUILD_VECTOR must be all constants. 1952 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1953 return None; 1954 1955 uint64_t Val = Op.getConstantOperandVal(Idx) & 1956 maskTrailingOnes<uint64_t>(EltSizeInBits); 1957 1958 if (PrevElt) { 1959 // Calculate the step since the last non-undef element, and ensure 1960 // it's consistent across the entire sequence. 1961 unsigned IdxDiff = Idx - PrevElt->second; 1962 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1963 1964 // A zero-value value difference means that we're somewhere in the middle 1965 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1966 // step change before evaluating the sequence. 1967 if (ValDiff == 0) 1968 continue; 1969 1970 int64_t Remainder = ValDiff % IdxDiff; 1971 // Normalize the step if it's greater than 1. 1972 if (Remainder != ValDiff) { 1973 // The difference must cleanly divide the element span. 1974 if (Remainder != 0) 1975 return None; 1976 ValDiff /= IdxDiff; 1977 IdxDiff = 1; 1978 } 1979 1980 if (!SeqStepNum) 1981 SeqStepNum = ValDiff; 1982 else if (ValDiff != SeqStepNum) 1983 return None; 1984 1985 if (!SeqStepDenom) 1986 SeqStepDenom = IdxDiff; 1987 else if (IdxDiff != *SeqStepDenom) 1988 return None; 1989 } 1990 1991 // Record this non-undef element for later. 1992 if (!PrevElt || PrevElt->first != Val) 1993 PrevElt = std::make_pair(Val, Idx); 1994 } 1995 1996 // We need to have logged a step for this to count as a legal index sequence. 1997 if (!SeqStepNum || !SeqStepDenom) 1998 return None; 1999 2000 // Loop back through the sequence and validate elements we might have skipped 2001 // while waiting for a valid step. While doing this, log any sequence addend. 2002 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 2003 if (Op.getOperand(Idx).isUndef()) 2004 continue; 2005 uint64_t Val = Op.getConstantOperandVal(Idx) & 2006 maskTrailingOnes<uint64_t>(EltSizeInBits); 2007 uint64_t ExpectedVal = 2008 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 2009 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 2010 if (!SeqAddend) 2011 SeqAddend = Addend; 2012 else if (Addend != SeqAddend) 2013 return None; 2014 } 2015 2016 assert(SeqAddend && "Must have an addend if we have a step"); 2017 2018 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 2019 } 2020 2021 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 2022 // and lower it as a VRGATHER_VX_VL from the source vector. 2023 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 2024 SelectionDAG &DAG, 2025 const RISCVSubtarget &Subtarget) { 2026 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 2027 return SDValue(); 2028 SDValue Vec = SplatVal.getOperand(0); 2029 // Only perform this optimization on vectors of the same size for simplicity. 2030 // Don't perform this optimization for i1 vectors. 2031 // FIXME: Support i1 vectors, maybe by promoting to i8? 2032 if (Vec.getValueType() != VT || VT.getVectorElementType() == MVT::i1) 2033 return SDValue(); 2034 SDValue Idx = SplatVal.getOperand(1); 2035 // The index must be a legal type. 2036 if (Idx.getValueType() != Subtarget.getXLenVT()) 2037 return SDValue(); 2038 2039 MVT ContainerVT = VT; 2040 if (VT.isFixedLengthVector()) { 2041 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2042 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 2043 } 2044 2045 SDValue Mask, VL; 2046 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2047 2048 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 2049 Idx, Mask, DAG.getUNDEF(ContainerVT), VL); 2050 2051 if (!VT.isFixedLengthVector()) 2052 return Gather; 2053 2054 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2055 } 2056 2057 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 2058 const RISCVSubtarget &Subtarget) { 2059 MVT VT = Op.getSimpleValueType(); 2060 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 2061 2062 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2063 2064 SDLoc DL(Op); 2065 SDValue Mask, VL; 2066 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2067 2068 MVT XLenVT = Subtarget.getXLenVT(); 2069 unsigned NumElts = Op.getNumOperands(); 2070 2071 if (VT.getVectorElementType() == MVT::i1) { 2072 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 2073 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 2074 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 2075 } 2076 2077 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 2078 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 2079 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 2080 } 2081 2082 // Lower constant mask BUILD_VECTORs via an integer vector type, in 2083 // scalar integer chunks whose bit-width depends on the number of mask 2084 // bits and XLEN. 2085 // First, determine the most appropriate scalar integer type to use. This 2086 // is at most XLenVT, but may be shrunk to a smaller vector element type 2087 // according to the size of the final vector - use i8 chunks rather than 2088 // XLenVT if we're producing a v8i1. This results in more consistent 2089 // codegen across RV32 and RV64. 2090 unsigned NumViaIntegerBits = 2091 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 2092 NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN()); 2093 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 2094 // If we have to use more than one INSERT_VECTOR_ELT then this 2095 // optimization is likely to increase code size; avoid peforming it in 2096 // such a case. We can use a load from a constant pool in this case. 2097 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 2098 return SDValue(); 2099 // Now we can create our integer vector type. Note that it may be larger 2100 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2101 MVT IntegerViaVecVT = 2102 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2103 divideCeil(NumElts, NumViaIntegerBits)); 2104 2105 uint64_t Bits = 0; 2106 unsigned BitPos = 0, IntegerEltIdx = 0; 2107 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2108 2109 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2110 // Once we accumulate enough bits to fill our scalar type, insert into 2111 // our vector and clear our accumulated data. 2112 if (I != 0 && I % NumViaIntegerBits == 0) { 2113 if (NumViaIntegerBits <= 32) 2114 Bits = SignExtend64<32>(Bits); 2115 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2116 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2117 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2118 Bits = 0; 2119 BitPos = 0; 2120 IntegerEltIdx++; 2121 } 2122 SDValue V = Op.getOperand(I); 2123 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2124 Bits |= ((uint64_t)BitValue << BitPos); 2125 } 2126 2127 // Insert the (remaining) scalar value into position in our integer 2128 // vector type. 2129 if (NumViaIntegerBits <= 32) 2130 Bits = SignExtend64<32>(Bits); 2131 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2132 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2133 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2134 2135 if (NumElts < NumViaIntegerBits) { 2136 // If we're producing a smaller vector than our minimum legal integer 2137 // type, bitcast to the equivalent (known-legal) mask type, and extract 2138 // our final mask. 2139 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2140 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2141 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2142 DAG.getConstant(0, DL, XLenVT)); 2143 } else { 2144 // Else we must have produced an integer type with the same size as the 2145 // mask type; bitcast for the final result. 2146 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2147 Vec = DAG.getBitcast(VT, Vec); 2148 } 2149 2150 return Vec; 2151 } 2152 2153 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2154 // vector type, we have a legal equivalently-sized i8 type, so we can use 2155 // that. 2156 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2157 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2158 2159 SDValue WideVec; 2160 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2161 // For a splat, perform a scalar truncate before creating the wider 2162 // vector. 2163 assert(Splat.getValueType() == XLenVT && 2164 "Unexpected type for i1 splat value"); 2165 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2166 DAG.getConstant(1, DL, XLenVT)); 2167 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2168 } else { 2169 SmallVector<SDValue, 8> Ops(Op->op_values()); 2170 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2171 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2172 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2173 } 2174 2175 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2176 } 2177 2178 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2179 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2180 return Gather; 2181 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2182 : RISCVISD::VMV_V_X_VL; 2183 Splat = 2184 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2185 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2186 } 2187 2188 // Try and match index sequences, which we can lower to the vid instruction 2189 // with optional modifications. An all-undef vector is matched by 2190 // getSplatValue, above. 2191 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2192 int64_t StepNumerator = SimpleVID->StepNumerator; 2193 unsigned StepDenominator = SimpleVID->StepDenominator; 2194 int64_t Addend = SimpleVID->Addend; 2195 2196 assert(StepNumerator != 0 && "Invalid step"); 2197 bool Negate = false; 2198 int64_t SplatStepVal = StepNumerator; 2199 unsigned StepOpcode = ISD::MUL; 2200 if (StepNumerator != 1) { 2201 if (isPowerOf2_64(std::abs(StepNumerator))) { 2202 Negate = StepNumerator < 0; 2203 StepOpcode = ISD::SHL; 2204 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2205 } 2206 } 2207 2208 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2209 // threshold since it's the immediate value many RVV instructions accept. 2210 // There is no vmul.vi instruction so ensure multiply constant can fit in 2211 // a single addi instruction. 2212 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2213 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2214 isPowerOf2_32(StepDenominator) && 2215 (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) { 2216 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2217 // Convert right out of the scalable type so we can use standard ISD 2218 // nodes for the rest of the computation. If we used scalable types with 2219 // these, we'd lose the fixed-length vector info and generate worse 2220 // vsetvli code. 2221 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2222 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2223 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2224 SDValue SplatStep = DAG.getSplatBuildVector( 2225 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2226 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2227 } 2228 if (StepDenominator != 1) { 2229 SDValue SplatStep = DAG.getSplatBuildVector( 2230 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2231 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2232 } 2233 if (Addend != 0 || Negate) { 2234 SDValue SplatAddend = DAG.getSplatBuildVector( 2235 VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2236 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2237 } 2238 return VID; 2239 } 2240 } 2241 2242 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2243 // when re-interpreted as a vector with a larger element type. For example, 2244 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2245 // could be instead splat as 2246 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2247 // TODO: This optimization could also work on non-constant splats, but it 2248 // would require bit-manipulation instructions to construct the splat value. 2249 SmallVector<SDValue> Sequence; 2250 unsigned EltBitSize = VT.getScalarSizeInBits(); 2251 const auto *BV = cast<BuildVectorSDNode>(Op); 2252 if (VT.isInteger() && EltBitSize < 64 && 2253 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2254 BV->getRepeatedSequence(Sequence) && 2255 (Sequence.size() * EltBitSize) <= 64) { 2256 unsigned SeqLen = Sequence.size(); 2257 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2258 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2259 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2260 ViaIntVT == MVT::i64) && 2261 "Unexpected sequence type"); 2262 2263 unsigned EltIdx = 0; 2264 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2265 uint64_t SplatValue = 0; 2266 // Construct the amalgamated value which can be splatted as this larger 2267 // vector type. 2268 for (const auto &SeqV : Sequence) { 2269 if (!SeqV.isUndef()) 2270 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2271 << (EltIdx * EltBitSize)); 2272 EltIdx++; 2273 } 2274 2275 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2276 // achieve better constant materializion. 2277 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2278 SplatValue = SignExtend64<32>(SplatValue); 2279 2280 // Since we can't introduce illegal i64 types at this stage, we can only 2281 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2282 // way we can use RVV instructions to splat. 2283 assert((ViaIntVT.bitsLE(XLenVT) || 2284 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2285 "Unexpected bitcast sequence"); 2286 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2287 SDValue ViaVL = 2288 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2289 MVT ViaContainerVT = 2290 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2291 SDValue Splat = 2292 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2293 DAG.getUNDEF(ViaContainerVT), 2294 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2295 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2296 return DAG.getBitcast(VT, Splat); 2297 } 2298 } 2299 2300 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2301 // which constitute a large proportion of the elements. In such cases we can 2302 // splat a vector with the dominant element and make up the shortfall with 2303 // INSERT_VECTOR_ELTs. 2304 // Note that this includes vectors of 2 elements by association. The 2305 // upper-most element is the "dominant" one, allowing us to use a splat to 2306 // "insert" the upper element, and an insert of the lower element at position 2307 // 0, which improves codegen. 2308 SDValue DominantValue; 2309 unsigned MostCommonCount = 0; 2310 DenseMap<SDValue, unsigned> ValueCounts; 2311 unsigned NumUndefElts = 2312 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2313 2314 // Track the number of scalar loads we know we'd be inserting, estimated as 2315 // any non-zero floating-point constant. Other kinds of element are either 2316 // already in registers or are materialized on demand. The threshold at which 2317 // a vector load is more desirable than several scalar materializion and 2318 // vector-insertion instructions is not known. 2319 unsigned NumScalarLoads = 0; 2320 2321 for (SDValue V : Op->op_values()) { 2322 if (V.isUndef()) 2323 continue; 2324 2325 ValueCounts.insert(std::make_pair(V, 0)); 2326 unsigned &Count = ValueCounts[V]; 2327 2328 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2329 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2330 2331 // Is this value dominant? In case of a tie, prefer the highest element as 2332 // it's cheaper to insert near the beginning of a vector than it is at the 2333 // end. 2334 if (++Count >= MostCommonCount) { 2335 DominantValue = V; 2336 MostCommonCount = Count; 2337 } 2338 } 2339 2340 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2341 unsigned NumDefElts = NumElts - NumUndefElts; 2342 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2343 2344 // Don't perform this optimization when optimizing for size, since 2345 // materializing elements and inserting them tends to cause code bloat. 2346 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2347 ((MostCommonCount > DominantValueCountThreshold) || 2348 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2349 // Start by splatting the most common element. 2350 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2351 2352 DenseSet<SDValue> Processed{DominantValue}; 2353 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2354 for (const auto &OpIdx : enumerate(Op->ops())) { 2355 const SDValue &V = OpIdx.value(); 2356 if (V.isUndef() || !Processed.insert(V).second) 2357 continue; 2358 if (ValueCounts[V] == 1) { 2359 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2360 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2361 } else { 2362 // Blend in all instances of this value using a VSELECT, using a 2363 // mask where each bit signals whether that element is the one 2364 // we're after. 2365 SmallVector<SDValue> Ops; 2366 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2367 return DAG.getConstant(V == V1, DL, XLenVT); 2368 }); 2369 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2370 DAG.getBuildVector(SelMaskTy, DL, Ops), 2371 DAG.getSplatBuildVector(VT, DL, V), Vec); 2372 } 2373 } 2374 2375 return Vec; 2376 } 2377 2378 return SDValue(); 2379 } 2380 2381 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2382 SDValue Lo, SDValue Hi, SDValue VL, 2383 SelectionDAG &DAG) { 2384 if (!Passthru) 2385 Passthru = DAG.getUNDEF(VT); 2386 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2387 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2388 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2389 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2390 // node in order to try and match RVV vector/scalar instructions. 2391 if ((LoC >> 31) == HiC) 2392 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2393 2394 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2395 // vmv.v.x whose EEW = 32 to lower it. 2396 auto *Const = dyn_cast<ConstantSDNode>(VL); 2397 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2398 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2399 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2400 // access the subtarget here now. 2401 auto InterVec = DAG.getNode( 2402 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2403 DAG.getRegister(RISCV::X0, MVT::i32)); 2404 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2405 } 2406 } 2407 2408 // Fall back to a stack store and stride x0 vector load. 2409 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2410 Hi, VL); 2411 } 2412 2413 // Called by type legalization to handle splat of i64 on RV32. 2414 // FIXME: We can optimize this when the type has sign or zero bits in one 2415 // of the halves. 2416 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2417 SDValue Scalar, SDValue VL, 2418 SelectionDAG &DAG) { 2419 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2420 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2421 DAG.getConstant(0, DL, MVT::i32)); 2422 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2423 DAG.getConstant(1, DL, MVT::i32)); 2424 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2425 } 2426 2427 // This function lowers a splat of a scalar operand Splat with the vector 2428 // length VL. It ensures the final sequence is type legal, which is useful when 2429 // lowering a splat after type legalization. 2430 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2431 MVT VT, SDLoc DL, SelectionDAG &DAG, 2432 const RISCVSubtarget &Subtarget) { 2433 bool HasPassthru = Passthru && !Passthru.isUndef(); 2434 if (!HasPassthru && !Passthru) 2435 Passthru = DAG.getUNDEF(VT); 2436 if (VT.isFloatingPoint()) { 2437 // If VL is 1, we could use vfmv.s.f. 2438 if (isOneConstant(VL)) 2439 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2440 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2441 } 2442 2443 MVT XLenVT = Subtarget.getXLenVT(); 2444 2445 // Simplest case is that the operand needs to be promoted to XLenVT. 2446 if (Scalar.getValueType().bitsLE(XLenVT)) { 2447 // If the operand is a constant, sign extend to increase our chances 2448 // of being able to use a .vi instruction. ANY_EXTEND would become a 2449 // a zero extend and the simm5 check in isel would fail. 2450 // FIXME: Should we ignore the upper bits in isel instead? 2451 unsigned ExtOpc = 2452 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2453 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2454 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2455 // If VL is 1 and the scalar value won't benefit from immediate, we could 2456 // use vmv.s.x. 2457 if (isOneConstant(VL) && 2458 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2459 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2460 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2461 } 2462 2463 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2464 "Unexpected scalar for splat lowering!"); 2465 2466 if (isOneConstant(VL) && isNullConstant(Scalar)) 2467 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2468 DAG.getConstant(0, DL, XLenVT), VL); 2469 2470 // Otherwise use the more complicated splatting algorithm. 2471 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2472 } 2473 2474 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2475 const RISCVSubtarget &Subtarget) { 2476 // We need to be able to widen elements to the next larger integer type. 2477 if (VT.getScalarSizeInBits() >= Subtarget.getELEN()) 2478 return false; 2479 2480 int Size = Mask.size(); 2481 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2482 2483 int Srcs[] = {-1, -1}; 2484 for (int i = 0; i != Size; ++i) { 2485 // Ignore undef elements. 2486 if (Mask[i] < 0) 2487 continue; 2488 2489 // Is this an even or odd element. 2490 int Pol = i % 2; 2491 2492 // Ensure we consistently use the same source for this element polarity. 2493 int Src = Mask[i] / Size; 2494 if (Srcs[Pol] < 0) 2495 Srcs[Pol] = Src; 2496 if (Srcs[Pol] != Src) 2497 return false; 2498 2499 // Make sure the element within the source is appropriate for this element 2500 // in the destination. 2501 int Elt = Mask[i] % Size; 2502 if (Elt != i / 2) 2503 return false; 2504 } 2505 2506 // We need to find a source for each polarity and they can't be the same. 2507 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2508 return false; 2509 2510 // Swap the sources if the second source was in the even polarity. 2511 SwapSources = Srcs[0] > Srcs[1]; 2512 2513 return true; 2514 } 2515 2516 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2517 /// and then extract the original number of elements from the rotated result. 2518 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2519 /// returned rotation amount is for a rotate right, where elements move from 2520 /// higher elements to lower elements. \p LoSrc indicates the first source 2521 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2522 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2523 /// 0 or 1 if a rotation is found. 2524 /// 2525 /// NOTE: We talk about rotate to the right which matches how bit shift and 2526 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2527 /// and the table below write vectors with the lowest elements on the left. 2528 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2529 int Size = Mask.size(); 2530 2531 // We need to detect various ways of spelling a rotation: 2532 // [11, 12, 13, 14, 15, 0, 1, 2] 2533 // [-1, 12, 13, 14, -1, -1, 1, -1] 2534 // [-1, -1, -1, -1, -1, -1, 1, 2] 2535 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2536 // [-1, 4, 5, 6, -1, -1, 9, -1] 2537 // [-1, 4, 5, 6, -1, -1, -1, -1] 2538 int Rotation = 0; 2539 LoSrc = -1; 2540 HiSrc = -1; 2541 for (int i = 0; i != Size; ++i) { 2542 int M = Mask[i]; 2543 if (M < 0) 2544 continue; 2545 2546 // Determine where a rotate vector would have started. 2547 int StartIdx = i - (M % Size); 2548 // The identity rotation isn't interesting, stop. 2549 if (StartIdx == 0) 2550 return -1; 2551 2552 // If we found the tail of a vector the rotation must be the missing 2553 // front. If we found the head of a vector, it must be how much of the 2554 // head. 2555 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2556 2557 if (Rotation == 0) 2558 Rotation = CandidateRotation; 2559 else if (Rotation != CandidateRotation) 2560 // The rotations don't match, so we can't match this mask. 2561 return -1; 2562 2563 // Compute which value this mask is pointing at. 2564 int MaskSrc = M < Size ? 0 : 1; 2565 2566 // Compute which of the two target values this index should be assigned to. 2567 // This reflects whether the high elements are remaining or the low elemnts 2568 // are remaining. 2569 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2570 2571 // Either set up this value if we've not encountered it before, or check 2572 // that it remains consistent. 2573 if (TargetSrc < 0) 2574 TargetSrc = MaskSrc; 2575 else if (TargetSrc != MaskSrc) 2576 // This may be a rotation, but it pulls from the inputs in some 2577 // unsupported interleaving. 2578 return -1; 2579 } 2580 2581 // Check that we successfully analyzed the mask, and normalize the results. 2582 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2583 assert((LoSrc >= 0 || HiSrc >= 0) && 2584 "Failed to find a rotated input vector!"); 2585 2586 return Rotation; 2587 } 2588 2589 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2590 const RISCVSubtarget &Subtarget) { 2591 SDValue V1 = Op.getOperand(0); 2592 SDValue V2 = Op.getOperand(1); 2593 SDLoc DL(Op); 2594 MVT XLenVT = Subtarget.getXLenVT(); 2595 MVT VT = Op.getSimpleValueType(); 2596 unsigned NumElts = VT.getVectorNumElements(); 2597 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2598 2599 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2600 2601 SDValue TrueMask, VL; 2602 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2603 2604 if (SVN->isSplat()) { 2605 const int Lane = SVN->getSplatIndex(); 2606 if (Lane >= 0) { 2607 MVT SVT = VT.getVectorElementType(); 2608 2609 // Turn splatted vector load into a strided load with an X0 stride. 2610 SDValue V = V1; 2611 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2612 // with undef. 2613 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2614 int Offset = Lane; 2615 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2616 int OpElements = 2617 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2618 V = V.getOperand(Offset / OpElements); 2619 Offset %= OpElements; 2620 } 2621 2622 // We need to ensure the load isn't atomic or volatile. 2623 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2624 auto *Ld = cast<LoadSDNode>(V); 2625 Offset *= SVT.getStoreSize(); 2626 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2627 TypeSize::Fixed(Offset), DL); 2628 2629 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2630 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2631 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2632 SDValue IntID = 2633 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2634 SDValue Ops[] = {Ld->getChain(), 2635 IntID, 2636 DAG.getUNDEF(ContainerVT), 2637 NewAddr, 2638 DAG.getRegister(RISCV::X0, XLenVT), 2639 VL}; 2640 SDValue NewLoad = DAG.getMemIntrinsicNode( 2641 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2642 DAG.getMachineFunction().getMachineMemOperand( 2643 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2644 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2645 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2646 } 2647 2648 // Otherwise use a scalar load and splat. This will give the best 2649 // opportunity to fold a splat into the operation. ISel can turn it into 2650 // the x0 strided load if we aren't able to fold away the select. 2651 if (SVT.isFloatingPoint()) 2652 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2653 Ld->getPointerInfo().getWithOffset(Offset), 2654 Ld->getOriginalAlign(), 2655 Ld->getMemOperand()->getFlags()); 2656 else 2657 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2658 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2659 Ld->getOriginalAlign(), 2660 Ld->getMemOperand()->getFlags()); 2661 DAG.makeEquivalentMemoryOrdering(Ld, V); 2662 2663 unsigned Opc = 2664 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2665 SDValue Splat = 2666 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2667 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2668 } 2669 2670 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2671 assert(Lane < (int)NumElts && "Unexpected lane!"); 2672 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, 2673 V1, DAG.getConstant(Lane, DL, XLenVT), 2674 TrueMask, DAG.getUNDEF(ContainerVT), VL); 2675 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2676 } 2677 } 2678 2679 ArrayRef<int> Mask = SVN->getMask(); 2680 2681 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2682 // be undef which can be handled with a single SLIDEDOWN/UP. 2683 int LoSrc, HiSrc; 2684 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2685 if (Rotation > 0) { 2686 SDValue LoV, HiV; 2687 if (LoSrc >= 0) { 2688 LoV = LoSrc == 0 ? V1 : V2; 2689 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2690 } 2691 if (HiSrc >= 0) { 2692 HiV = HiSrc == 0 ? V1 : V2; 2693 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2694 } 2695 2696 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2697 // to slide LoV up by (NumElts - Rotation). 2698 unsigned InvRotate = NumElts - Rotation; 2699 2700 SDValue Res = DAG.getUNDEF(ContainerVT); 2701 if (HiV) { 2702 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2703 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2704 // causes multiple vsetvlis in some test cases such as lowering 2705 // reduce.mul 2706 SDValue DownVL = VL; 2707 if (LoV) 2708 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2709 Res = 2710 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2711 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2712 } 2713 if (LoV) 2714 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2715 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2716 2717 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2718 } 2719 2720 // Detect an interleave shuffle and lower to 2721 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2722 bool SwapSources; 2723 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2724 // Swap sources if needed. 2725 if (SwapSources) 2726 std::swap(V1, V2); 2727 2728 // Extract the lower half of the vectors. 2729 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2730 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2731 DAG.getConstant(0, DL, XLenVT)); 2732 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2733 DAG.getConstant(0, DL, XLenVT)); 2734 2735 // Double the element width and halve the number of elements in an int type. 2736 unsigned EltBits = VT.getScalarSizeInBits(); 2737 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2738 MVT WideIntVT = 2739 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2740 // Convert this to a scalable vector. We need to base this on the 2741 // destination size to ensure there's always a type with a smaller LMUL. 2742 MVT WideIntContainerVT = 2743 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2744 2745 // Convert sources to scalable vectors with the same element count as the 2746 // larger type. 2747 MVT HalfContainerVT = MVT::getVectorVT( 2748 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2749 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2750 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2751 2752 // Cast sources to integer. 2753 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2754 MVT IntHalfVT = 2755 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2756 V1 = DAG.getBitcast(IntHalfVT, V1); 2757 V2 = DAG.getBitcast(IntHalfVT, V2); 2758 2759 // Freeze V2 since we use it twice and we need to be sure that the add and 2760 // multiply see the same value. 2761 V2 = DAG.getFreeze(V2); 2762 2763 // Recreate TrueMask using the widened type's element count. 2764 TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG); 2765 2766 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2767 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2768 V2, TrueMask, VL); 2769 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2770 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2771 DAG.getUNDEF(IntHalfVT), 2772 DAG.getAllOnesConstant(DL, XLenVT)); 2773 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2774 V2, Multiplier, TrueMask, VL); 2775 // Add the new copies to our previous addition giving us 2^eltbits copies of 2776 // V2. This is equivalent to shifting V2 left by eltbits. This should 2777 // combine with the vwmulu.vv above to form vwmaccu.vv. 2778 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2779 TrueMask, VL); 2780 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2781 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2782 // vector VT. 2783 ContainerVT = 2784 MVT::getVectorVT(VT.getVectorElementType(), 2785 WideIntContainerVT.getVectorElementCount() * 2); 2786 Add = DAG.getBitcast(ContainerVT, Add); 2787 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2788 } 2789 2790 // Detect shuffles which can be re-expressed as vector selects; these are 2791 // shuffles in which each element in the destination is taken from an element 2792 // at the corresponding index in either source vectors. 2793 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2794 int MaskIndex = MaskIdx.value(); 2795 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2796 }); 2797 2798 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2799 2800 SmallVector<SDValue> MaskVals; 2801 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2802 // merged with a second vrgather. 2803 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2804 2805 // By default we preserve the original operand order, and use a mask to 2806 // select LHS as true and RHS as false. However, since RVV vector selects may 2807 // feature splats but only on the LHS, we may choose to invert our mask and 2808 // instead select between RHS and LHS. 2809 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2810 bool InvertMask = IsSelect == SwapOps; 2811 2812 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2813 // half. 2814 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2815 2816 // Now construct the mask that will be used by the vselect or blended 2817 // vrgather operation. For vrgathers, construct the appropriate indices into 2818 // each vector. 2819 for (int MaskIndex : Mask) { 2820 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2821 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2822 if (!IsSelect) { 2823 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2824 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2825 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2826 : DAG.getUNDEF(XLenVT)); 2827 GatherIndicesRHS.push_back( 2828 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2829 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2830 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2831 ++LHSIndexCounts[MaskIndex]; 2832 if (!IsLHSOrUndefIndex) 2833 ++RHSIndexCounts[MaskIndex - NumElts]; 2834 } 2835 } 2836 2837 if (SwapOps) { 2838 std::swap(V1, V2); 2839 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2840 } 2841 2842 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2843 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2844 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2845 2846 if (IsSelect) 2847 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2848 2849 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2850 // On such a large vector we're unable to use i8 as the index type. 2851 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2852 // may involve vector splitting if we're already at LMUL=8, or our 2853 // user-supplied maximum fixed-length LMUL. 2854 return SDValue(); 2855 } 2856 2857 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2858 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2859 MVT IndexVT = VT.changeTypeToInteger(); 2860 // Since we can't introduce illegal index types at this stage, use i16 and 2861 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2862 // than XLenVT. 2863 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2864 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2865 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2866 } 2867 2868 MVT IndexContainerVT = 2869 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2870 2871 SDValue Gather; 2872 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2873 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2874 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2875 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2876 Subtarget); 2877 } else { 2878 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2879 // If only one index is used, we can use a "splat" vrgather. 2880 // TODO: We can splat the most-common index and fix-up any stragglers, if 2881 // that's beneficial. 2882 if (LHSIndexCounts.size() == 1) { 2883 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2884 Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2885 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, 2886 DAG.getUNDEF(ContainerVT), VL); 2887 } else { 2888 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2889 LHSIndices = 2890 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2891 2892 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2893 TrueMask, DAG.getUNDEF(ContainerVT), VL); 2894 } 2895 } 2896 2897 // If a second vector operand is used by this shuffle, blend it in with an 2898 // additional vrgather. 2899 if (!V2.isUndef()) { 2900 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2901 2902 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2903 SelectMask = 2904 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2905 2906 // If only one index is used, we can use a "splat" vrgather. 2907 // TODO: We can splat the most-common index and fix-up any stragglers, if 2908 // that's beneficial. 2909 if (RHSIndexCounts.size() == 1) { 2910 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2911 Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2912 DAG.getConstant(SplatIndex, DL, XLenVT), SelectMask, 2913 Gather, VL); 2914 } else { 2915 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2916 RHSIndices = 2917 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2918 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, 2919 SelectMask, Gather, VL); 2920 } 2921 } 2922 2923 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2924 } 2925 2926 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2927 // Support splats for any type. These should type legalize well. 2928 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2929 return true; 2930 2931 // Only support legal VTs for other shuffles for now. 2932 if (!isTypeLegal(VT)) 2933 return false; 2934 2935 MVT SVT = VT.getSimpleVT(); 2936 2937 bool SwapSources; 2938 int LoSrc, HiSrc; 2939 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2940 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2941 } 2942 2943 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2944 // the exponent. 2945 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2946 MVT VT = Op.getSimpleValueType(); 2947 unsigned EltSize = VT.getScalarSizeInBits(); 2948 SDValue Src = Op.getOperand(0); 2949 SDLoc DL(Op); 2950 2951 // We need a FP type that can represent the value. 2952 // TODO: Use f16 for i8 when possible? 2953 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2954 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2955 2956 // Legal types should have been checked in the RISCVTargetLowering 2957 // constructor. 2958 // TODO: Splitting may make sense in some cases. 2959 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2960 "Expected legal float type!"); 2961 2962 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2963 // The trailing zero count is equal to log2 of this single bit value. 2964 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2965 SDValue Neg = 2966 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2967 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2968 } 2969 2970 // We have a legal FP type, convert to it. 2971 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2972 // Bitcast to integer and shift the exponent to the LSB. 2973 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2974 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2975 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2976 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2977 DAG.getConstant(ShiftAmt, DL, IntVT)); 2978 // Truncate back to original type to allow vnsrl. 2979 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2980 // The exponent contains log2 of the value in biased form. 2981 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2982 2983 // For trailing zeros, we just need to subtract the bias. 2984 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2985 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2986 DAG.getConstant(ExponentBias, DL, VT)); 2987 2988 // For leading zeros, we need to remove the bias and convert from log2 to 2989 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2990 unsigned Adjust = ExponentBias + (EltSize - 1); 2991 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2992 } 2993 2994 // While RVV has alignment restrictions, we should always be able to load as a 2995 // legal equivalently-sized byte-typed vector instead. This method is 2996 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2997 // the load is already correctly-aligned, it returns SDValue(). 2998 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2999 SelectionDAG &DAG) const { 3000 auto *Load = cast<LoadSDNode>(Op); 3001 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 3002 3003 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 3004 Load->getMemoryVT(), 3005 *Load->getMemOperand())) 3006 return SDValue(); 3007 3008 SDLoc DL(Op); 3009 MVT VT = Op.getSimpleValueType(); 3010 unsigned EltSizeBits = VT.getScalarSizeInBits(); 3011 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 3012 "Unexpected unaligned RVV load type"); 3013 MVT NewVT = 3014 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 3015 assert(NewVT.isValid() && 3016 "Expecting equally-sized RVV vector types to be legal"); 3017 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 3018 Load->getPointerInfo(), Load->getOriginalAlign(), 3019 Load->getMemOperand()->getFlags()); 3020 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 3021 } 3022 3023 // While RVV has alignment restrictions, we should always be able to store as a 3024 // legal equivalently-sized byte-typed vector instead. This method is 3025 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 3026 // returns SDValue() if the store is already correctly aligned. 3027 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 3028 SelectionDAG &DAG) const { 3029 auto *Store = cast<StoreSDNode>(Op); 3030 assert(Store && Store->getValue().getValueType().isVector() && 3031 "Expected vector store"); 3032 3033 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 3034 Store->getMemoryVT(), 3035 *Store->getMemOperand())) 3036 return SDValue(); 3037 3038 SDLoc DL(Op); 3039 SDValue StoredVal = Store->getValue(); 3040 MVT VT = StoredVal.getSimpleValueType(); 3041 unsigned EltSizeBits = VT.getScalarSizeInBits(); 3042 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 3043 "Unexpected unaligned RVV store type"); 3044 MVT NewVT = 3045 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 3046 assert(NewVT.isValid() && 3047 "Expecting equally-sized RVV vector types to be legal"); 3048 StoredVal = DAG.getBitcast(NewVT, StoredVal); 3049 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 3050 Store->getPointerInfo(), Store->getOriginalAlign(), 3051 Store->getMemOperand()->getFlags()); 3052 } 3053 3054 static SDValue lowerConstant(SDValue Op, SelectionDAG &DAG, 3055 const RISCVSubtarget &Subtarget) { 3056 assert(Op.getValueType() == MVT::i64 && "Unexpected VT"); 3057 3058 int64_t Imm = cast<ConstantSDNode>(Op)->getSExtValue(); 3059 3060 // All simm32 constants should be handled by isel. 3061 // NOTE: The getMaxBuildIntsCost call below should return a value >= 2 making 3062 // this check redundant, but small immediates are common so this check 3063 // should have better compile time. 3064 if (isInt<32>(Imm)) 3065 return Op; 3066 3067 // We only need to cost the immediate, if constant pool lowering is enabled. 3068 if (!Subtarget.useConstantPoolForLargeInts()) 3069 return Op; 3070 3071 RISCVMatInt::InstSeq Seq = 3072 RISCVMatInt::generateInstSeq(Imm, Subtarget.getFeatureBits()); 3073 if (Seq.size() <= Subtarget.getMaxBuildIntsCost()) 3074 return Op; 3075 3076 // Expand to a constant pool using the default expansion code. 3077 return SDValue(); 3078 } 3079 3080 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 3081 SelectionDAG &DAG) const { 3082 switch (Op.getOpcode()) { 3083 default: 3084 report_fatal_error("unimplemented operand"); 3085 case ISD::GlobalAddress: 3086 return lowerGlobalAddress(Op, DAG); 3087 case ISD::BlockAddress: 3088 return lowerBlockAddress(Op, DAG); 3089 case ISD::ConstantPool: 3090 return lowerConstantPool(Op, DAG); 3091 case ISD::JumpTable: 3092 return lowerJumpTable(Op, DAG); 3093 case ISD::GlobalTLSAddress: 3094 return lowerGlobalTLSAddress(Op, DAG); 3095 case ISD::Constant: 3096 return lowerConstant(Op, DAG, Subtarget); 3097 case ISD::SELECT: 3098 return lowerSELECT(Op, DAG); 3099 case ISD::BRCOND: 3100 return lowerBRCOND(Op, DAG); 3101 case ISD::VASTART: 3102 return lowerVASTART(Op, DAG); 3103 case ISD::FRAMEADDR: 3104 return lowerFRAMEADDR(Op, DAG); 3105 case ISD::RETURNADDR: 3106 return lowerRETURNADDR(Op, DAG); 3107 case ISD::SHL_PARTS: 3108 return lowerShiftLeftParts(Op, DAG); 3109 case ISD::SRA_PARTS: 3110 return lowerShiftRightParts(Op, DAG, true); 3111 case ISD::SRL_PARTS: 3112 return lowerShiftRightParts(Op, DAG, false); 3113 case ISD::BITCAST: { 3114 SDLoc DL(Op); 3115 EVT VT = Op.getValueType(); 3116 SDValue Op0 = Op.getOperand(0); 3117 EVT Op0VT = Op0.getValueType(); 3118 MVT XLenVT = Subtarget.getXLenVT(); 3119 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 3120 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 3121 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 3122 return FPConv; 3123 } 3124 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 3125 Subtarget.hasStdExtF()) { 3126 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3127 SDValue FPConv = 3128 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3129 return FPConv; 3130 } 3131 3132 // Consider other scalar<->scalar casts as legal if the types are legal. 3133 // Otherwise expand them. 3134 if (!VT.isVector() && !Op0VT.isVector()) { 3135 if (isTypeLegal(VT) && isTypeLegal(Op0VT)) 3136 return Op; 3137 return SDValue(); 3138 } 3139 3140 assert(!VT.isScalableVector() && !Op0VT.isScalableVector() && 3141 "Unexpected types"); 3142 3143 if (VT.isFixedLengthVector()) { 3144 // We can handle fixed length vector bitcasts with a simple replacement 3145 // in isel. 3146 if (Op0VT.isFixedLengthVector()) 3147 return Op; 3148 // When bitcasting from scalar to fixed-length vector, insert the scalar 3149 // into a one-element vector of the result type, and perform a vector 3150 // bitcast. 3151 if (!Op0VT.isVector()) { 3152 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 3153 if (!isTypeLegal(BVT)) 3154 return SDValue(); 3155 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 3156 DAG.getUNDEF(BVT), Op0, 3157 DAG.getConstant(0, DL, XLenVT))); 3158 } 3159 return SDValue(); 3160 } 3161 // Custom-legalize bitcasts from fixed-length vector types to scalar types 3162 // thus: bitcast the vector to a one-element vector type whose element type 3163 // is the same as the result type, and extract the first element. 3164 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 3165 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 3166 if (!isTypeLegal(BVT)) 3167 return SDValue(); 3168 SDValue BVec = DAG.getBitcast(BVT, Op0); 3169 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 3170 DAG.getConstant(0, DL, XLenVT)); 3171 } 3172 return SDValue(); 3173 } 3174 case ISD::INTRINSIC_WO_CHAIN: 3175 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3176 case ISD::INTRINSIC_W_CHAIN: 3177 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3178 case ISD::INTRINSIC_VOID: 3179 return LowerINTRINSIC_VOID(Op, DAG); 3180 case ISD::BSWAP: 3181 case ISD::BITREVERSE: { 3182 MVT VT = Op.getSimpleValueType(); 3183 SDLoc DL(Op); 3184 if (Subtarget.hasStdExtZbp()) { 3185 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3186 // Start with the maximum immediate value which is the bitwidth - 1. 3187 unsigned Imm = VT.getSizeInBits() - 1; 3188 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3189 if (Op.getOpcode() == ISD::BSWAP) 3190 Imm &= ~0x7U; 3191 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3192 DAG.getConstant(Imm, DL, VT)); 3193 } 3194 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3195 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3196 // Expand bitreverse to a bswap(rev8) followed by brev8. 3197 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3198 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3199 // as brev8 by an isel pattern. 3200 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3201 DAG.getConstant(7, DL, VT)); 3202 } 3203 case ISD::FSHL: 3204 case ISD::FSHR: { 3205 MVT VT = Op.getSimpleValueType(); 3206 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3207 SDLoc DL(Op); 3208 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3209 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3210 // accidentally setting the extra bit. 3211 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3212 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3213 DAG.getConstant(ShAmtWidth, DL, VT)); 3214 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3215 // instruction use different orders. fshl will return its first operand for 3216 // shift of zero, fshr will return its second operand. fsl and fsr both 3217 // return rs1 so the ISD nodes need to have different operand orders. 3218 // Shift amount is in rs2. 3219 SDValue Op0 = Op.getOperand(0); 3220 SDValue Op1 = Op.getOperand(1); 3221 unsigned Opc = RISCVISD::FSL; 3222 if (Op.getOpcode() == ISD::FSHR) { 3223 std::swap(Op0, Op1); 3224 Opc = RISCVISD::FSR; 3225 } 3226 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3227 } 3228 case ISD::TRUNCATE: 3229 // Only custom-lower vector truncates 3230 if (!Op.getSimpleValueType().isVector()) 3231 return Op; 3232 return lowerVectorTruncLike(Op, DAG); 3233 case ISD::ANY_EXTEND: 3234 case ISD::ZERO_EXTEND: 3235 if (Op.getOperand(0).getValueType().isVector() && 3236 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3237 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3238 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3239 case ISD::SIGN_EXTEND: 3240 if (Op.getOperand(0).getValueType().isVector() && 3241 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3242 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3243 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3244 case ISD::SPLAT_VECTOR_PARTS: 3245 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3246 case ISD::INSERT_VECTOR_ELT: 3247 return lowerINSERT_VECTOR_ELT(Op, DAG); 3248 case ISD::EXTRACT_VECTOR_ELT: 3249 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3250 case ISD::VSCALE: { 3251 MVT VT = Op.getSimpleValueType(); 3252 SDLoc DL(Op); 3253 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3254 // We define our scalable vector types for lmul=1 to use a 64 bit known 3255 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3256 // vscale as VLENB / 8. 3257 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3258 if (Subtarget.getRealMinVLen() < RISCV::RVVBitsPerBlock) 3259 report_fatal_error("Support for VLEN==32 is incomplete."); 3260 // We assume VLENB is a multiple of 8. We manually choose the best shift 3261 // here because SimplifyDemandedBits isn't always able to simplify it. 3262 uint64_t Val = Op.getConstantOperandVal(0); 3263 if (isPowerOf2_64(Val)) { 3264 uint64_t Log2 = Log2_64(Val); 3265 if (Log2 < 3) 3266 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3267 DAG.getConstant(3 - Log2, DL, VT)); 3268 if (Log2 > 3) 3269 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3270 DAG.getConstant(Log2 - 3, DL, VT)); 3271 return VLENB; 3272 } 3273 // If the multiplier is a multiple of 8, scale it down to avoid needing 3274 // to shift the VLENB value. 3275 if ((Val % 8) == 0) 3276 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3277 DAG.getConstant(Val / 8, DL, VT)); 3278 3279 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3280 DAG.getConstant(3, DL, VT)); 3281 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3282 } 3283 case ISD::FPOWI: { 3284 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3285 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3286 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3287 Op.getOperand(1).getValueType() == MVT::i32) { 3288 SDLoc DL(Op); 3289 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3290 SDValue Powi = 3291 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3292 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3293 DAG.getIntPtrConstant(0, DL)); 3294 } 3295 return SDValue(); 3296 } 3297 case ISD::FP_EXTEND: 3298 case ISD::FP_ROUND: 3299 if (!Op.getValueType().isVector()) 3300 return Op; 3301 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3302 case ISD::FP_TO_SINT: 3303 case ISD::FP_TO_UINT: 3304 case ISD::SINT_TO_FP: 3305 case ISD::UINT_TO_FP: { 3306 // RVV can only do fp<->int conversions to types half/double the size as 3307 // the source. We custom-lower any conversions that do two hops into 3308 // sequences. 3309 MVT VT = Op.getSimpleValueType(); 3310 if (!VT.isVector()) 3311 return Op; 3312 SDLoc DL(Op); 3313 SDValue Src = Op.getOperand(0); 3314 MVT EltVT = VT.getVectorElementType(); 3315 MVT SrcVT = Src.getSimpleValueType(); 3316 MVT SrcEltVT = SrcVT.getVectorElementType(); 3317 unsigned EltSize = EltVT.getSizeInBits(); 3318 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3319 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3320 "Unexpected vector element types"); 3321 3322 bool IsInt2FP = SrcEltVT.isInteger(); 3323 // Widening conversions 3324 if (EltSize > (2 * SrcEltSize)) { 3325 if (IsInt2FP) { 3326 // Do a regular integer sign/zero extension then convert to float. 3327 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), 3328 VT.getVectorElementCount()); 3329 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3330 ? ISD::ZERO_EXTEND 3331 : ISD::SIGN_EXTEND; 3332 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3333 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3334 } 3335 // FP2Int 3336 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3337 // Do one doubling fp_extend then complete the operation by converting 3338 // to int. 3339 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3340 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3341 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3342 } 3343 3344 // Narrowing conversions 3345 if (SrcEltSize > (2 * EltSize)) { 3346 if (IsInt2FP) { 3347 // One narrowing int_to_fp, then an fp_round. 3348 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3349 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3350 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3351 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3352 } 3353 // FP2Int 3354 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3355 // representable by the integer, the result is poison. 3356 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 3357 VT.getVectorElementCount()); 3358 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3359 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3360 } 3361 3362 // Scalable vectors can exit here. Patterns will handle equally-sized 3363 // conversions halving/doubling ones. 3364 if (!VT.isFixedLengthVector()) 3365 return Op; 3366 3367 // For fixed-length vectors we lower to a custom "VL" node. 3368 unsigned RVVOpc = 0; 3369 switch (Op.getOpcode()) { 3370 default: 3371 llvm_unreachable("Impossible opcode"); 3372 case ISD::FP_TO_SINT: 3373 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3374 break; 3375 case ISD::FP_TO_UINT: 3376 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3377 break; 3378 case ISD::SINT_TO_FP: 3379 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3380 break; 3381 case ISD::UINT_TO_FP: 3382 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3383 break; 3384 } 3385 3386 MVT ContainerVT, SrcContainerVT; 3387 // Derive the reference container type from the larger vector type. 3388 if (SrcEltSize > EltSize) { 3389 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3390 ContainerVT = 3391 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3392 } else { 3393 ContainerVT = getContainerForFixedLengthVector(VT); 3394 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3395 } 3396 3397 SDValue Mask, VL; 3398 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3399 3400 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3401 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3402 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3403 } 3404 case ISD::FP_TO_SINT_SAT: 3405 case ISD::FP_TO_UINT_SAT: 3406 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3407 case ISD::FTRUNC: 3408 case ISD::FCEIL: 3409 case ISD::FFLOOR: 3410 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3411 case ISD::FROUND: 3412 return lowerFROUND(Op, DAG); 3413 case ISD::VECREDUCE_ADD: 3414 case ISD::VECREDUCE_UMAX: 3415 case ISD::VECREDUCE_SMAX: 3416 case ISD::VECREDUCE_UMIN: 3417 case ISD::VECREDUCE_SMIN: 3418 return lowerVECREDUCE(Op, DAG); 3419 case ISD::VECREDUCE_AND: 3420 case ISD::VECREDUCE_OR: 3421 case ISD::VECREDUCE_XOR: 3422 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3423 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3424 return lowerVECREDUCE(Op, DAG); 3425 case ISD::VECREDUCE_FADD: 3426 case ISD::VECREDUCE_SEQ_FADD: 3427 case ISD::VECREDUCE_FMIN: 3428 case ISD::VECREDUCE_FMAX: 3429 return lowerFPVECREDUCE(Op, DAG); 3430 case ISD::VP_REDUCE_ADD: 3431 case ISD::VP_REDUCE_UMAX: 3432 case ISD::VP_REDUCE_SMAX: 3433 case ISD::VP_REDUCE_UMIN: 3434 case ISD::VP_REDUCE_SMIN: 3435 case ISD::VP_REDUCE_FADD: 3436 case ISD::VP_REDUCE_SEQ_FADD: 3437 case ISD::VP_REDUCE_FMIN: 3438 case ISD::VP_REDUCE_FMAX: 3439 return lowerVPREDUCE(Op, DAG); 3440 case ISD::VP_REDUCE_AND: 3441 case ISD::VP_REDUCE_OR: 3442 case ISD::VP_REDUCE_XOR: 3443 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3444 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3445 return lowerVPREDUCE(Op, DAG); 3446 case ISD::INSERT_SUBVECTOR: 3447 return lowerINSERT_SUBVECTOR(Op, DAG); 3448 case ISD::EXTRACT_SUBVECTOR: 3449 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3450 case ISD::STEP_VECTOR: 3451 return lowerSTEP_VECTOR(Op, DAG); 3452 case ISD::VECTOR_REVERSE: 3453 return lowerVECTOR_REVERSE(Op, DAG); 3454 case ISD::VECTOR_SPLICE: 3455 return lowerVECTOR_SPLICE(Op, DAG); 3456 case ISD::BUILD_VECTOR: 3457 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3458 case ISD::SPLAT_VECTOR: 3459 if (Op.getValueType().getVectorElementType() == MVT::i1) 3460 return lowerVectorMaskSplat(Op, DAG); 3461 return SDValue(); 3462 case ISD::VECTOR_SHUFFLE: 3463 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3464 case ISD::CONCAT_VECTORS: { 3465 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3466 // better than going through the stack, as the default expansion does. 3467 SDLoc DL(Op); 3468 MVT VT = Op.getSimpleValueType(); 3469 unsigned NumOpElts = 3470 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3471 SDValue Vec = DAG.getUNDEF(VT); 3472 for (const auto &OpIdx : enumerate(Op->ops())) { 3473 SDValue SubVec = OpIdx.value(); 3474 // Don't insert undef subvectors. 3475 if (SubVec.isUndef()) 3476 continue; 3477 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3478 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3479 } 3480 return Vec; 3481 } 3482 case ISD::LOAD: 3483 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3484 return V; 3485 if (Op.getValueType().isFixedLengthVector()) 3486 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3487 return Op; 3488 case ISD::STORE: 3489 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3490 return V; 3491 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3492 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3493 return Op; 3494 case ISD::MLOAD: 3495 case ISD::VP_LOAD: 3496 return lowerMaskedLoad(Op, DAG); 3497 case ISD::MSTORE: 3498 case ISD::VP_STORE: 3499 return lowerMaskedStore(Op, DAG); 3500 case ISD::SETCC: 3501 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3502 case ISD::ADD: 3503 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3504 case ISD::SUB: 3505 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3506 case ISD::MUL: 3507 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3508 case ISD::MULHS: 3509 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3510 case ISD::MULHU: 3511 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3512 case ISD::AND: 3513 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3514 RISCVISD::AND_VL); 3515 case ISD::OR: 3516 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3517 RISCVISD::OR_VL); 3518 case ISD::XOR: 3519 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3520 RISCVISD::XOR_VL); 3521 case ISD::SDIV: 3522 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3523 case ISD::SREM: 3524 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3525 case ISD::UDIV: 3526 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3527 case ISD::UREM: 3528 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3529 case ISD::SHL: 3530 case ISD::SRA: 3531 case ISD::SRL: 3532 if (Op.getSimpleValueType().isFixedLengthVector()) 3533 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3534 // This can be called for an i32 shift amount that needs to be promoted. 3535 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3536 "Unexpected custom legalisation"); 3537 return SDValue(); 3538 case ISD::SADDSAT: 3539 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3540 case ISD::UADDSAT: 3541 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3542 case ISD::SSUBSAT: 3543 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3544 case ISD::USUBSAT: 3545 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3546 case ISD::FADD: 3547 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3548 case ISD::FSUB: 3549 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3550 case ISD::FMUL: 3551 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3552 case ISD::FDIV: 3553 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3554 case ISD::FNEG: 3555 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3556 case ISD::FABS: 3557 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3558 case ISD::FSQRT: 3559 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3560 case ISD::FMA: 3561 return lowerToScalableOp(Op, DAG, RISCVISD::VFMADD_VL); 3562 case ISD::SMIN: 3563 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3564 case ISD::SMAX: 3565 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3566 case ISD::UMIN: 3567 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3568 case ISD::UMAX: 3569 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3570 case ISD::FMINNUM: 3571 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3572 case ISD::FMAXNUM: 3573 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3574 case ISD::ABS: 3575 return lowerABS(Op, DAG); 3576 case ISD::CTLZ_ZERO_UNDEF: 3577 case ISD::CTTZ_ZERO_UNDEF: 3578 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3579 case ISD::VSELECT: 3580 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3581 case ISD::FCOPYSIGN: 3582 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3583 case ISD::MGATHER: 3584 case ISD::VP_GATHER: 3585 return lowerMaskedGather(Op, DAG); 3586 case ISD::MSCATTER: 3587 case ISD::VP_SCATTER: 3588 return lowerMaskedScatter(Op, DAG); 3589 case ISD::FLT_ROUNDS_: 3590 return lowerGET_ROUNDING(Op, DAG); 3591 case ISD::SET_ROUNDING: 3592 return lowerSET_ROUNDING(Op, DAG); 3593 case ISD::EH_DWARF_CFA: 3594 return lowerEH_DWARF_CFA(Op, DAG); 3595 case ISD::VP_SELECT: 3596 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3597 case ISD::VP_MERGE: 3598 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3599 case ISD::VP_ADD: 3600 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3601 case ISD::VP_SUB: 3602 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3603 case ISD::VP_MUL: 3604 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3605 case ISD::VP_SDIV: 3606 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3607 case ISD::VP_UDIV: 3608 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3609 case ISD::VP_SREM: 3610 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3611 case ISD::VP_UREM: 3612 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3613 case ISD::VP_AND: 3614 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3615 case ISD::VP_OR: 3616 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3617 case ISD::VP_XOR: 3618 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3619 case ISD::VP_ASHR: 3620 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3621 case ISD::VP_LSHR: 3622 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3623 case ISD::VP_SHL: 3624 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3625 case ISD::VP_FADD: 3626 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3627 case ISD::VP_FSUB: 3628 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3629 case ISD::VP_FMUL: 3630 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3631 case ISD::VP_FDIV: 3632 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3633 case ISD::VP_FNEG: 3634 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3635 case ISD::VP_FMA: 3636 return lowerVPOp(Op, DAG, RISCVISD::VFMADD_VL); 3637 case ISD::VP_SIGN_EXTEND: 3638 case ISD::VP_ZERO_EXTEND: 3639 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3640 return lowerVPExtMaskOp(Op, DAG); 3641 return lowerVPOp(Op, DAG, 3642 Op.getOpcode() == ISD::VP_SIGN_EXTEND 3643 ? RISCVISD::VSEXT_VL 3644 : RISCVISD::VZEXT_VL); 3645 case ISD::VP_TRUNCATE: 3646 return lowerVectorTruncLike(Op, DAG); 3647 case ISD::VP_FP_EXTEND: 3648 case ISD::VP_FP_ROUND: 3649 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3650 case ISD::VP_FPTOSI: 3651 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL); 3652 case ISD::VP_FPTOUI: 3653 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL); 3654 case ISD::VP_SITOFP: 3655 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL); 3656 case ISD::VP_UITOFP: 3657 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL); 3658 case ISD::VP_SETCC: 3659 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3660 return lowerVPSetCCMaskOp(Op, DAG); 3661 return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL); 3662 } 3663 } 3664 3665 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3666 SelectionDAG &DAG, unsigned Flags) { 3667 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3668 } 3669 3670 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3671 SelectionDAG &DAG, unsigned Flags) { 3672 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3673 Flags); 3674 } 3675 3676 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3677 SelectionDAG &DAG, unsigned Flags) { 3678 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3679 N->getOffset(), Flags); 3680 } 3681 3682 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3683 SelectionDAG &DAG, unsigned Flags) { 3684 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3685 } 3686 3687 template <class NodeTy> 3688 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3689 bool IsLocal) const { 3690 SDLoc DL(N); 3691 EVT Ty = getPointerTy(DAG.getDataLayout()); 3692 3693 if (isPositionIndependent()) { 3694 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3695 if (IsLocal) 3696 // Use PC-relative addressing to access the symbol. This generates the 3697 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3698 // %pcrel_lo(auipc)). 3699 return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr); 3700 3701 // Use PC-relative addressing to access the GOT for this symbol, then load 3702 // the address from the GOT. This generates the pattern (PseudoLA sym), 3703 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3704 MachineFunction &MF = DAG.getMachineFunction(); 3705 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3706 MachinePointerInfo::getGOT(MF), 3707 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3708 MachineMemOperand::MOInvariant, 3709 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3710 SDValue Load = 3711 DAG.getMemIntrinsicNode(RISCVISD::LA, DL, DAG.getVTList(Ty, MVT::Other), 3712 {DAG.getEntryNode(), Addr}, Ty, MemOp); 3713 return Load; 3714 } 3715 3716 switch (getTargetMachine().getCodeModel()) { 3717 default: 3718 report_fatal_error("Unsupported code model for lowering"); 3719 case CodeModel::Small: { 3720 // Generate a sequence for accessing addresses within the first 2 GiB of 3721 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3722 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3723 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3724 SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi); 3725 return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNHi, AddrLo); 3726 } 3727 case CodeModel::Medium: { 3728 // Generate a sequence for accessing addresses within any 2GiB range within 3729 // the address space. This generates the pattern (PseudoLLA sym), which 3730 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3731 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3732 return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr); 3733 } 3734 } 3735 } 3736 3737 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3738 SelectionDAG &DAG) const { 3739 SDLoc DL(Op); 3740 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3741 assert(N->getOffset() == 0 && "unexpected offset in global node"); 3742 return getAddr(N, DAG, N->getGlobal()->isDSOLocal()); 3743 } 3744 3745 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3746 SelectionDAG &DAG) const { 3747 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3748 3749 return getAddr(N, DAG); 3750 } 3751 3752 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3753 SelectionDAG &DAG) const { 3754 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3755 3756 return getAddr(N, DAG); 3757 } 3758 3759 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3760 SelectionDAG &DAG) const { 3761 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3762 3763 return getAddr(N, DAG); 3764 } 3765 3766 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3767 SelectionDAG &DAG, 3768 bool UseGOT) const { 3769 SDLoc DL(N); 3770 EVT Ty = getPointerTy(DAG.getDataLayout()); 3771 const GlobalValue *GV = N->getGlobal(); 3772 MVT XLenVT = Subtarget.getXLenVT(); 3773 3774 if (UseGOT) { 3775 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3776 // load the address from the GOT and add the thread pointer. This generates 3777 // the pattern (PseudoLA_TLS_IE sym), which expands to 3778 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3779 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3780 MachineFunction &MF = DAG.getMachineFunction(); 3781 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3782 MachinePointerInfo::getGOT(MF), 3783 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3784 MachineMemOperand::MOInvariant, 3785 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3786 SDValue Load = DAG.getMemIntrinsicNode( 3787 RISCVISD::LA_TLS_IE, DL, DAG.getVTList(Ty, MVT::Other), 3788 {DAG.getEntryNode(), Addr}, Ty, MemOp); 3789 3790 // Add the thread pointer. 3791 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3792 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3793 } 3794 3795 // Generate a sequence for accessing the address relative to the thread 3796 // pointer, with the appropriate adjustment for the thread pointer offset. 3797 // This generates the pattern 3798 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3799 SDValue AddrHi = 3800 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3801 SDValue AddrAdd = 3802 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3803 SDValue AddrLo = 3804 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3805 3806 SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi); 3807 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3808 SDValue MNAdd = 3809 DAG.getNode(RISCVISD::ADD_TPREL, DL, Ty, MNHi, TPReg, AddrAdd); 3810 return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNAdd, AddrLo); 3811 } 3812 3813 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3814 SelectionDAG &DAG) const { 3815 SDLoc DL(N); 3816 EVT Ty = getPointerTy(DAG.getDataLayout()); 3817 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3818 const GlobalValue *GV = N->getGlobal(); 3819 3820 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3821 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3822 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3823 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3824 SDValue Load = DAG.getNode(RISCVISD::LA_TLS_GD, DL, Ty, Addr); 3825 3826 // Prepare argument list to generate call. 3827 ArgListTy Args; 3828 ArgListEntry Entry; 3829 Entry.Node = Load; 3830 Entry.Ty = CallTy; 3831 Args.push_back(Entry); 3832 3833 // Setup call to __tls_get_addr. 3834 TargetLowering::CallLoweringInfo CLI(DAG); 3835 CLI.setDebugLoc(DL) 3836 .setChain(DAG.getEntryNode()) 3837 .setLibCallee(CallingConv::C, CallTy, 3838 DAG.getExternalSymbol("__tls_get_addr", Ty), 3839 std::move(Args)); 3840 3841 return LowerCallTo(CLI).first; 3842 } 3843 3844 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3845 SelectionDAG &DAG) const { 3846 SDLoc DL(Op); 3847 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3848 assert(N->getOffset() == 0 && "unexpected offset in global node"); 3849 3850 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3851 3852 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3853 CallingConv::GHC) 3854 report_fatal_error("In GHC calling convention TLS is not supported"); 3855 3856 SDValue Addr; 3857 switch (Model) { 3858 case TLSModel::LocalExec: 3859 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3860 break; 3861 case TLSModel::InitialExec: 3862 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3863 break; 3864 case TLSModel::LocalDynamic: 3865 case TLSModel::GeneralDynamic: 3866 Addr = getDynamicTLSAddr(N, DAG); 3867 break; 3868 } 3869 3870 return Addr; 3871 } 3872 3873 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3874 SDValue CondV = Op.getOperand(0); 3875 SDValue TrueV = Op.getOperand(1); 3876 SDValue FalseV = Op.getOperand(2); 3877 SDLoc DL(Op); 3878 MVT VT = Op.getSimpleValueType(); 3879 MVT XLenVT = Subtarget.getXLenVT(); 3880 3881 // Lower vector SELECTs to VSELECTs by splatting the condition. 3882 if (VT.isVector()) { 3883 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3884 SDValue CondSplat = VT.isScalableVector() 3885 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3886 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3887 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3888 } 3889 3890 // If the result type is XLenVT and CondV is the output of a SETCC node 3891 // which also operated on XLenVT inputs, then merge the SETCC node into the 3892 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3893 // compare+branch instructions. i.e.: 3894 // (select (setcc lhs, rhs, cc), truev, falsev) 3895 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3896 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3897 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3898 SDValue LHS = CondV.getOperand(0); 3899 SDValue RHS = CondV.getOperand(1); 3900 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3901 ISD::CondCode CCVal = CC->get(); 3902 3903 // Special case for a select of 2 constants that have a diffence of 1. 3904 // Normally this is done by DAGCombine, but if the select is introduced by 3905 // type legalization or op legalization, we miss it. Restricting to SETLT 3906 // case for now because that is what signed saturating add/sub need. 3907 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3908 // but we would probably want to swap the true/false values if the condition 3909 // is SETGE/SETLE to avoid an XORI. 3910 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3911 CCVal == ISD::SETLT) { 3912 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3913 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3914 if (TrueVal - 1 == FalseVal) 3915 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3916 if (TrueVal + 1 == FalseVal) 3917 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3918 } 3919 3920 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3921 3922 SDValue TargetCC = DAG.getCondCode(CCVal); 3923 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3924 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3925 } 3926 3927 // Otherwise: 3928 // (select condv, truev, falsev) 3929 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3930 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3931 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3932 3933 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3934 3935 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3936 } 3937 3938 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3939 SDValue CondV = Op.getOperand(1); 3940 SDLoc DL(Op); 3941 MVT XLenVT = Subtarget.getXLenVT(); 3942 3943 if (CondV.getOpcode() == ISD::SETCC && 3944 CondV.getOperand(0).getValueType() == XLenVT) { 3945 SDValue LHS = CondV.getOperand(0); 3946 SDValue RHS = CondV.getOperand(1); 3947 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3948 3949 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3950 3951 SDValue TargetCC = DAG.getCondCode(CCVal); 3952 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3953 LHS, RHS, TargetCC, Op.getOperand(2)); 3954 } 3955 3956 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3957 CondV, DAG.getConstant(0, DL, XLenVT), 3958 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3959 } 3960 3961 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3962 MachineFunction &MF = DAG.getMachineFunction(); 3963 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3964 3965 SDLoc DL(Op); 3966 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3967 getPointerTy(MF.getDataLayout())); 3968 3969 // vastart just stores the address of the VarArgsFrameIndex slot into the 3970 // memory location argument. 3971 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3972 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3973 MachinePointerInfo(SV)); 3974 } 3975 3976 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3977 SelectionDAG &DAG) const { 3978 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3979 MachineFunction &MF = DAG.getMachineFunction(); 3980 MachineFrameInfo &MFI = MF.getFrameInfo(); 3981 MFI.setFrameAddressIsTaken(true); 3982 Register FrameReg = RI.getFrameRegister(MF); 3983 int XLenInBytes = Subtarget.getXLen() / 8; 3984 3985 EVT VT = Op.getValueType(); 3986 SDLoc DL(Op); 3987 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3988 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3989 while (Depth--) { 3990 int Offset = -(XLenInBytes * 2); 3991 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3992 DAG.getIntPtrConstant(Offset, DL)); 3993 FrameAddr = 3994 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3995 } 3996 return FrameAddr; 3997 } 3998 3999 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 4000 SelectionDAG &DAG) const { 4001 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 4002 MachineFunction &MF = DAG.getMachineFunction(); 4003 MachineFrameInfo &MFI = MF.getFrameInfo(); 4004 MFI.setReturnAddressIsTaken(true); 4005 MVT XLenVT = Subtarget.getXLenVT(); 4006 int XLenInBytes = Subtarget.getXLen() / 8; 4007 4008 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 4009 return SDValue(); 4010 4011 EVT VT = Op.getValueType(); 4012 SDLoc DL(Op); 4013 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 4014 if (Depth) { 4015 int Off = -XLenInBytes; 4016 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 4017 SDValue Offset = DAG.getConstant(Off, DL, VT); 4018 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 4019 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 4020 MachinePointerInfo()); 4021 } 4022 4023 // Return the value of the return address register, marking it an implicit 4024 // live-in. 4025 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 4026 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 4027 } 4028 4029 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 4030 SelectionDAG &DAG) const { 4031 SDLoc DL(Op); 4032 SDValue Lo = Op.getOperand(0); 4033 SDValue Hi = Op.getOperand(1); 4034 SDValue Shamt = Op.getOperand(2); 4035 EVT VT = Lo.getValueType(); 4036 4037 // if Shamt-XLEN < 0: // Shamt < XLEN 4038 // Lo = Lo << Shamt 4039 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 4040 // else: 4041 // Lo = 0 4042 // Hi = Lo << (Shamt-XLEN) 4043 4044 SDValue Zero = DAG.getConstant(0, DL, VT); 4045 SDValue One = DAG.getConstant(1, DL, VT); 4046 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4047 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4048 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4049 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4050 4051 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 4052 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 4053 SDValue ShiftRightLo = 4054 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 4055 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 4056 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 4057 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 4058 4059 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4060 4061 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 4062 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4063 4064 SDValue Parts[2] = {Lo, Hi}; 4065 return DAG.getMergeValues(Parts, DL); 4066 } 4067 4068 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 4069 bool IsSRA) const { 4070 SDLoc DL(Op); 4071 SDValue Lo = Op.getOperand(0); 4072 SDValue Hi = Op.getOperand(1); 4073 SDValue Shamt = Op.getOperand(2); 4074 EVT VT = Lo.getValueType(); 4075 4076 // SRA expansion: 4077 // if Shamt-XLEN < 0: // Shamt < XLEN 4078 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4079 // Hi = Hi >>s Shamt 4080 // else: 4081 // Lo = Hi >>s (Shamt-XLEN); 4082 // Hi = Hi >>s (XLEN-1) 4083 // 4084 // SRL expansion: 4085 // if Shamt-XLEN < 0: // Shamt < XLEN 4086 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4087 // Hi = Hi >>u Shamt 4088 // else: 4089 // Lo = Hi >>u (Shamt-XLEN); 4090 // Hi = 0; 4091 4092 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 4093 4094 SDValue Zero = DAG.getConstant(0, DL, VT); 4095 SDValue One = DAG.getConstant(1, DL, VT); 4096 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4097 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4098 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4099 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4100 4101 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 4102 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 4103 SDValue ShiftLeftHi = 4104 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 4105 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 4106 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 4107 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 4108 SDValue HiFalse = 4109 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 4110 4111 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4112 4113 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 4114 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4115 4116 SDValue Parts[2] = {Lo, Hi}; 4117 return DAG.getMergeValues(Parts, DL); 4118 } 4119 4120 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 4121 // legal equivalently-sized i8 type, so we can use that as a go-between. 4122 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4123 SelectionDAG &DAG) const { 4124 SDLoc DL(Op); 4125 MVT VT = Op.getSimpleValueType(); 4126 SDValue SplatVal = Op.getOperand(0); 4127 // All-zeros or all-ones splats are handled specially. 4128 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4129 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4130 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4131 } 4132 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4133 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4134 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4135 } 4136 MVT XLenVT = Subtarget.getXLenVT(); 4137 assert(SplatVal.getValueType() == XLenVT && 4138 "Unexpected type for i1 splat value"); 4139 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4140 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4141 DAG.getConstant(1, DL, XLenVT)); 4142 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4143 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4144 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4145 } 4146 4147 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4148 // illegal (currently only vXi64 RV32). 4149 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4150 // them to VMV_V_X_VL. 4151 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4152 SelectionDAG &DAG) const { 4153 SDLoc DL(Op); 4154 MVT VecVT = Op.getSimpleValueType(); 4155 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4156 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4157 4158 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4159 SDValue Lo = Op.getOperand(0); 4160 SDValue Hi = Op.getOperand(1); 4161 4162 if (VecVT.isFixedLengthVector()) { 4163 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4164 SDLoc DL(Op); 4165 SDValue Mask, VL; 4166 std::tie(Mask, VL) = 4167 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4168 4169 SDValue Res = 4170 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4171 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4172 } 4173 4174 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4175 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4176 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4177 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4178 // node in order to try and match RVV vector/scalar instructions. 4179 if ((LoC >> 31) == HiC) 4180 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4181 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4182 } 4183 4184 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4185 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4186 isa<ConstantSDNode>(Hi.getOperand(1)) && 4187 Hi.getConstantOperandVal(1) == 31) 4188 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4189 DAG.getRegister(RISCV::X0, MVT::i32)); 4190 4191 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4192 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4193 DAG.getUNDEF(VecVT), Lo, Hi, 4194 DAG.getRegister(RISCV::X0, MVT::i32)); 4195 } 4196 4197 // Custom-lower extensions from mask vectors by using a vselect either with 1 4198 // for zero/any-extension or -1 for sign-extension: 4199 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4200 // Note that any-extension is lowered identically to zero-extension. 4201 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4202 int64_t ExtTrueVal) const { 4203 SDLoc DL(Op); 4204 MVT VecVT = Op.getSimpleValueType(); 4205 SDValue Src = Op.getOperand(0); 4206 // Only custom-lower extensions from mask types 4207 assert(Src.getValueType().isVector() && 4208 Src.getValueType().getVectorElementType() == MVT::i1); 4209 4210 if (VecVT.isScalableVector()) { 4211 SDValue SplatZero = DAG.getConstant(0, DL, VecVT); 4212 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT); 4213 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4214 } 4215 4216 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4217 MVT I1ContainerVT = 4218 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4219 4220 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4221 4222 SDValue Mask, VL; 4223 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4224 4225 MVT XLenVT = Subtarget.getXLenVT(); 4226 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4227 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4228 4229 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4230 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4231 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4232 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4233 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4234 SplatTrueVal, SplatZero, VL); 4235 4236 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4237 } 4238 4239 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4240 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4241 MVT ExtVT = Op.getSimpleValueType(); 4242 // Only custom-lower extensions from fixed-length vector types. 4243 if (!ExtVT.isFixedLengthVector()) 4244 return Op; 4245 MVT VT = Op.getOperand(0).getSimpleValueType(); 4246 // Grab the canonical container type for the extended type. Infer the smaller 4247 // type from that to ensure the same number of vector elements, as we know 4248 // the LMUL will be sufficient to hold the smaller type. 4249 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4250 // Get the extended container type manually to ensure the same number of 4251 // vector elements between source and dest. 4252 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4253 ContainerExtVT.getVectorElementCount()); 4254 4255 SDValue Op1 = 4256 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4257 4258 SDLoc DL(Op); 4259 SDValue Mask, VL; 4260 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4261 4262 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4263 4264 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4265 } 4266 4267 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4268 // setcc operation: 4269 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4270 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op, 4271 SelectionDAG &DAG) const { 4272 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4273 SDLoc DL(Op); 4274 EVT MaskVT = Op.getValueType(); 4275 // Only expect to custom-lower truncations to mask types 4276 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4277 "Unexpected type for vector mask lowering"); 4278 SDValue Src = Op.getOperand(0); 4279 MVT VecVT = Src.getSimpleValueType(); 4280 SDValue Mask, VL; 4281 if (IsVPTrunc) { 4282 Mask = Op.getOperand(1); 4283 VL = Op.getOperand(2); 4284 } 4285 // If this is a fixed vector, we need to convert it to a scalable vector. 4286 MVT ContainerVT = VecVT; 4287 4288 if (VecVT.isFixedLengthVector()) { 4289 ContainerVT = getContainerForFixedLengthVector(VecVT); 4290 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4291 if (IsVPTrunc) { 4292 MVT MaskContainerVT = 4293 getContainerForFixedLengthVector(Mask.getSimpleValueType()); 4294 Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget); 4295 } 4296 } 4297 4298 if (!IsVPTrunc) { 4299 std::tie(Mask, VL) = 4300 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4301 } 4302 4303 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4304 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4305 4306 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4307 DAG.getUNDEF(ContainerVT), SplatOne, VL); 4308 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4309 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4310 4311 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4312 SDValue Trunc = 4313 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4314 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4315 DAG.getCondCode(ISD::SETNE), Mask, VL); 4316 if (MaskVT.isFixedLengthVector()) 4317 Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4318 return Trunc; 4319 } 4320 4321 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op, 4322 SelectionDAG &DAG) const { 4323 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4324 SDLoc DL(Op); 4325 4326 MVT VT = Op.getSimpleValueType(); 4327 // Only custom-lower vector truncates 4328 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4329 4330 // Truncates to mask types are handled differently 4331 if (VT.getVectorElementType() == MVT::i1) 4332 return lowerVectorMaskTruncLike(Op, DAG); 4333 4334 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 4335 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 4336 // truncate by one power of two at a time. 4337 MVT DstEltVT = VT.getVectorElementType(); 4338 4339 SDValue Src = Op.getOperand(0); 4340 MVT SrcVT = Src.getSimpleValueType(); 4341 MVT SrcEltVT = SrcVT.getVectorElementType(); 4342 4343 assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) && 4344 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 4345 "Unexpected vector truncate lowering"); 4346 4347 MVT ContainerVT = SrcVT; 4348 SDValue Mask, VL; 4349 if (IsVPTrunc) { 4350 Mask = Op.getOperand(1); 4351 VL = Op.getOperand(2); 4352 } 4353 if (SrcVT.isFixedLengthVector()) { 4354 ContainerVT = getContainerForFixedLengthVector(SrcVT); 4355 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4356 if (IsVPTrunc) { 4357 MVT MaskVT = getMaskTypeFor(ContainerVT); 4358 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4359 } 4360 } 4361 4362 SDValue Result = Src; 4363 if (!IsVPTrunc) { 4364 std::tie(Mask, VL) = 4365 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4366 } 4367 4368 LLVMContext &Context = *DAG.getContext(); 4369 const ElementCount Count = ContainerVT.getVectorElementCount(); 4370 do { 4371 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 4372 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 4373 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 4374 Mask, VL); 4375 } while (SrcEltVT != DstEltVT); 4376 4377 if (SrcVT.isFixedLengthVector()) 4378 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4379 4380 return Result; 4381 } 4382 4383 SDValue 4384 RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op, 4385 SelectionDAG &DAG) const { 4386 bool IsVP = 4387 Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND; 4388 bool IsExtend = 4389 Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND; 4390 // RVV can only do truncate fp to types half the size as the source. We 4391 // custom-lower f64->f16 rounds via RVV's round-to-odd float 4392 // conversion instruction. 4393 SDLoc DL(Op); 4394 MVT VT = Op.getSimpleValueType(); 4395 4396 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4397 4398 SDValue Src = Op.getOperand(0); 4399 MVT SrcVT = Src.getSimpleValueType(); 4400 4401 bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 || 4402 SrcVT.getVectorElementType() != MVT::f16); 4403 bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 || 4404 SrcVT.getVectorElementType() != MVT::f64); 4405 4406 bool IsDirectConv = IsDirectExtend || IsDirectTrunc; 4407 4408 // Prepare any fixed-length vector operands. 4409 MVT ContainerVT = VT; 4410 SDValue Mask, VL; 4411 if (IsVP) { 4412 Mask = Op.getOperand(1); 4413 VL = Op.getOperand(2); 4414 } 4415 if (VT.isFixedLengthVector()) { 4416 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 4417 ContainerVT = 4418 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 4419 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 4420 if (IsVP) { 4421 MVT MaskVT = getMaskTypeFor(ContainerVT); 4422 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4423 } 4424 } 4425 4426 if (!IsVP) 4427 std::tie(Mask, VL) = 4428 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4429 4430 unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL; 4431 4432 if (IsDirectConv) { 4433 Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL); 4434 if (VT.isFixedLengthVector()) 4435 Src = convertFromScalableVector(VT, Src, DAG, Subtarget); 4436 return Src; 4437 } 4438 4439 unsigned InterConvOpc = 4440 IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL; 4441 4442 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 4443 SDValue IntermediateConv = 4444 DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL); 4445 SDValue Result = 4446 DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL); 4447 if (VT.isFixedLengthVector()) 4448 return convertFromScalableVector(VT, Result, DAG, Subtarget); 4449 return Result; 4450 } 4451 4452 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4453 // first position of a vector, and that vector is slid up to the insert index. 4454 // By limiting the active vector length to index+1 and merging with the 4455 // original vector (with an undisturbed tail policy for elements >= VL), we 4456 // achieve the desired result of leaving all elements untouched except the one 4457 // at VL-1, which is replaced with the desired value. 4458 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4459 SelectionDAG &DAG) const { 4460 SDLoc DL(Op); 4461 MVT VecVT = Op.getSimpleValueType(); 4462 SDValue Vec = Op.getOperand(0); 4463 SDValue Val = Op.getOperand(1); 4464 SDValue Idx = Op.getOperand(2); 4465 4466 if (VecVT.getVectorElementType() == MVT::i1) { 4467 // FIXME: For now we just promote to an i8 vector and insert into that, 4468 // but this is probably not optimal. 4469 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4470 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4471 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4472 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4473 } 4474 4475 MVT ContainerVT = VecVT; 4476 // If the operand is a fixed-length vector, convert to a scalable one. 4477 if (VecVT.isFixedLengthVector()) { 4478 ContainerVT = getContainerForFixedLengthVector(VecVT); 4479 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4480 } 4481 4482 MVT XLenVT = Subtarget.getXLenVT(); 4483 4484 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4485 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4486 // Even i64-element vectors on RV32 can be lowered without scalar 4487 // legalization if the most-significant 32 bits of the value are not affected 4488 // by the sign-extension of the lower 32 bits. 4489 // TODO: We could also catch sign extensions of a 32-bit value. 4490 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4491 const auto *CVal = cast<ConstantSDNode>(Val); 4492 if (isInt<32>(CVal->getSExtValue())) { 4493 IsLegalInsert = true; 4494 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4495 } 4496 } 4497 4498 SDValue Mask, VL; 4499 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4500 4501 SDValue ValInVec; 4502 4503 if (IsLegalInsert) { 4504 unsigned Opc = 4505 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4506 if (isNullConstant(Idx)) { 4507 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4508 if (!VecVT.isFixedLengthVector()) 4509 return Vec; 4510 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4511 } 4512 ValInVec = 4513 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4514 } else { 4515 // On RV32, i64-element vectors must be specially handled to place the 4516 // value at element 0, by using two vslide1up instructions in sequence on 4517 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4518 // this. 4519 SDValue One = DAG.getConstant(1, DL, XLenVT); 4520 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4521 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4522 MVT I32ContainerVT = 4523 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4524 SDValue I32Mask = 4525 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4526 // Limit the active VL to two. 4527 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4528 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4529 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4530 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4531 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4532 // First slide in the hi value, then the lo in underneath it. 4533 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4534 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4535 I32Mask, InsertI64VL); 4536 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4537 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4538 I32Mask, InsertI64VL); 4539 // Bitcast back to the right container type. 4540 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4541 } 4542 4543 // Now that the value is in a vector, slide it into position. 4544 SDValue InsertVL = 4545 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4546 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4547 ValInVec, Idx, Mask, InsertVL); 4548 if (!VecVT.isFixedLengthVector()) 4549 return Slideup; 4550 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4551 } 4552 4553 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4554 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4555 // types this is done using VMV_X_S to allow us to glean information about the 4556 // sign bits of the result. 4557 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4558 SelectionDAG &DAG) const { 4559 SDLoc DL(Op); 4560 SDValue Idx = Op.getOperand(1); 4561 SDValue Vec = Op.getOperand(0); 4562 EVT EltVT = Op.getValueType(); 4563 MVT VecVT = Vec.getSimpleValueType(); 4564 MVT XLenVT = Subtarget.getXLenVT(); 4565 4566 if (VecVT.getVectorElementType() == MVT::i1) { 4567 if (VecVT.isFixedLengthVector()) { 4568 unsigned NumElts = VecVT.getVectorNumElements(); 4569 if (NumElts >= 8) { 4570 MVT WideEltVT; 4571 unsigned WidenVecLen; 4572 SDValue ExtractElementIdx; 4573 SDValue ExtractBitIdx; 4574 unsigned MaxEEW = Subtarget.getELEN(); 4575 MVT LargestEltVT = MVT::getIntegerVT( 4576 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4577 if (NumElts <= LargestEltVT.getSizeInBits()) { 4578 assert(isPowerOf2_32(NumElts) && 4579 "the number of elements should be power of 2"); 4580 WideEltVT = MVT::getIntegerVT(NumElts); 4581 WidenVecLen = 1; 4582 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4583 ExtractBitIdx = Idx; 4584 } else { 4585 WideEltVT = LargestEltVT; 4586 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4587 // extract element index = index / element width 4588 ExtractElementIdx = DAG.getNode( 4589 ISD::SRL, DL, XLenVT, Idx, 4590 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4591 // mask bit index = index % element width 4592 ExtractBitIdx = DAG.getNode( 4593 ISD::AND, DL, XLenVT, Idx, 4594 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4595 } 4596 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4597 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4598 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4599 Vec, ExtractElementIdx); 4600 // Extract the bit from GPR. 4601 SDValue ShiftRight = 4602 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4603 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4604 DAG.getConstant(1, DL, XLenVT)); 4605 } 4606 } 4607 // Otherwise, promote to an i8 vector and extract from that. 4608 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4609 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4610 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4611 } 4612 4613 // If this is a fixed vector, we need to convert it to a scalable vector. 4614 MVT ContainerVT = VecVT; 4615 if (VecVT.isFixedLengthVector()) { 4616 ContainerVT = getContainerForFixedLengthVector(VecVT); 4617 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4618 } 4619 4620 // If the index is 0, the vector is already in the right position. 4621 if (!isNullConstant(Idx)) { 4622 // Use a VL of 1 to avoid processing more elements than we need. 4623 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4624 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 4625 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4626 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4627 } 4628 4629 if (!EltVT.isInteger()) { 4630 // Floating-point extracts are handled in TableGen. 4631 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4632 DAG.getConstant(0, DL, XLenVT)); 4633 } 4634 4635 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4636 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4637 } 4638 4639 // Some RVV intrinsics may claim that they want an integer operand to be 4640 // promoted or expanded. 4641 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG, 4642 const RISCVSubtarget &Subtarget) { 4643 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4644 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4645 "Unexpected opcode"); 4646 4647 if (!Subtarget.hasVInstructions()) 4648 return SDValue(); 4649 4650 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4651 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4652 SDLoc DL(Op); 4653 4654 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4655 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4656 if (!II || !II->hasScalarOperand()) 4657 return SDValue(); 4658 4659 unsigned SplatOp = II->ScalarOperand + 1 + HasChain; 4660 assert(SplatOp < Op.getNumOperands()); 4661 4662 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4663 SDValue &ScalarOp = Operands[SplatOp]; 4664 MVT OpVT = ScalarOp.getSimpleValueType(); 4665 MVT XLenVT = Subtarget.getXLenVT(); 4666 4667 // If this isn't a scalar, or its type is XLenVT we're done. 4668 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4669 return SDValue(); 4670 4671 // Simplest case is that the operand needs to be promoted to XLenVT. 4672 if (OpVT.bitsLT(XLenVT)) { 4673 // If the operand is a constant, sign extend to increase our chances 4674 // of being able to use a .vi instruction. ANY_EXTEND would become a 4675 // a zero extend and the simm5 check in isel would fail. 4676 // FIXME: Should we ignore the upper bits in isel instead? 4677 unsigned ExtOpc = 4678 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4679 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4680 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4681 } 4682 4683 // Use the previous operand to get the vXi64 VT. The result might be a mask 4684 // VT for compares. Using the previous operand assumes that the previous 4685 // operand will never have a smaller element size than a scalar operand and 4686 // that a widening operation never uses SEW=64. 4687 // NOTE: If this fails the below assert, we can probably just find the 4688 // element count from any operand or result and use it to construct the VT. 4689 assert(II->ScalarOperand > 0 && "Unexpected splat operand!"); 4690 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4691 4692 // The more complex case is when the scalar is larger than XLenVT. 4693 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4694 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4695 4696 // If this is a sign-extended 32-bit value, we can truncate it and rely on the 4697 // instruction to sign-extend since SEW>XLEN. 4698 if (DAG.ComputeNumSignBits(ScalarOp) > 32) { 4699 ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp); 4700 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4701 } 4702 4703 switch (IntNo) { 4704 case Intrinsic::riscv_vslide1up: 4705 case Intrinsic::riscv_vslide1down: 4706 case Intrinsic::riscv_vslide1up_mask: 4707 case Intrinsic::riscv_vslide1down_mask: { 4708 // We need to special case these when the scalar is larger than XLen. 4709 unsigned NumOps = Op.getNumOperands(); 4710 bool IsMasked = NumOps == 7; 4711 4712 // Convert the vector source to the equivalent nxvXi32 vector. 4713 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4714 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4715 4716 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4717 DAG.getConstant(0, DL, XLenVT)); 4718 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4719 DAG.getConstant(1, DL, XLenVT)); 4720 4721 // Double the VL since we halved SEW. 4722 SDValue AVL = getVLOperand(Op); 4723 SDValue I32VL; 4724 4725 // Optimize for constant AVL 4726 if (isa<ConstantSDNode>(AVL)) { 4727 unsigned EltSize = VT.getScalarSizeInBits(); 4728 unsigned MinSize = VT.getSizeInBits().getKnownMinValue(); 4729 4730 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 4731 unsigned MaxVLMAX = 4732 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 4733 4734 unsigned VectorBitsMin = Subtarget.getRealMinVLen(); 4735 unsigned MinVLMAX = 4736 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize); 4737 4738 uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue(); 4739 if (AVLInt <= MinVLMAX) { 4740 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT); 4741 } else if (AVLInt >= 2 * MaxVLMAX) { 4742 // Just set vl to VLMAX in this situation 4743 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT); 4744 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4745 unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits()); 4746 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4747 SDValue SETVLMAX = DAG.getTargetConstant( 4748 Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32); 4749 I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW, 4750 LMUL); 4751 } else { 4752 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl 4753 // is related to the hardware implementation. 4754 // So let the following code handle 4755 } 4756 } 4757 if (!I32VL) { 4758 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT); 4759 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4760 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits()); 4761 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4762 SDValue SETVL = 4763 DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32); 4764 // Using vsetvli instruction to get actually used length which related to 4765 // the hardware implementation 4766 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL, 4767 SEW, LMUL); 4768 I32VL = 4769 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4770 } 4771 4772 SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG); 4773 4774 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4775 // instructions. 4776 SDValue Passthru; 4777 if (IsMasked) 4778 Passthru = DAG.getUNDEF(I32VT); 4779 else 4780 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4781 4782 if (IntNo == Intrinsic::riscv_vslide1up || 4783 IntNo == Intrinsic::riscv_vslide1up_mask) { 4784 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4785 ScalarHi, I32Mask, I32VL); 4786 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4787 ScalarLo, I32Mask, I32VL); 4788 } else { 4789 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4790 ScalarLo, I32Mask, I32VL); 4791 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4792 ScalarHi, I32Mask, I32VL); 4793 } 4794 4795 // Convert back to nxvXi64. 4796 Vec = DAG.getBitcast(VT, Vec); 4797 4798 if (!IsMasked) 4799 return Vec; 4800 // Apply mask after the operation. 4801 SDValue Mask = Operands[NumOps - 3]; 4802 SDValue MaskedOff = Operands[1]; 4803 // Assume Policy operand is the last operand. 4804 uint64_t Policy = 4805 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4806 // We don't need to select maskedoff if it's undef. 4807 if (MaskedOff.isUndef()) 4808 return Vec; 4809 // TAMU 4810 if (Policy == RISCVII::TAIL_AGNOSTIC) 4811 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4812 AVL); 4813 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4814 // It's fine because vmerge does not care mask policy. 4815 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, 4816 AVL); 4817 } 4818 } 4819 4820 // We need to convert the scalar to a splat vector. 4821 SDValue VL = getVLOperand(Op); 4822 assert(VL.getValueType() == XLenVT); 4823 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4824 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4825 } 4826 4827 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4828 SelectionDAG &DAG) const { 4829 unsigned IntNo = Op.getConstantOperandVal(0); 4830 SDLoc DL(Op); 4831 MVT XLenVT = Subtarget.getXLenVT(); 4832 4833 switch (IntNo) { 4834 default: 4835 break; // Don't custom lower most intrinsics. 4836 case Intrinsic::thread_pointer: { 4837 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4838 return DAG.getRegister(RISCV::X4, PtrVT); 4839 } 4840 case Intrinsic::riscv_orc_b: 4841 case Intrinsic::riscv_brev8: { 4842 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4843 unsigned Opc = 4844 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4845 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4846 DAG.getConstant(7, DL, XLenVT)); 4847 } 4848 case Intrinsic::riscv_grev: 4849 case Intrinsic::riscv_gorc: { 4850 unsigned Opc = 4851 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4852 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4853 } 4854 case Intrinsic::riscv_zip: 4855 case Intrinsic::riscv_unzip: { 4856 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4857 // For i32 the immediate is 15. For i64 the immediate is 31. 4858 unsigned Opc = 4859 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4860 unsigned BitWidth = Op.getValueSizeInBits(); 4861 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4862 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4863 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4864 } 4865 case Intrinsic::riscv_shfl: 4866 case Intrinsic::riscv_unshfl: { 4867 unsigned Opc = 4868 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4869 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4870 } 4871 case Intrinsic::riscv_bcompress: 4872 case Intrinsic::riscv_bdecompress: { 4873 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4874 : RISCVISD::BDECOMPRESS; 4875 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4876 } 4877 case Intrinsic::riscv_bfp: 4878 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4879 Op.getOperand(2)); 4880 case Intrinsic::riscv_fsl: 4881 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4882 Op.getOperand(2), Op.getOperand(3)); 4883 case Intrinsic::riscv_fsr: 4884 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4885 Op.getOperand(2), Op.getOperand(3)); 4886 case Intrinsic::riscv_vmv_x_s: 4887 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4888 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4889 Op.getOperand(1)); 4890 case Intrinsic::riscv_vmv_v_x: 4891 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4892 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4893 Subtarget); 4894 case Intrinsic::riscv_vfmv_v_f: 4895 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4896 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4897 case Intrinsic::riscv_vmv_s_x: { 4898 SDValue Scalar = Op.getOperand(2); 4899 4900 if (Scalar.getValueType().bitsLE(XLenVT)) { 4901 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4902 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4903 Op.getOperand(1), Scalar, Op.getOperand(3)); 4904 } 4905 4906 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4907 4908 // This is an i64 value that lives in two scalar registers. We have to 4909 // insert this in a convoluted way. First we build vXi64 splat containing 4910 // the two values that we assemble using some bit math. Next we'll use 4911 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4912 // to merge element 0 from our splat into the source vector. 4913 // FIXME: This is probably not the best way to do this, but it is 4914 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4915 // point. 4916 // sw lo, (a0) 4917 // sw hi, 4(a0) 4918 // vlse vX, (a0) 4919 // 4920 // vid.v vVid 4921 // vmseq.vx mMask, vVid, 0 4922 // vmerge.vvm vDest, vSrc, vVal, mMask 4923 MVT VT = Op.getSimpleValueType(); 4924 SDValue Vec = Op.getOperand(1); 4925 SDValue VL = getVLOperand(Op); 4926 4927 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4928 if (Op.getOperand(1).isUndef()) 4929 return SplattedVal; 4930 SDValue SplattedIdx = 4931 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4932 DAG.getConstant(0, DL, MVT::i32), VL); 4933 4934 MVT MaskVT = getMaskTypeFor(VT); 4935 SDValue Mask = getAllOnesMask(VT, VL, DL, DAG); 4936 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4937 SDValue SelectCond = 4938 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4939 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4940 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4941 Vec, VL); 4942 } 4943 } 4944 4945 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4946 } 4947 4948 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4949 SelectionDAG &DAG) const { 4950 unsigned IntNo = Op.getConstantOperandVal(1); 4951 switch (IntNo) { 4952 default: 4953 break; 4954 case Intrinsic::riscv_masked_strided_load: { 4955 SDLoc DL(Op); 4956 MVT XLenVT = Subtarget.getXLenVT(); 4957 4958 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4959 // the selection of the masked intrinsics doesn't do this for us. 4960 SDValue Mask = Op.getOperand(5); 4961 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4962 4963 MVT VT = Op->getSimpleValueType(0); 4964 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4965 4966 SDValue PassThru = Op.getOperand(2); 4967 if (!IsUnmasked) { 4968 MVT MaskVT = getMaskTypeFor(ContainerVT); 4969 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4970 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4971 } 4972 4973 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4974 4975 SDValue IntID = DAG.getTargetConstant( 4976 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4977 XLenVT); 4978 4979 auto *Load = cast<MemIntrinsicSDNode>(Op); 4980 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4981 if (IsUnmasked) 4982 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4983 else 4984 Ops.push_back(PassThru); 4985 Ops.push_back(Op.getOperand(3)); // Ptr 4986 Ops.push_back(Op.getOperand(4)); // Stride 4987 if (!IsUnmasked) 4988 Ops.push_back(Mask); 4989 Ops.push_back(VL); 4990 if (!IsUnmasked) { 4991 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4992 Ops.push_back(Policy); 4993 } 4994 4995 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4996 SDValue Result = 4997 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4998 Load->getMemoryVT(), Load->getMemOperand()); 4999 SDValue Chain = Result.getValue(1); 5000 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5001 return DAG.getMergeValues({Result, Chain}, DL); 5002 } 5003 case Intrinsic::riscv_seg2_load: 5004 case Intrinsic::riscv_seg3_load: 5005 case Intrinsic::riscv_seg4_load: 5006 case Intrinsic::riscv_seg5_load: 5007 case Intrinsic::riscv_seg6_load: 5008 case Intrinsic::riscv_seg7_load: 5009 case Intrinsic::riscv_seg8_load: { 5010 SDLoc DL(Op); 5011 static const Intrinsic::ID VlsegInts[7] = { 5012 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 5013 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 5014 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 5015 Intrinsic::riscv_vlseg8}; 5016 unsigned NF = Op->getNumValues() - 1; 5017 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 5018 MVT XLenVT = Subtarget.getXLenVT(); 5019 MVT VT = Op->getSimpleValueType(0); 5020 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5021 5022 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5023 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 5024 auto *Load = cast<MemIntrinsicSDNode>(Op); 5025 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 5026 ContainerVTs.push_back(MVT::Other); 5027 SDVTList VTs = DAG.getVTList(ContainerVTs); 5028 SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID}; 5029 Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT)); 5030 Ops.push_back(Op.getOperand(2)); 5031 Ops.push_back(VL); 5032 SDValue Result = 5033 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5034 Load->getMemoryVT(), Load->getMemOperand()); 5035 SmallVector<SDValue, 9> Results; 5036 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 5037 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 5038 DAG, Subtarget)); 5039 Results.push_back(Result.getValue(NF)); 5040 return DAG.getMergeValues(Results, DL); 5041 } 5042 } 5043 5044 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 5045 } 5046 5047 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 5048 SelectionDAG &DAG) const { 5049 unsigned IntNo = Op.getConstantOperandVal(1); 5050 switch (IntNo) { 5051 default: 5052 break; 5053 case Intrinsic::riscv_masked_strided_store: { 5054 SDLoc DL(Op); 5055 MVT XLenVT = Subtarget.getXLenVT(); 5056 5057 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5058 // the selection of the masked intrinsics doesn't do this for us. 5059 SDValue Mask = Op.getOperand(5); 5060 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5061 5062 SDValue Val = Op.getOperand(2); 5063 MVT VT = Val.getSimpleValueType(); 5064 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5065 5066 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5067 if (!IsUnmasked) { 5068 MVT MaskVT = getMaskTypeFor(ContainerVT); 5069 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5070 } 5071 5072 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5073 5074 SDValue IntID = DAG.getTargetConstant( 5075 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 5076 XLenVT); 5077 5078 auto *Store = cast<MemIntrinsicSDNode>(Op); 5079 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 5080 Ops.push_back(Val); 5081 Ops.push_back(Op.getOperand(3)); // Ptr 5082 Ops.push_back(Op.getOperand(4)); // Stride 5083 if (!IsUnmasked) 5084 Ops.push_back(Mask); 5085 Ops.push_back(VL); 5086 5087 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 5088 Ops, Store->getMemoryVT(), 5089 Store->getMemOperand()); 5090 } 5091 } 5092 5093 return SDValue(); 5094 } 5095 5096 static MVT getLMUL1VT(MVT VT) { 5097 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 5098 "Unexpected vector MVT"); 5099 return MVT::getScalableVectorVT( 5100 VT.getVectorElementType(), 5101 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 5102 } 5103 5104 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 5105 switch (ISDOpcode) { 5106 default: 5107 llvm_unreachable("Unhandled reduction"); 5108 case ISD::VECREDUCE_ADD: 5109 return RISCVISD::VECREDUCE_ADD_VL; 5110 case ISD::VECREDUCE_UMAX: 5111 return RISCVISD::VECREDUCE_UMAX_VL; 5112 case ISD::VECREDUCE_SMAX: 5113 return RISCVISD::VECREDUCE_SMAX_VL; 5114 case ISD::VECREDUCE_UMIN: 5115 return RISCVISD::VECREDUCE_UMIN_VL; 5116 case ISD::VECREDUCE_SMIN: 5117 return RISCVISD::VECREDUCE_SMIN_VL; 5118 case ISD::VECREDUCE_AND: 5119 return RISCVISD::VECREDUCE_AND_VL; 5120 case ISD::VECREDUCE_OR: 5121 return RISCVISD::VECREDUCE_OR_VL; 5122 case ISD::VECREDUCE_XOR: 5123 return RISCVISD::VECREDUCE_XOR_VL; 5124 } 5125 } 5126 5127 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 5128 SelectionDAG &DAG, 5129 bool IsVP) const { 5130 SDLoc DL(Op); 5131 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 5132 MVT VecVT = Vec.getSimpleValueType(); 5133 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 5134 Op.getOpcode() == ISD::VECREDUCE_OR || 5135 Op.getOpcode() == ISD::VECREDUCE_XOR || 5136 Op.getOpcode() == ISD::VP_REDUCE_AND || 5137 Op.getOpcode() == ISD::VP_REDUCE_OR || 5138 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5139 "Unexpected reduction lowering"); 5140 5141 MVT XLenVT = Subtarget.getXLenVT(); 5142 assert(Op.getValueType() == XLenVT && 5143 "Expected reduction output to be legalized to XLenVT"); 5144 5145 MVT ContainerVT = VecVT; 5146 if (VecVT.isFixedLengthVector()) { 5147 ContainerVT = getContainerForFixedLengthVector(VecVT); 5148 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5149 } 5150 5151 SDValue Mask, VL; 5152 if (IsVP) { 5153 Mask = Op.getOperand(2); 5154 VL = Op.getOperand(3); 5155 } else { 5156 std::tie(Mask, VL) = 5157 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5158 } 5159 5160 unsigned BaseOpc; 5161 ISD::CondCode CC; 5162 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5163 5164 switch (Op.getOpcode()) { 5165 default: 5166 llvm_unreachable("Unhandled reduction"); 5167 case ISD::VECREDUCE_AND: 5168 case ISD::VP_REDUCE_AND: { 5169 // vcpop ~x == 0 5170 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5171 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5172 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5173 CC = ISD::SETEQ; 5174 BaseOpc = ISD::AND; 5175 break; 5176 } 5177 case ISD::VECREDUCE_OR: 5178 case ISD::VP_REDUCE_OR: 5179 // vcpop x != 0 5180 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5181 CC = ISD::SETNE; 5182 BaseOpc = ISD::OR; 5183 break; 5184 case ISD::VECREDUCE_XOR: 5185 case ISD::VP_REDUCE_XOR: { 5186 // ((vcpop x) & 1) != 0 5187 SDValue One = DAG.getConstant(1, DL, XLenVT); 5188 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5189 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5190 CC = ISD::SETNE; 5191 BaseOpc = ISD::XOR; 5192 break; 5193 } 5194 } 5195 5196 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5197 5198 if (!IsVP) 5199 return SetCC; 5200 5201 // Now include the start value in the operation. 5202 // Note that we must return the start value when no elements are operated 5203 // upon. The vcpop instructions we've emitted in each case above will return 5204 // 0 for an inactive vector, and so we've already received the neutral value: 5205 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5206 // can simply include the start value. 5207 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5208 } 5209 5210 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5211 SelectionDAG &DAG) const { 5212 SDLoc DL(Op); 5213 SDValue Vec = Op.getOperand(0); 5214 EVT VecEVT = Vec.getValueType(); 5215 5216 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5217 5218 // Due to ordering in legalize types we may have a vector type that needs to 5219 // be split. Do that manually so we can get down to a legal type. 5220 while (getTypeAction(*DAG.getContext(), VecEVT) == 5221 TargetLowering::TypeSplitVector) { 5222 SDValue Lo, Hi; 5223 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5224 VecEVT = Lo.getValueType(); 5225 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5226 } 5227 5228 // TODO: The type may need to be widened rather than split. Or widened before 5229 // it can be split. 5230 if (!isTypeLegal(VecEVT)) 5231 return SDValue(); 5232 5233 MVT VecVT = VecEVT.getSimpleVT(); 5234 MVT VecEltVT = VecVT.getVectorElementType(); 5235 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5236 5237 MVT ContainerVT = VecVT; 5238 if (VecVT.isFixedLengthVector()) { 5239 ContainerVT = getContainerForFixedLengthVector(VecVT); 5240 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5241 } 5242 5243 MVT M1VT = getLMUL1VT(ContainerVT); 5244 MVT XLenVT = Subtarget.getXLenVT(); 5245 5246 SDValue Mask, VL; 5247 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5248 5249 SDValue NeutralElem = 5250 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5251 SDValue IdentitySplat = 5252 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5253 M1VT, DL, DAG, Subtarget); 5254 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5255 IdentitySplat, Mask, VL); 5256 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5257 DAG.getConstant(0, DL, XLenVT)); 5258 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5259 } 5260 5261 // Given a reduction op, this function returns the matching reduction opcode, 5262 // the vector SDValue and the scalar SDValue required to lower this to a 5263 // RISCVISD node. 5264 static std::tuple<unsigned, SDValue, SDValue> 5265 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5266 SDLoc DL(Op); 5267 auto Flags = Op->getFlags(); 5268 unsigned Opcode = Op.getOpcode(); 5269 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5270 switch (Opcode) { 5271 default: 5272 llvm_unreachable("Unhandled reduction"); 5273 case ISD::VECREDUCE_FADD: { 5274 // Use positive zero if we can. It is cheaper to materialize. 5275 SDValue Zero = 5276 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5277 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5278 } 5279 case ISD::VECREDUCE_SEQ_FADD: 5280 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5281 Op.getOperand(0)); 5282 case ISD::VECREDUCE_FMIN: 5283 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5284 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5285 case ISD::VECREDUCE_FMAX: 5286 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5287 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5288 } 5289 } 5290 5291 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5292 SelectionDAG &DAG) const { 5293 SDLoc DL(Op); 5294 MVT VecEltVT = Op.getSimpleValueType(); 5295 5296 unsigned RVVOpcode; 5297 SDValue VectorVal, ScalarVal; 5298 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5299 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5300 MVT VecVT = VectorVal.getSimpleValueType(); 5301 5302 MVT ContainerVT = VecVT; 5303 if (VecVT.isFixedLengthVector()) { 5304 ContainerVT = getContainerForFixedLengthVector(VecVT); 5305 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5306 } 5307 5308 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5309 MVT XLenVT = Subtarget.getXLenVT(); 5310 5311 SDValue Mask, VL; 5312 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5313 5314 SDValue ScalarSplat = 5315 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5316 M1VT, DL, DAG, Subtarget); 5317 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5318 VectorVal, ScalarSplat, Mask, VL); 5319 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5320 DAG.getConstant(0, DL, XLenVT)); 5321 } 5322 5323 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5324 switch (ISDOpcode) { 5325 default: 5326 llvm_unreachable("Unhandled reduction"); 5327 case ISD::VP_REDUCE_ADD: 5328 return RISCVISD::VECREDUCE_ADD_VL; 5329 case ISD::VP_REDUCE_UMAX: 5330 return RISCVISD::VECREDUCE_UMAX_VL; 5331 case ISD::VP_REDUCE_SMAX: 5332 return RISCVISD::VECREDUCE_SMAX_VL; 5333 case ISD::VP_REDUCE_UMIN: 5334 return RISCVISD::VECREDUCE_UMIN_VL; 5335 case ISD::VP_REDUCE_SMIN: 5336 return RISCVISD::VECREDUCE_SMIN_VL; 5337 case ISD::VP_REDUCE_AND: 5338 return RISCVISD::VECREDUCE_AND_VL; 5339 case ISD::VP_REDUCE_OR: 5340 return RISCVISD::VECREDUCE_OR_VL; 5341 case ISD::VP_REDUCE_XOR: 5342 return RISCVISD::VECREDUCE_XOR_VL; 5343 case ISD::VP_REDUCE_FADD: 5344 return RISCVISD::VECREDUCE_FADD_VL; 5345 case ISD::VP_REDUCE_SEQ_FADD: 5346 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5347 case ISD::VP_REDUCE_FMAX: 5348 return RISCVISD::VECREDUCE_FMAX_VL; 5349 case ISD::VP_REDUCE_FMIN: 5350 return RISCVISD::VECREDUCE_FMIN_VL; 5351 } 5352 } 5353 5354 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5355 SelectionDAG &DAG) const { 5356 SDLoc DL(Op); 5357 SDValue Vec = Op.getOperand(1); 5358 EVT VecEVT = Vec.getValueType(); 5359 5360 // TODO: The type may need to be widened rather than split. Or widened before 5361 // it can be split. 5362 if (!isTypeLegal(VecEVT)) 5363 return SDValue(); 5364 5365 MVT VecVT = VecEVT.getSimpleVT(); 5366 MVT VecEltVT = VecVT.getVectorElementType(); 5367 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5368 5369 MVT ContainerVT = VecVT; 5370 if (VecVT.isFixedLengthVector()) { 5371 ContainerVT = getContainerForFixedLengthVector(VecVT); 5372 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5373 } 5374 5375 SDValue VL = Op.getOperand(3); 5376 SDValue Mask = Op.getOperand(2); 5377 5378 MVT M1VT = getLMUL1VT(ContainerVT); 5379 MVT XLenVT = Subtarget.getXLenVT(); 5380 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5381 5382 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5383 DAG.getConstant(1, DL, XLenVT), M1VT, 5384 DL, DAG, Subtarget); 5385 SDValue Reduction = 5386 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5387 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5388 DAG.getConstant(0, DL, XLenVT)); 5389 if (!VecVT.isInteger()) 5390 return Elt0; 5391 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5392 } 5393 5394 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5395 SelectionDAG &DAG) const { 5396 SDValue Vec = Op.getOperand(0); 5397 SDValue SubVec = Op.getOperand(1); 5398 MVT VecVT = Vec.getSimpleValueType(); 5399 MVT SubVecVT = SubVec.getSimpleValueType(); 5400 5401 SDLoc DL(Op); 5402 MVT XLenVT = Subtarget.getXLenVT(); 5403 unsigned OrigIdx = Op.getConstantOperandVal(2); 5404 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5405 5406 // We don't have the ability to slide mask vectors up indexed by their i1 5407 // elements; the smallest we can do is i8. Often we are able to bitcast to 5408 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5409 // into a scalable one, we might not necessarily have enough scalable 5410 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5411 if (SubVecVT.getVectorElementType() == MVT::i1 && 5412 (OrigIdx != 0 || !Vec.isUndef())) { 5413 if (VecVT.getVectorMinNumElements() >= 8 && 5414 SubVecVT.getVectorMinNumElements() >= 8) { 5415 assert(OrigIdx % 8 == 0 && "Invalid index"); 5416 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5417 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5418 "Unexpected mask vector lowering"); 5419 OrigIdx /= 8; 5420 SubVecVT = 5421 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5422 SubVecVT.isScalableVector()); 5423 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5424 VecVT.isScalableVector()); 5425 Vec = DAG.getBitcast(VecVT, Vec); 5426 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5427 } else { 5428 // We can't slide this mask vector up indexed by its i1 elements. 5429 // This poses a problem when we wish to insert a scalable vector which 5430 // can't be re-expressed as a larger type. Just choose the slow path and 5431 // extend to a larger type, then truncate back down. 5432 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5433 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5434 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5435 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5436 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5437 Op.getOperand(2)); 5438 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5439 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5440 } 5441 } 5442 5443 // If the subvector vector is a fixed-length type, we cannot use subregister 5444 // manipulation to simplify the codegen; we don't know which register of a 5445 // LMUL group contains the specific subvector as we only know the minimum 5446 // register size. Therefore we must slide the vector group up the full 5447 // amount. 5448 if (SubVecVT.isFixedLengthVector()) { 5449 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5450 return Op; 5451 MVT ContainerVT = VecVT; 5452 if (VecVT.isFixedLengthVector()) { 5453 ContainerVT = getContainerForFixedLengthVector(VecVT); 5454 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5455 } 5456 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5457 DAG.getUNDEF(ContainerVT), SubVec, 5458 DAG.getConstant(0, DL, XLenVT)); 5459 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5460 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5461 return DAG.getBitcast(Op.getValueType(), SubVec); 5462 } 5463 SDValue Mask = 5464 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5465 // Set the vector length to only the number of elements we care about. Note 5466 // that for slideup this includes the offset. 5467 SDValue VL = 5468 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5469 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5470 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5471 SubVec, SlideupAmt, Mask, VL); 5472 if (VecVT.isFixedLengthVector()) 5473 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5474 return DAG.getBitcast(Op.getValueType(), Slideup); 5475 } 5476 5477 unsigned SubRegIdx, RemIdx; 5478 std::tie(SubRegIdx, RemIdx) = 5479 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5480 VecVT, SubVecVT, OrigIdx, TRI); 5481 5482 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5483 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5484 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5485 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5486 5487 // 1. If the Idx has been completely eliminated and this subvector's size is 5488 // a vector register or a multiple thereof, or the surrounding elements are 5489 // undef, then this is a subvector insert which naturally aligns to a vector 5490 // register. These can easily be handled using subregister manipulation. 5491 // 2. If the subvector is smaller than a vector register, then the insertion 5492 // must preserve the undisturbed elements of the register. We do this by 5493 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5494 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5495 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5496 // LMUL=1 type back into the larger vector (resolving to another subregister 5497 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5498 // to avoid allocating a large register group to hold our subvector. 5499 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5500 return Op; 5501 5502 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5503 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5504 // (in our case undisturbed). This means we can set up a subvector insertion 5505 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5506 // size of the subvector. 5507 MVT InterSubVT = VecVT; 5508 SDValue AlignedExtract = Vec; 5509 unsigned AlignedIdx = OrigIdx - RemIdx; 5510 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5511 InterSubVT = getLMUL1VT(VecVT); 5512 // Extract a subvector equal to the nearest full vector register type. This 5513 // should resolve to a EXTRACT_SUBREG instruction. 5514 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5515 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5516 } 5517 5518 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5519 // For scalable vectors this must be further multiplied by vscale. 5520 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5521 5522 SDValue Mask, VL; 5523 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5524 5525 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5526 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5527 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5528 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5529 5530 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5531 DAG.getUNDEF(InterSubVT), SubVec, 5532 DAG.getConstant(0, DL, XLenVT)); 5533 5534 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5535 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5536 5537 // If required, insert this subvector back into the correct vector register. 5538 // This should resolve to an INSERT_SUBREG instruction. 5539 if (VecVT.bitsGT(InterSubVT)) 5540 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5541 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5542 5543 // We might have bitcast from a mask type: cast back to the original type if 5544 // required. 5545 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5546 } 5547 5548 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5549 SelectionDAG &DAG) const { 5550 SDValue Vec = Op.getOperand(0); 5551 MVT SubVecVT = Op.getSimpleValueType(); 5552 MVT VecVT = Vec.getSimpleValueType(); 5553 5554 SDLoc DL(Op); 5555 MVT XLenVT = Subtarget.getXLenVT(); 5556 unsigned OrigIdx = Op.getConstantOperandVal(1); 5557 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5558 5559 // We don't have the ability to slide mask vectors down indexed by their i1 5560 // elements; the smallest we can do is i8. Often we are able to bitcast to 5561 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5562 // from a scalable one, we might not necessarily have enough scalable 5563 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5564 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5565 if (VecVT.getVectorMinNumElements() >= 8 && 5566 SubVecVT.getVectorMinNumElements() >= 8) { 5567 assert(OrigIdx % 8 == 0 && "Invalid index"); 5568 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5569 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5570 "Unexpected mask vector lowering"); 5571 OrigIdx /= 8; 5572 SubVecVT = 5573 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5574 SubVecVT.isScalableVector()); 5575 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5576 VecVT.isScalableVector()); 5577 Vec = DAG.getBitcast(VecVT, Vec); 5578 } else { 5579 // We can't slide this mask vector down, indexed by its i1 elements. 5580 // This poses a problem when we wish to extract a scalable vector which 5581 // can't be re-expressed as a larger type. Just choose the slow path and 5582 // extend to a larger type, then truncate back down. 5583 // TODO: We could probably improve this when extracting certain fixed 5584 // from fixed, where we can extract as i8 and shift the correct element 5585 // right to reach the desired subvector? 5586 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5587 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5588 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5589 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5590 Op.getOperand(1)); 5591 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5592 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5593 } 5594 } 5595 5596 // If the subvector vector is a fixed-length type, we cannot use subregister 5597 // manipulation to simplify the codegen; we don't know which register of a 5598 // LMUL group contains the specific subvector as we only know the minimum 5599 // register size. Therefore we must slide the vector group down the full 5600 // amount. 5601 if (SubVecVT.isFixedLengthVector()) { 5602 // With an index of 0 this is a cast-like subvector, which can be performed 5603 // with subregister operations. 5604 if (OrigIdx == 0) 5605 return Op; 5606 MVT ContainerVT = VecVT; 5607 if (VecVT.isFixedLengthVector()) { 5608 ContainerVT = getContainerForFixedLengthVector(VecVT); 5609 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5610 } 5611 SDValue Mask = 5612 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5613 // Set the vector length to only the number of elements we care about. This 5614 // avoids sliding down elements we're going to discard straight away. 5615 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5616 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5617 SDValue Slidedown = 5618 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5619 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5620 // Now we can use a cast-like subvector extract to get the result. 5621 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5622 DAG.getConstant(0, DL, XLenVT)); 5623 return DAG.getBitcast(Op.getValueType(), Slidedown); 5624 } 5625 5626 unsigned SubRegIdx, RemIdx; 5627 std::tie(SubRegIdx, RemIdx) = 5628 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5629 VecVT, SubVecVT, OrigIdx, TRI); 5630 5631 // If the Idx has been completely eliminated then this is a subvector extract 5632 // which naturally aligns to a vector register. These can easily be handled 5633 // using subregister manipulation. 5634 if (RemIdx == 0) 5635 return Op; 5636 5637 // Else we must shift our vector register directly to extract the subvector. 5638 // Do this using VSLIDEDOWN. 5639 5640 // If the vector type is an LMUL-group type, extract a subvector equal to the 5641 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5642 // instruction. 5643 MVT InterSubVT = VecVT; 5644 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5645 InterSubVT = getLMUL1VT(VecVT); 5646 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5647 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5648 } 5649 5650 // Slide this vector register down by the desired number of elements in order 5651 // to place the desired subvector starting at element 0. 5652 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5653 // For scalable vectors this must be further multiplied by vscale. 5654 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5655 5656 SDValue Mask, VL; 5657 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5658 SDValue Slidedown = 5659 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5660 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5661 5662 // Now the vector is in the right position, extract our final subvector. This 5663 // should resolve to a COPY. 5664 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5665 DAG.getConstant(0, DL, XLenVT)); 5666 5667 // We might have bitcast from a mask type: cast back to the original type if 5668 // required. 5669 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5670 } 5671 5672 // Lower step_vector to the vid instruction. Any non-identity step value must 5673 // be accounted for my manual expansion. 5674 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5675 SelectionDAG &DAG) const { 5676 SDLoc DL(Op); 5677 MVT VT = Op.getSimpleValueType(); 5678 MVT XLenVT = Subtarget.getXLenVT(); 5679 SDValue Mask, VL; 5680 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5681 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5682 uint64_t StepValImm = Op.getConstantOperandVal(0); 5683 if (StepValImm != 1) { 5684 if (isPowerOf2_64(StepValImm)) { 5685 SDValue StepVal = 5686 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5687 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5688 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5689 } else { 5690 SDValue StepVal = lowerScalarSplat( 5691 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5692 VL, VT, DL, DAG, Subtarget); 5693 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5694 } 5695 } 5696 return StepVec; 5697 } 5698 5699 // Implement vector_reverse using vrgather.vv with indices determined by 5700 // subtracting the id of each element from (VLMAX-1). This will convert 5701 // the indices like so: 5702 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5703 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5704 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5705 SelectionDAG &DAG) const { 5706 SDLoc DL(Op); 5707 MVT VecVT = Op.getSimpleValueType(); 5708 if (VecVT.getVectorElementType() == MVT::i1) { 5709 MVT WidenVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 5710 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenVT, Op.getOperand(0)); 5711 SDValue Op2 = DAG.getNode(ISD::VECTOR_REVERSE, DL, WidenVT, Op1); 5712 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Op2); 5713 } 5714 unsigned EltSize = VecVT.getScalarSizeInBits(); 5715 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5716 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 5717 unsigned MaxVLMAX = 5718 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 5719 5720 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5721 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5722 5723 // If this is SEW=8 and VLMAX is potentially more than 256, we need 5724 // to use vrgatherei16.vv. 5725 // TODO: It's also possible to use vrgatherei16.vv for other types to 5726 // decrease register width for the index calculation. 5727 if (MaxVLMAX > 256 && EltSize == 8) { 5728 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5729 // Reverse each half, then reassemble them in reverse order. 5730 // NOTE: It's also possible that after splitting that VLMAX no longer 5731 // requires vrgatherei16.vv. 5732 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5733 SDValue Lo, Hi; 5734 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5735 EVT LoVT, HiVT; 5736 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5737 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5738 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5739 // Reassemble the low and high pieces reversed. 5740 // FIXME: This is a CONCAT_VECTORS. 5741 SDValue Res = 5742 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5743 DAG.getIntPtrConstant(0, DL)); 5744 return DAG.getNode( 5745 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5746 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5747 } 5748 5749 // Just promote the int type to i16 which will double the LMUL. 5750 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5751 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5752 } 5753 5754 MVT XLenVT = Subtarget.getXLenVT(); 5755 SDValue Mask, VL; 5756 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5757 5758 // Calculate VLMAX-1 for the desired SEW. 5759 unsigned MinElts = VecVT.getVectorMinNumElements(); 5760 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5761 DAG.getConstant(MinElts, DL, XLenVT)); 5762 SDValue VLMinus1 = 5763 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5764 5765 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5766 bool IsRV32E64 = 5767 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5768 SDValue SplatVL; 5769 if (!IsRV32E64) 5770 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5771 else 5772 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5773 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5774 5775 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5776 SDValue Indices = 5777 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5778 5779 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, 5780 DAG.getUNDEF(VecVT), VL); 5781 } 5782 5783 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5784 SelectionDAG &DAG) const { 5785 SDLoc DL(Op); 5786 SDValue V1 = Op.getOperand(0); 5787 SDValue V2 = Op.getOperand(1); 5788 MVT XLenVT = Subtarget.getXLenVT(); 5789 MVT VecVT = Op.getSimpleValueType(); 5790 5791 unsigned MinElts = VecVT.getVectorMinNumElements(); 5792 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5793 DAG.getConstant(MinElts, DL, XLenVT)); 5794 5795 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5796 SDValue DownOffset, UpOffset; 5797 if (ImmValue >= 0) { 5798 // The operand is a TargetConstant, we need to rebuild it as a regular 5799 // constant. 5800 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5801 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5802 } else { 5803 // The operand is a TargetConstant, we need to rebuild it as a regular 5804 // constant rather than negating the original operand. 5805 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5806 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5807 } 5808 5809 SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG); 5810 5811 SDValue SlideDown = 5812 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5813 DownOffset, TrueMask, UpOffset); 5814 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5815 TrueMask, DAG.getRegister(RISCV::X0, XLenVT)); 5816 } 5817 5818 SDValue 5819 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5820 SelectionDAG &DAG) const { 5821 SDLoc DL(Op); 5822 auto *Load = cast<LoadSDNode>(Op); 5823 5824 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5825 Load->getMemoryVT(), 5826 *Load->getMemOperand()) && 5827 "Expecting a correctly-aligned load"); 5828 5829 MVT VT = Op.getSimpleValueType(); 5830 MVT XLenVT = Subtarget.getXLenVT(); 5831 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5832 5833 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5834 5835 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5836 SDValue IntID = DAG.getTargetConstant( 5837 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 5838 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 5839 if (!IsMaskOp) 5840 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5841 Ops.push_back(Load->getBasePtr()); 5842 Ops.push_back(VL); 5843 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5844 SDValue NewLoad = 5845 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5846 Load->getMemoryVT(), Load->getMemOperand()); 5847 5848 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5849 return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL); 5850 } 5851 5852 SDValue 5853 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5854 SelectionDAG &DAG) const { 5855 SDLoc DL(Op); 5856 auto *Store = cast<StoreSDNode>(Op); 5857 5858 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5859 Store->getMemoryVT(), 5860 *Store->getMemOperand()) && 5861 "Expecting a correctly-aligned store"); 5862 5863 SDValue StoreVal = Store->getValue(); 5864 MVT VT = StoreVal.getSimpleValueType(); 5865 MVT XLenVT = Subtarget.getXLenVT(); 5866 5867 // If the size less than a byte, we need to pad with zeros to make a byte. 5868 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5869 VT = MVT::v8i1; 5870 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5871 DAG.getConstant(0, DL, VT), StoreVal, 5872 DAG.getIntPtrConstant(0, DL)); 5873 } 5874 5875 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5876 5877 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5878 5879 SDValue NewValue = 5880 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5881 5882 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5883 SDValue IntID = DAG.getTargetConstant( 5884 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 5885 return DAG.getMemIntrinsicNode( 5886 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 5887 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 5888 Store->getMemoryVT(), Store->getMemOperand()); 5889 } 5890 5891 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5892 SelectionDAG &DAG) const { 5893 SDLoc DL(Op); 5894 MVT VT = Op.getSimpleValueType(); 5895 5896 const auto *MemSD = cast<MemSDNode>(Op); 5897 EVT MemVT = MemSD->getMemoryVT(); 5898 MachineMemOperand *MMO = MemSD->getMemOperand(); 5899 SDValue Chain = MemSD->getChain(); 5900 SDValue BasePtr = MemSD->getBasePtr(); 5901 5902 SDValue Mask, PassThru, VL; 5903 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5904 Mask = VPLoad->getMask(); 5905 PassThru = DAG.getUNDEF(VT); 5906 VL = VPLoad->getVectorLength(); 5907 } else { 5908 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5909 Mask = MLoad->getMask(); 5910 PassThru = MLoad->getPassThru(); 5911 } 5912 5913 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5914 5915 MVT XLenVT = Subtarget.getXLenVT(); 5916 5917 MVT ContainerVT = VT; 5918 if (VT.isFixedLengthVector()) { 5919 ContainerVT = getContainerForFixedLengthVector(VT); 5920 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5921 if (!IsUnmasked) { 5922 MVT MaskVT = getMaskTypeFor(ContainerVT); 5923 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5924 } 5925 } 5926 5927 if (!VL) 5928 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5929 5930 unsigned IntID = 5931 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5932 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5933 if (IsUnmasked) 5934 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5935 else 5936 Ops.push_back(PassThru); 5937 Ops.push_back(BasePtr); 5938 if (!IsUnmasked) 5939 Ops.push_back(Mask); 5940 Ops.push_back(VL); 5941 if (!IsUnmasked) 5942 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5943 5944 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5945 5946 SDValue Result = 5947 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5948 Chain = Result.getValue(1); 5949 5950 if (VT.isFixedLengthVector()) 5951 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5952 5953 return DAG.getMergeValues({Result, Chain}, DL); 5954 } 5955 5956 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5957 SelectionDAG &DAG) const { 5958 SDLoc DL(Op); 5959 5960 const auto *MemSD = cast<MemSDNode>(Op); 5961 EVT MemVT = MemSD->getMemoryVT(); 5962 MachineMemOperand *MMO = MemSD->getMemOperand(); 5963 SDValue Chain = MemSD->getChain(); 5964 SDValue BasePtr = MemSD->getBasePtr(); 5965 SDValue Val, Mask, VL; 5966 5967 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5968 Val = VPStore->getValue(); 5969 Mask = VPStore->getMask(); 5970 VL = VPStore->getVectorLength(); 5971 } else { 5972 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5973 Val = MStore->getValue(); 5974 Mask = MStore->getMask(); 5975 } 5976 5977 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5978 5979 MVT VT = Val.getSimpleValueType(); 5980 MVT XLenVT = Subtarget.getXLenVT(); 5981 5982 MVT ContainerVT = VT; 5983 if (VT.isFixedLengthVector()) { 5984 ContainerVT = getContainerForFixedLengthVector(VT); 5985 5986 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5987 if (!IsUnmasked) { 5988 MVT MaskVT = getMaskTypeFor(ContainerVT); 5989 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5990 } 5991 } 5992 5993 if (!VL) 5994 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5995 5996 unsigned IntID = 5997 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5998 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5999 Ops.push_back(Val); 6000 Ops.push_back(BasePtr); 6001 if (!IsUnmasked) 6002 Ops.push_back(Mask); 6003 Ops.push_back(VL); 6004 6005 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6006 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6007 } 6008 6009 SDValue 6010 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 6011 SelectionDAG &DAG) const { 6012 MVT InVT = Op.getOperand(0).getSimpleValueType(); 6013 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 6014 6015 MVT VT = Op.getSimpleValueType(); 6016 6017 SDValue Op1 = 6018 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 6019 SDValue Op2 = 6020 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 6021 6022 SDLoc DL(Op); 6023 SDValue VL = 6024 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 6025 6026 MVT MaskVT = getMaskTypeFor(ContainerVT); 6027 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 6028 6029 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 6030 Op.getOperand(2), Mask, VL); 6031 6032 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 6033 } 6034 6035 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 6036 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 6037 MVT VT = Op.getSimpleValueType(); 6038 6039 if (VT.getVectorElementType() == MVT::i1) 6040 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 6041 6042 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 6043 } 6044 6045 SDValue 6046 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 6047 SelectionDAG &DAG) const { 6048 unsigned Opc; 6049 switch (Op.getOpcode()) { 6050 default: llvm_unreachable("Unexpected opcode!"); 6051 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 6052 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 6053 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 6054 } 6055 6056 return lowerToScalableOp(Op, DAG, Opc); 6057 } 6058 6059 // Lower vector ABS to smax(X, sub(0, X)). 6060 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 6061 SDLoc DL(Op); 6062 MVT VT = Op.getSimpleValueType(); 6063 SDValue X = Op.getOperand(0); 6064 6065 assert(VT.isFixedLengthVector() && "Unexpected type"); 6066 6067 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6068 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 6069 6070 SDValue Mask, VL; 6071 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6072 6073 SDValue SplatZero = DAG.getNode( 6074 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 6075 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 6076 SDValue NegX = 6077 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 6078 SDValue Max = 6079 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 6080 6081 return convertFromScalableVector(VT, Max, DAG, Subtarget); 6082 } 6083 6084 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 6085 SDValue Op, SelectionDAG &DAG) const { 6086 SDLoc DL(Op); 6087 MVT VT = Op.getSimpleValueType(); 6088 SDValue Mag = Op.getOperand(0); 6089 SDValue Sign = Op.getOperand(1); 6090 assert(Mag.getValueType() == Sign.getValueType() && 6091 "Can only handle COPYSIGN with matching types."); 6092 6093 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6094 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 6095 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 6096 6097 SDValue Mask, VL; 6098 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6099 6100 SDValue CopySign = 6101 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 6102 6103 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 6104 } 6105 6106 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 6107 SDValue Op, SelectionDAG &DAG) const { 6108 MVT VT = Op.getSimpleValueType(); 6109 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6110 6111 MVT I1ContainerVT = 6112 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6113 6114 SDValue CC = 6115 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 6116 SDValue Op1 = 6117 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 6118 SDValue Op2 = 6119 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 6120 6121 SDLoc DL(Op); 6122 SDValue Mask, VL; 6123 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6124 6125 SDValue Select = 6126 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 6127 6128 return convertFromScalableVector(VT, Select, DAG, Subtarget); 6129 } 6130 6131 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 6132 unsigned NewOpc, 6133 bool HasMask) const { 6134 MVT VT = Op.getSimpleValueType(); 6135 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6136 6137 // Create list of operands by converting existing ones to scalable types. 6138 SmallVector<SDValue, 6> Ops; 6139 for (const SDValue &V : Op->op_values()) { 6140 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6141 6142 // Pass through non-vector operands. 6143 if (!V.getValueType().isVector()) { 6144 Ops.push_back(V); 6145 continue; 6146 } 6147 6148 // "cast" fixed length vector to a scalable vector. 6149 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6150 "Only fixed length vectors are supported!"); 6151 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6152 } 6153 6154 SDLoc DL(Op); 6155 SDValue Mask, VL; 6156 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6157 if (HasMask) 6158 Ops.push_back(Mask); 6159 Ops.push_back(VL); 6160 6161 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6162 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6163 } 6164 6165 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6166 // * Operands of each node are assumed to be in the same order. 6167 // * The EVL operand is promoted from i32 to i64 on RV64. 6168 // * Fixed-length vectors are converted to their scalable-vector container 6169 // types. 6170 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6171 unsigned RISCVISDOpc) const { 6172 SDLoc DL(Op); 6173 MVT VT = Op.getSimpleValueType(); 6174 SmallVector<SDValue, 4> Ops; 6175 6176 for (const auto &OpIdx : enumerate(Op->ops())) { 6177 SDValue V = OpIdx.value(); 6178 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6179 // Pass through operands which aren't fixed-length vectors. 6180 if (!V.getValueType().isFixedLengthVector()) { 6181 Ops.push_back(V); 6182 continue; 6183 } 6184 // "cast" fixed length vector to a scalable vector. 6185 MVT OpVT = V.getSimpleValueType(); 6186 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6187 assert(useRVVForFixedLengthVectorVT(OpVT) && 6188 "Only fixed length vectors are supported!"); 6189 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6190 } 6191 6192 if (!VT.isFixedLengthVector()) 6193 return DAG.getNode(RISCVISDOpc, DL, VT, Ops, Op->getFlags()); 6194 6195 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6196 6197 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops, Op->getFlags()); 6198 6199 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6200 } 6201 6202 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op, 6203 SelectionDAG &DAG) const { 6204 SDLoc DL(Op); 6205 MVT VT = Op.getSimpleValueType(); 6206 6207 SDValue Src = Op.getOperand(0); 6208 // NOTE: Mask is dropped. 6209 SDValue VL = Op.getOperand(2); 6210 6211 MVT ContainerVT = VT; 6212 if (VT.isFixedLengthVector()) { 6213 ContainerVT = getContainerForFixedLengthVector(VT); 6214 MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6215 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6216 } 6217 6218 MVT XLenVT = Subtarget.getXLenVT(); 6219 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6220 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6221 DAG.getUNDEF(ContainerVT), Zero, VL); 6222 6223 SDValue SplatValue = DAG.getConstant( 6224 Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT); 6225 SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6226 DAG.getUNDEF(ContainerVT), SplatValue, VL); 6227 6228 SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src, 6229 Splat, ZeroSplat, VL); 6230 if (!VT.isFixedLengthVector()) 6231 return Result; 6232 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6233 } 6234 6235 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op, 6236 SelectionDAG &DAG) const { 6237 SDLoc DL(Op); 6238 MVT VT = Op.getSimpleValueType(); 6239 6240 SDValue Op1 = Op.getOperand(0); 6241 SDValue Op2 = Op.getOperand(1); 6242 ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 6243 // NOTE: Mask is dropped. 6244 SDValue VL = Op.getOperand(4); 6245 6246 MVT ContainerVT = VT; 6247 if (VT.isFixedLengthVector()) { 6248 ContainerVT = getContainerForFixedLengthVector(VT); 6249 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6250 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6251 } 6252 6253 SDValue Result; 6254 SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 6255 6256 switch (Condition) { 6257 default: 6258 break; 6259 // X != Y --> (X^Y) 6260 case ISD::SETNE: 6261 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6262 break; 6263 // X == Y --> ~(X^Y) 6264 case ISD::SETEQ: { 6265 SDValue Temp = 6266 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6267 Result = 6268 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL); 6269 break; 6270 } 6271 // X >s Y --> X == 0 & Y == 1 --> ~X & Y 6272 // X <u Y --> X == 0 & Y == 1 --> ~X & Y 6273 case ISD::SETGT: 6274 case ISD::SETULT: { 6275 SDValue Temp = 6276 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6277 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL); 6278 break; 6279 } 6280 // X <s Y --> X == 1 & Y == 0 --> ~Y & X 6281 // X >u Y --> X == 1 & Y == 0 --> ~Y & X 6282 case ISD::SETLT: 6283 case ISD::SETUGT: { 6284 SDValue Temp = 6285 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6286 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL); 6287 break; 6288 } 6289 // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 6290 // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 6291 case ISD::SETGE: 6292 case ISD::SETULE: { 6293 SDValue Temp = 6294 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6295 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL); 6296 break; 6297 } 6298 // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 6299 // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 6300 case ISD::SETLE: 6301 case ISD::SETUGE: { 6302 SDValue Temp = 6303 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6304 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL); 6305 break; 6306 } 6307 } 6308 6309 if (!VT.isFixedLengthVector()) 6310 return Result; 6311 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6312 } 6313 6314 // Lower Floating-Point/Integer Type-Convert VP SDNodes 6315 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG, 6316 unsigned RISCVISDOpc) const { 6317 SDLoc DL(Op); 6318 6319 SDValue Src = Op.getOperand(0); 6320 SDValue Mask = Op.getOperand(1); 6321 SDValue VL = Op.getOperand(2); 6322 6323 MVT DstVT = Op.getSimpleValueType(); 6324 MVT SrcVT = Src.getSimpleValueType(); 6325 if (DstVT.isFixedLengthVector()) { 6326 DstVT = getContainerForFixedLengthVector(DstVT); 6327 SrcVT = getContainerForFixedLengthVector(SrcVT); 6328 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6329 MVT MaskVT = getMaskTypeFor(DstVT); 6330 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6331 } 6332 6333 unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL || 6334 RISCVISDOpc == RISCVISD::FP_TO_SINT_VL) 6335 ? RISCVISD::VSEXT_VL 6336 : RISCVISD::VZEXT_VL; 6337 6338 unsigned DstEltSize = DstVT.getScalarSizeInBits(); 6339 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 6340 6341 SDValue Result; 6342 if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion. 6343 if (SrcVT.isInteger()) { 6344 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6345 6346 // Do we need to do any pre-widening before converting? 6347 if (SrcEltSize == 1) { 6348 MVT IntVT = DstVT.changeVectorElementTypeToInteger(); 6349 MVT XLenVT = Subtarget.getXLenVT(); 6350 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6351 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6352 DAG.getUNDEF(IntVT), Zero, VL); 6353 SDValue One = DAG.getConstant( 6354 RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT); 6355 SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6356 DAG.getUNDEF(IntVT), One, VL); 6357 Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat, 6358 ZeroSplat, VL); 6359 } else if (DstEltSize > (2 * SrcEltSize)) { 6360 // Widen before converting. 6361 MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2), 6362 DstVT.getVectorElementCount()); 6363 Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL); 6364 } 6365 6366 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6367 } else { 6368 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6369 "Wrong input/output vector types"); 6370 6371 // Convert f16 to f32 then convert f32 to i64. 6372 if (DstEltSize > (2 * SrcEltSize)) { 6373 assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6374 MVT InterimFVT = 6375 MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6376 Src = 6377 DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL); 6378 } 6379 6380 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6381 } 6382 } else { // Narrowing + Conversion 6383 if (SrcVT.isInteger()) { 6384 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6385 // First do a narrowing convert to an FP type half the size, then round 6386 // the FP type to a small FP type if needed. 6387 6388 MVT InterimFVT = DstVT; 6389 if (SrcEltSize > (2 * DstEltSize)) { 6390 assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!"); 6391 assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6392 InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6393 } 6394 6395 Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL); 6396 6397 if (InterimFVT != DstVT) { 6398 Src = Result; 6399 Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL); 6400 } 6401 } else { 6402 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6403 "Wrong input/output vector types"); 6404 // First do a narrowing conversion to an integer half the size, then 6405 // truncate if needed. 6406 6407 if (DstEltSize == 1) { 6408 // First convert to the same size integer, then convert to mask using 6409 // setcc. 6410 assert(SrcEltSize >= 16 && "Unexpected FP type!"); 6411 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize), 6412 DstVT.getVectorElementCount()); 6413 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6414 6415 // Compare the integer result to 0. The integer should be 0 or 1/-1, 6416 // otherwise the conversion was undefined. 6417 MVT XLenVT = Subtarget.getXLenVT(); 6418 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 6419 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT, 6420 DAG.getUNDEF(InterimIVT), SplatZero); 6421 Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero, 6422 DAG.getCondCode(ISD::SETNE), Mask, VL); 6423 } else { 6424 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6425 DstVT.getVectorElementCount()); 6426 6427 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6428 6429 while (InterimIVT != DstVT) { 6430 SrcEltSize /= 2; 6431 Src = Result; 6432 InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6433 DstVT.getVectorElementCount()); 6434 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT, 6435 Src, Mask, VL); 6436 } 6437 } 6438 } 6439 } 6440 6441 MVT VT = Op.getSimpleValueType(); 6442 if (!VT.isFixedLengthVector()) 6443 return Result; 6444 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6445 } 6446 6447 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6448 unsigned MaskOpc, 6449 unsigned VecOpc) const { 6450 MVT VT = Op.getSimpleValueType(); 6451 if (VT.getVectorElementType() != MVT::i1) 6452 return lowerVPOp(Op, DAG, VecOpc); 6453 6454 // It is safe to drop mask parameter as masked-off elements are undef. 6455 SDValue Op1 = Op->getOperand(0); 6456 SDValue Op2 = Op->getOperand(1); 6457 SDValue VL = Op->getOperand(3); 6458 6459 MVT ContainerVT = VT; 6460 const bool IsFixed = VT.isFixedLengthVector(); 6461 if (IsFixed) { 6462 ContainerVT = getContainerForFixedLengthVector(VT); 6463 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6464 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6465 } 6466 6467 SDLoc DL(Op); 6468 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6469 if (!IsFixed) 6470 return Val; 6471 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6472 } 6473 6474 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6475 // matched to a RVV indexed load. The RVV indexed load instructions only 6476 // support the "unsigned unscaled" addressing mode; indices are implicitly 6477 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6478 // signed or scaled indexing is extended to the XLEN value type and scaled 6479 // accordingly. 6480 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6481 SelectionDAG &DAG) const { 6482 SDLoc DL(Op); 6483 MVT VT = Op.getSimpleValueType(); 6484 6485 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6486 EVT MemVT = MemSD->getMemoryVT(); 6487 MachineMemOperand *MMO = MemSD->getMemOperand(); 6488 SDValue Chain = MemSD->getChain(); 6489 SDValue BasePtr = MemSD->getBasePtr(); 6490 6491 ISD::LoadExtType LoadExtType; 6492 SDValue Index, Mask, PassThru, VL; 6493 6494 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6495 Index = VPGN->getIndex(); 6496 Mask = VPGN->getMask(); 6497 PassThru = DAG.getUNDEF(VT); 6498 VL = VPGN->getVectorLength(); 6499 // VP doesn't support extending loads. 6500 LoadExtType = ISD::NON_EXTLOAD; 6501 } else { 6502 // Else it must be a MGATHER. 6503 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6504 Index = MGN->getIndex(); 6505 Mask = MGN->getMask(); 6506 PassThru = MGN->getPassThru(); 6507 LoadExtType = MGN->getExtensionType(); 6508 } 6509 6510 MVT IndexVT = Index.getSimpleValueType(); 6511 MVT XLenVT = Subtarget.getXLenVT(); 6512 6513 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6514 "Unexpected VTs!"); 6515 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6516 // Targets have to explicitly opt-in for extending vector loads. 6517 assert(LoadExtType == ISD::NON_EXTLOAD && 6518 "Unexpected extending MGATHER/VP_GATHER"); 6519 (void)LoadExtType; 6520 6521 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6522 // the selection of the masked intrinsics doesn't do this for us. 6523 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6524 6525 MVT ContainerVT = VT; 6526 if (VT.isFixedLengthVector()) { 6527 ContainerVT = getContainerForFixedLengthVector(VT); 6528 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6529 ContainerVT.getVectorElementCount()); 6530 6531 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6532 6533 if (!IsUnmasked) { 6534 MVT MaskVT = getMaskTypeFor(ContainerVT); 6535 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6536 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6537 } 6538 } 6539 6540 if (!VL) 6541 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6542 6543 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6544 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6545 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6546 VL); 6547 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6548 TrueMask, VL); 6549 } 6550 6551 unsigned IntID = 6552 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6553 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6554 if (IsUnmasked) 6555 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6556 else 6557 Ops.push_back(PassThru); 6558 Ops.push_back(BasePtr); 6559 Ops.push_back(Index); 6560 if (!IsUnmasked) 6561 Ops.push_back(Mask); 6562 Ops.push_back(VL); 6563 if (!IsUnmasked) 6564 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6565 6566 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6567 SDValue Result = 6568 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6569 Chain = Result.getValue(1); 6570 6571 if (VT.isFixedLengthVector()) 6572 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6573 6574 return DAG.getMergeValues({Result, Chain}, DL); 6575 } 6576 6577 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6578 // matched to a RVV indexed store. The RVV indexed store instructions only 6579 // support the "unsigned unscaled" addressing mode; indices are implicitly 6580 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6581 // signed or scaled indexing is extended to the XLEN value type and scaled 6582 // accordingly. 6583 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6584 SelectionDAG &DAG) const { 6585 SDLoc DL(Op); 6586 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6587 EVT MemVT = MemSD->getMemoryVT(); 6588 MachineMemOperand *MMO = MemSD->getMemOperand(); 6589 SDValue Chain = MemSD->getChain(); 6590 SDValue BasePtr = MemSD->getBasePtr(); 6591 6592 bool IsTruncatingStore = false; 6593 SDValue Index, Mask, Val, VL; 6594 6595 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6596 Index = VPSN->getIndex(); 6597 Mask = VPSN->getMask(); 6598 Val = VPSN->getValue(); 6599 VL = VPSN->getVectorLength(); 6600 // VP doesn't support truncating stores. 6601 IsTruncatingStore = false; 6602 } else { 6603 // Else it must be a MSCATTER. 6604 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6605 Index = MSN->getIndex(); 6606 Mask = MSN->getMask(); 6607 Val = MSN->getValue(); 6608 IsTruncatingStore = MSN->isTruncatingStore(); 6609 } 6610 6611 MVT VT = Val.getSimpleValueType(); 6612 MVT IndexVT = Index.getSimpleValueType(); 6613 MVT XLenVT = Subtarget.getXLenVT(); 6614 6615 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6616 "Unexpected VTs!"); 6617 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6618 // Targets have to explicitly opt-in for extending vector loads and 6619 // truncating vector stores. 6620 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6621 (void)IsTruncatingStore; 6622 6623 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6624 // the selection of the masked intrinsics doesn't do this for us. 6625 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6626 6627 MVT ContainerVT = VT; 6628 if (VT.isFixedLengthVector()) { 6629 ContainerVT = getContainerForFixedLengthVector(VT); 6630 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6631 ContainerVT.getVectorElementCount()); 6632 6633 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6634 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6635 6636 if (!IsUnmasked) { 6637 MVT MaskVT = getMaskTypeFor(ContainerVT); 6638 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6639 } 6640 } 6641 6642 if (!VL) 6643 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6644 6645 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6646 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6647 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6648 VL); 6649 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6650 TrueMask, VL); 6651 } 6652 6653 unsigned IntID = 6654 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6655 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6656 Ops.push_back(Val); 6657 Ops.push_back(BasePtr); 6658 Ops.push_back(Index); 6659 if (!IsUnmasked) 6660 Ops.push_back(Mask); 6661 Ops.push_back(VL); 6662 6663 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6664 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6665 } 6666 6667 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6668 SelectionDAG &DAG) const { 6669 const MVT XLenVT = Subtarget.getXLenVT(); 6670 SDLoc DL(Op); 6671 SDValue Chain = Op->getOperand(0); 6672 SDValue SysRegNo = DAG.getTargetConstant( 6673 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6674 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6675 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6676 6677 // Encoding used for rounding mode in RISCV differs from that used in 6678 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6679 // table, which consists of a sequence of 4-bit fields, each representing 6680 // corresponding FLT_ROUNDS mode. 6681 static const int Table = 6682 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6683 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6684 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6685 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6686 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6687 6688 SDValue Shift = 6689 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6690 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6691 DAG.getConstant(Table, DL, XLenVT), Shift); 6692 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6693 DAG.getConstant(7, DL, XLenVT)); 6694 6695 return DAG.getMergeValues({Masked, Chain}, DL); 6696 } 6697 6698 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6699 SelectionDAG &DAG) const { 6700 const MVT XLenVT = Subtarget.getXLenVT(); 6701 SDLoc DL(Op); 6702 SDValue Chain = Op->getOperand(0); 6703 SDValue RMValue = Op->getOperand(1); 6704 SDValue SysRegNo = DAG.getTargetConstant( 6705 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6706 6707 // Encoding used for rounding mode in RISCV differs from that used in 6708 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6709 // a table, which consists of a sequence of 4-bit fields, each representing 6710 // corresponding RISCV mode. 6711 static const unsigned Table = 6712 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6713 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6714 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6715 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6716 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6717 6718 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6719 DAG.getConstant(2, DL, XLenVT)); 6720 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6721 DAG.getConstant(Table, DL, XLenVT), Shift); 6722 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6723 DAG.getConstant(0x7, DL, XLenVT)); 6724 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6725 RMValue); 6726 } 6727 6728 SDValue RISCVTargetLowering::lowerEH_DWARF_CFA(SDValue Op, 6729 SelectionDAG &DAG) const { 6730 MachineFunction &MF = DAG.getMachineFunction(); 6731 6732 bool isRISCV64 = Subtarget.is64Bit(); 6733 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6734 6735 int FI = MF.getFrameInfo().CreateFixedObject(isRISCV64 ? 8 : 4, 0, false); 6736 return DAG.getFrameIndex(FI, PtrVT); 6737 } 6738 6739 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6740 switch (IntNo) { 6741 default: 6742 llvm_unreachable("Unexpected Intrinsic"); 6743 case Intrinsic::riscv_bcompress: 6744 return RISCVISD::BCOMPRESSW; 6745 case Intrinsic::riscv_bdecompress: 6746 return RISCVISD::BDECOMPRESSW; 6747 case Intrinsic::riscv_bfp: 6748 return RISCVISD::BFPW; 6749 case Intrinsic::riscv_fsl: 6750 return RISCVISD::FSLW; 6751 case Intrinsic::riscv_fsr: 6752 return RISCVISD::FSRW; 6753 } 6754 } 6755 6756 // Converts the given intrinsic to a i64 operation with any extension. 6757 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6758 unsigned IntNo) { 6759 SDLoc DL(N); 6760 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6761 // Deal with the Instruction Operands 6762 SmallVector<SDValue, 3> NewOps; 6763 for (SDValue Op : drop_begin(N->ops())) 6764 // Promote the operand to i64 type 6765 NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op)); 6766 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps); 6767 // ReplaceNodeResults requires we maintain the same type for the return value. 6768 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6769 } 6770 6771 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6772 // form of the given Opcode. 6773 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6774 switch (Opcode) { 6775 default: 6776 llvm_unreachable("Unexpected opcode"); 6777 case ISD::SHL: 6778 return RISCVISD::SLLW; 6779 case ISD::SRA: 6780 return RISCVISD::SRAW; 6781 case ISD::SRL: 6782 return RISCVISD::SRLW; 6783 case ISD::SDIV: 6784 return RISCVISD::DIVW; 6785 case ISD::UDIV: 6786 return RISCVISD::DIVUW; 6787 case ISD::UREM: 6788 return RISCVISD::REMUW; 6789 case ISD::ROTL: 6790 return RISCVISD::ROLW; 6791 case ISD::ROTR: 6792 return RISCVISD::RORW; 6793 } 6794 } 6795 6796 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6797 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6798 // otherwise be promoted to i64, making it difficult to select the 6799 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6800 // type i8/i16/i32 is lost. 6801 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6802 unsigned ExtOpc = ISD::ANY_EXTEND) { 6803 SDLoc DL(N); 6804 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6805 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6806 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6807 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6808 // ReplaceNodeResults requires we maintain the same type for the return value. 6809 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6810 } 6811 6812 // Converts the given 32-bit operation to a i64 operation with signed extension 6813 // semantic to reduce the signed extension instructions. 6814 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6815 SDLoc DL(N); 6816 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6817 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6818 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6819 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6820 DAG.getValueType(MVT::i32)); 6821 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6822 } 6823 6824 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6825 SmallVectorImpl<SDValue> &Results, 6826 SelectionDAG &DAG) const { 6827 SDLoc DL(N); 6828 switch (N->getOpcode()) { 6829 default: 6830 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6831 case ISD::STRICT_FP_TO_SINT: 6832 case ISD::STRICT_FP_TO_UINT: 6833 case ISD::FP_TO_SINT: 6834 case ISD::FP_TO_UINT: { 6835 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6836 "Unexpected custom legalisation"); 6837 bool IsStrict = N->isStrictFPOpcode(); 6838 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6839 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6840 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6841 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6842 TargetLowering::TypeSoftenFloat) { 6843 if (!isTypeLegal(Op0.getValueType())) 6844 return; 6845 if (IsStrict) { 6846 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6847 : RISCVISD::STRICT_FCVT_WU_RV64; 6848 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6849 SDValue Res = DAG.getNode( 6850 Opc, DL, VTs, N->getOperand(0), Op0, 6851 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6852 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6853 Results.push_back(Res.getValue(1)); 6854 return; 6855 } 6856 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6857 SDValue Res = 6858 DAG.getNode(Opc, DL, MVT::i64, Op0, 6859 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6860 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6861 return; 6862 } 6863 // If the FP type needs to be softened, emit a library call using the 'si' 6864 // version. If we left it to default legalization we'd end up with 'di'. If 6865 // the FP type doesn't need to be softened just let generic type 6866 // legalization promote the result type. 6867 RTLIB::Libcall LC; 6868 if (IsSigned) 6869 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6870 else 6871 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6872 MakeLibCallOptions CallOptions; 6873 EVT OpVT = Op0.getValueType(); 6874 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6875 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6876 SDValue Result; 6877 std::tie(Result, Chain) = 6878 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6879 Results.push_back(Result); 6880 if (IsStrict) 6881 Results.push_back(Chain); 6882 break; 6883 } 6884 case ISD::READCYCLECOUNTER: { 6885 assert(!Subtarget.is64Bit() && 6886 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6887 6888 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6889 SDValue RCW = 6890 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6891 6892 Results.push_back( 6893 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6894 Results.push_back(RCW.getValue(2)); 6895 break; 6896 } 6897 case ISD::MUL: { 6898 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6899 unsigned XLen = Subtarget.getXLen(); 6900 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6901 if (Size > XLen) { 6902 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6903 SDValue LHS = N->getOperand(0); 6904 SDValue RHS = N->getOperand(1); 6905 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6906 6907 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6908 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6909 // We need exactly one side to be unsigned. 6910 if (LHSIsU == RHSIsU) 6911 return; 6912 6913 auto MakeMULPair = [&](SDValue S, SDValue U) { 6914 MVT XLenVT = Subtarget.getXLenVT(); 6915 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6916 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6917 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6918 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6919 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6920 }; 6921 6922 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6923 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6924 6925 // The other operand should be signed, but still prefer MULH when 6926 // possible. 6927 if (RHSIsU && LHSIsS && !RHSIsS) 6928 Results.push_back(MakeMULPair(LHS, RHS)); 6929 else if (LHSIsU && RHSIsS && !LHSIsS) 6930 Results.push_back(MakeMULPair(RHS, LHS)); 6931 6932 return; 6933 } 6934 LLVM_FALLTHROUGH; 6935 } 6936 case ISD::ADD: 6937 case ISD::SUB: 6938 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6939 "Unexpected custom legalisation"); 6940 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6941 break; 6942 case ISD::SHL: 6943 case ISD::SRA: 6944 case ISD::SRL: 6945 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6946 "Unexpected custom legalisation"); 6947 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6948 // If we can use a BSET instruction, allow default promotion to apply. 6949 if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() && 6950 isOneConstant(N->getOperand(0))) 6951 break; 6952 Results.push_back(customLegalizeToWOp(N, DAG)); 6953 break; 6954 } 6955 6956 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6957 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6958 // shift amount. 6959 if (N->getOpcode() == ISD::SHL) { 6960 SDLoc DL(N); 6961 SDValue NewOp0 = 6962 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6963 SDValue NewOp1 = 6964 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6965 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6966 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6967 DAG.getValueType(MVT::i32)); 6968 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6969 } 6970 6971 break; 6972 case ISD::ROTL: 6973 case ISD::ROTR: 6974 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6975 "Unexpected custom legalisation"); 6976 Results.push_back(customLegalizeToWOp(N, DAG)); 6977 break; 6978 case ISD::CTTZ: 6979 case ISD::CTTZ_ZERO_UNDEF: 6980 case ISD::CTLZ: 6981 case ISD::CTLZ_ZERO_UNDEF: { 6982 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6983 "Unexpected custom legalisation"); 6984 6985 SDValue NewOp0 = 6986 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6987 bool IsCTZ = 6988 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6989 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6990 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6991 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6992 return; 6993 } 6994 case ISD::SDIV: 6995 case ISD::UDIV: 6996 case ISD::UREM: { 6997 MVT VT = N->getSimpleValueType(0); 6998 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6999 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 7000 "Unexpected custom legalisation"); 7001 // Don't promote division/remainder by constant since we should expand those 7002 // to multiply by magic constant. 7003 // FIXME: What if the expansion is disabled for minsize. 7004 if (N->getOperand(1).getOpcode() == ISD::Constant) 7005 return; 7006 7007 // If the input is i32, use ANY_EXTEND since the W instructions don't read 7008 // the upper 32 bits. For other types we need to sign or zero extend 7009 // based on the opcode. 7010 unsigned ExtOpc = ISD::ANY_EXTEND; 7011 if (VT != MVT::i32) 7012 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 7013 : ISD::ZERO_EXTEND; 7014 7015 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 7016 break; 7017 } 7018 case ISD::UADDO: 7019 case ISD::USUBO: { 7020 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7021 "Unexpected custom legalisation"); 7022 bool IsAdd = N->getOpcode() == ISD::UADDO; 7023 // Create an ADDW or SUBW. 7024 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7025 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7026 SDValue Res = 7027 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 7028 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 7029 DAG.getValueType(MVT::i32)); 7030 7031 SDValue Overflow; 7032 if (IsAdd && isOneConstant(RHS)) { 7033 // Special case uaddo X, 1 overflowed if the addition result is 0. 7034 // The general case (X + C) < C is not necessarily beneficial. Although we 7035 // reduce the live range of X, we may introduce the materialization of 7036 // constant C, especially when the setcc result is used by branch. We have 7037 // no compare with constant and branch instructions. 7038 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, 7039 DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ); 7040 } else { 7041 // Sign extend the LHS and perform an unsigned compare with the ADDW 7042 // result. Since the inputs are sign extended from i32, this is equivalent 7043 // to comparing the lower 32 bits. 7044 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 7045 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 7046 IsAdd ? ISD::SETULT : ISD::SETUGT); 7047 } 7048 7049 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7050 Results.push_back(Overflow); 7051 return; 7052 } 7053 case ISD::UADDSAT: 7054 case ISD::USUBSAT: { 7055 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7056 "Unexpected custom legalisation"); 7057 if (Subtarget.hasStdExtZbb()) { 7058 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 7059 // sign extend allows overflow of the lower 32 bits to be detected on 7060 // the promoted size. 7061 SDValue LHS = 7062 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 7063 SDValue RHS = 7064 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 7065 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 7066 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7067 return; 7068 } 7069 7070 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 7071 // promotion for UADDO/USUBO. 7072 Results.push_back(expandAddSubSat(N, DAG)); 7073 return; 7074 } 7075 case ISD::ABS: { 7076 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7077 "Unexpected custom legalisation"); 7078 7079 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 7080 7081 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7082 7083 // Freeze the source so we can increase it's use count. 7084 Src = DAG.getFreeze(Src); 7085 7086 // Copy sign bit to all bits using the sraiw pattern. 7087 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 7088 DAG.getValueType(MVT::i32)); 7089 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 7090 DAG.getConstant(31, DL, MVT::i64)); 7091 7092 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 7093 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 7094 7095 // NOTE: The result is only required to be anyextended, but sext is 7096 // consistent with type legalization of sub. 7097 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 7098 DAG.getValueType(MVT::i32)); 7099 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 7100 return; 7101 } 7102 case ISD::BITCAST: { 7103 EVT VT = N->getValueType(0); 7104 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 7105 SDValue Op0 = N->getOperand(0); 7106 EVT Op0VT = Op0.getValueType(); 7107 MVT XLenVT = Subtarget.getXLenVT(); 7108 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 7109 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 7110 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 7111 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 7112 Subtarget.hasStdExtF()) { 7113 SDValue FPConv = 7114 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 7115 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 7116 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 7117 isTypeLegal(Op0VT)) { 7118 // Custom-legalize bitcasts from fixed-length vector types to illegal 7119 // scalar types in order to improve codegen. Bitcast the vector to a 7120 // one-element vector type whose element type is the same as the result 7121 // type, and extract the first element. 7122 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 7123 if (isTypeLegal(BVT)) { 7124 SDValue BVec = DAG.getBitcast(BVT, Op0); 7125 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 7126 DAG.getConstant(0, DL, XLenVT))); 7127 } 7128 } 7129 break; 7130 } 7131 case RISCVISD::GREV: 7132 case RISCVISD::GORC: 7133 case RISCVISD::SHFL: { 7134 MVT VT = N->getSimpleValueType(0); 7135 MVT XLenVT = Subtarget.getXLenVT(); 7136 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) && 7137 "Unexpected custom legalisation"); 7138 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 7139 assert((Subtarget.hasStdExtZbp() || 7140 (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV && 7141 N->getConstantOperandVal(1) == 7)) && 7142 "Unexpected extension"); 7143 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7144 SDValue NewOp1 = 7145 DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1)); 7146 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1); 7147 // ReplaceNodeResults requires we maintain the same type for the return 7148 // value. 7149 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes)); 7150 break; 7151 } 7152 case ISD::BSWAP: 7153 case ISD::BITREVERSE: { 7154 MVT VT = N->getSimpleValueType(0); 7155 MVT XLenVT = Subtarget.getXLenVT(); 7156 assert((VT == MVT::i8 || VT == MVT::i16 || 7157 (VT == MVT::i32 && Subtarget.is64Bit())) && 7158 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 7159 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7160 unsigned Imm = VT.getSizeInBits() - 1; 7161 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 7162 if (N->getOpcode() == ISD::BSWAP) 7163 Imm &= ~0x7U; 7164 SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0, 7165 DAG.getConstant(Imm, DL, XLenVT)); 7166 // ReplaceNodeResults requires we maintain the same type for the return 7167 // value. 7168 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 7169 break; 7170 } 7171 case ISD::FSHL: 7172 case ISD::FSHR: { 7173 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7174 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 7175 SDValue NewOp0 = 7176 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7177 SDValue NewOp1 = 7178 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7179 SDValue NewShAmt = 7180 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7181 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 7182 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 7183 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 7184 DAG.getConstant(0x1f, DL, MVT::i64)); 7185 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 7186 // instruction use different orders. fshl will return its first operand for 7187 // shift of zero, fshr will return its second operand. fsl and fsr both 7188 // return rs1 so the ISD nodes need to have different operand orders. 7189 // Shift amount is in rs2. 7190 unsigned Opc = RISCVISD::FSLW; 7191 if (N->getOpcode() == ISD::FSHR) { 7192 std::swap(NewOp0, NewOp1); 7193 Opc = RISCVISD::FSRW; 7194 } 7195 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 7196 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 7197 break; 7198 } 7199 case ISD::EXTRACT_VECTOR_ELT: { 7200 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 7201 // type is illegal (currently only vXi64 RV32). 7202 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 7203 // transferred to the destination register. We issue two of these from the 7204 // upper- and lower- halves of the SEW-bit vector element, slid down to the 7205 // first element. 7206 SDValue Vec = N->getOperand(0); 7207 SDValue Idx = N->getOperand(1); 7208 7209 // The vector type hasn't been legalized yet so we can't issue target 7210 // specific nodes if it needs legalization. 7211 // FIXME: We would manually legalize if it's important. 7212 if (!isTypeLegal(Vec.getValueType())) 7213 return; 7214 7215 MVT VecVT = Vec.getSimpleValueType(); 7216 7217 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 7218 VecVT.getVectorElementType() == MVT::i64 && 7219 "Unexpected EXTRACT_VECTOR_ELT legalization"); 7220 7221 // If this is a fixed vector, we need to convert it to a scalable vector. 7222 MVT ContainerVT = VecVT; 7223 if (VecVT.isFixedLengthVector()) { 7224 ContainerVT = getContainerForFixedLengthVector(VecVT); 7225 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 7226 } 7227 7228 MVT XLenVT = Subtarget.getXLenVT(); 7229 7230 // Use a VL of 1 to avoid processing more elements than we need. 7231 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7232 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 7233 7234 // Unless the index is known to be 0, we must slide the vector down to get 7235 // the desired element into index 0. 7236 if (!isNullConstant(Idx)) { 7237 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 7238 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 7239 } 7240 7241 // Extract the lower XLEN bits of the correct vector element. 7242 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7243 7244 // To extract the upper XLEN bits of the vector element, shift the first 7245 // element right by 32 bits and re-extract the lower XLEN bits. 7246 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 7247 DAG.getUNDEF(ContainerVT), 7248 DAG.getConstant(32, DL, XLenVT), VL); 7249 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 7250 ThirtyTwoV, Mask, VL); 7251 7252 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7253 7254 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7255 break; 7256 } 7257 case ISD::INTRINSIC_WO_CHAIN: { 7258 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7259 switch (IntNo) { 7260 default: 7261 llvm_unreachable( 7262 "Don't know how to custom type legalize this intrinsic!"); 7263 case Intrinsic::riscv_grev: 7264 case Intrinsic::riscv_gorc: { 7265 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7266 "Unexpected custom legalisation"); 7267 SDValue NewOp1 = 7268 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7269 SDValue NewOp2 = 7270 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7271 unsigned Opc = 7272 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 7273 // If the control is a constant, promote the node by clearing any extra 7274 // bits bits in the control. isel will form greviw/gorciw if the result is 7275 // sign extended. 7276 if (isa<ConstantSDNode>(NewOp2)) { 7277 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7278 DAG.getConstant(0x1f, DL, MVT::i64)); 7279 Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 7280 } 7281 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7282 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7283 break; 7284 } 7285 case Intrinsic::riscv_bcompress: 7286 case Intrinsic::riscv_bdecompress: 7287 case Intrinsic::riscv_bfp: 7288 case Intrinsic::riscv_fsl: 7289 case Intrinsic::riscv_fsr: { 7290 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7291 "Unexpected custom legalisation"); 7292 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 7293 break; 7294 } 7295 case Intrinsic::riscv_orc_b: { 7296 // Lower to the GORCI encoding for orc.b with the operand extended. 7297 SDValue NewOp = 7298 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7299 SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp, 7300 DAG.getConstant(7, DL, MVT::i64)); 7301 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7302 return; 7303 } 7304 case Intrinsic::riscv_shfl: 7305 case Intrinsic::riscv_unshfl: { 7306 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7307 "Unexpected custom legalisation"); 7308 SDValue NewOp1 = 7309 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7310 SDValue NewOp2 = 7311 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7312 unsigned Opc = 7313 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 7314 // There is no (UN)SHFLIW. If the control word is a constant, we can use 7315 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 7316 // will be shuffled the same way as the lower 32 bit half, but the two 7317 // halves won't cross. 7318 if (isa<ConstantSDNode>(NewOp2)) { 7319 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7320 DAG.getConstant(0xf, DL, MVT::i64)); 7321 Opc = 7322 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 7323 } 7324 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7325 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7326 break; 7327 } 7328 case Intrinsic::riscv_vmv_x_s: { 7329 EVT VT = N->getValueType(0); 7330 MVT XLenVT = Subtarget.getXLenVT(); 7331 if (VT.bitsLT(XLenVT)) { 7332 // Simple case just extract using vmv.x.s and truncate. 7333 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 7334 Subtarget.getXLenVT(), N->getOperand(1)); 7335 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 7336 return; 7337 } 7338 7339 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 7340 "Unexpected custom legalization"); 7341 7342 // We need to do the move in two steps. 7343 SDValue Vec = N->getOperand(1); 7344 MVT VecVT = Vec.getSimpleValueType(); 7345 7346 // First extract the lower XLEN bits of the element. 7347 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7348 7349 // To extract the upper XLEN bits of the vector element, shift the first 7350 // element right by 32 bits and re-extract the lower XLEN bits. 7351 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7352 SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG); 7353 7354 SDValue ThirtyTwoV = 7355 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 7356 DAG.getConstant(32, DL, XLenVT), VL); 7357 SDValue LShr32 = 7358 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 7359 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7360 7361 Results.push_back( 7362 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7363 break; 7364 } 7365 } 7366 break; 7367 } 7368 case ISD::VECREDUCE_ADD: 7369 case ISD::VECREDUCE_AND: 7370 case ISD::VECREDUCE_OR: 7371 case ISD::VECREDUCE_XOR: 7372 case ISD::VECREDUCE_SMAX: 7373 case ISD::VECREDUCE_UMAX: 7374 case ISD::VECREDUCE_SMIN: 7375 case ISD::VECREDUCE_UMIN: 7376 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 7377 Results.push_back(V); 7378 break; 7379 case ISD::VP_REDUCE_ADD: 7380 case ISD::VP_REDUCE_AND: 7381 case ISD::VP_REDUCE_OR: 7382 case ISD::VP_REDUCE_XOR: 7383 case ISD::VP_REDUCE_SMAX: 7384 case ISD::VP_REDUCE_UMAX: 7385 case ISD::VP_REDUCE_SMIN: 7386 case ISD::VP_REDUCE_UMIN: 7387 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 7388 Results.push_back(V); 7389 break; 7390 case ISD::FLT_ROUNDS_: { 7391 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7392 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7393 Results.push_back(Res.getValue(0)); 7394 Results.push_back(Res.getValue(1)); 7395 break; 7396 } 7397 } 7398 } 7399 7400 // A structure to hold one of the bit-manipulation patterns below. Together, a 7401 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7402 // (or (and (shl x, 1), 0xAAAAAAAA), 7403 // (and (srl x, 1), 0x55555555)) 7404 struct RISCVBitmanipPat { 7405 SDValue Op; 7406 unsigned ShAmt; 7407 bool IsSHL; 7408 7409 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7410 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7411 } 7412 }; 7413 7414 // Matches patterns of the form 7415 // (and (shl x, C2), (C1 << C2)) 7416 // (and (srl x, C2), C1) 7417 // (shl (and x, C1), C2) 7418 // (srl (and x, (C1 << C2)), C2) 7419 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7420 // The expected masks for each shift amount are specified in BitmanipMasks where 7421 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7422 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7423 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7424 // XLen is 64. 7425 static Optional<RISCVBitmanipPat> 7426 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7427 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7428 "Unexpected number of masks"); 7429 Optional<uint64_t> Mask; 7430 // Optionally consume a mask around the shift operation. 7431 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7432 Mask = Op.getConstantOperandVal(1); 7433 Op = Op.getOperand(0); 7434 } 7435 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7436 return None; 7437 bool IsSHL = Op.getOpcode() == ISD::SHL; 7438 7439 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7440 return None; 7441 uint64_t ShAmt = Op.getConstantOperandVal(1); 7442 7443 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7444 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7445 return None; 7446 // If we don't have enough masks for 64 bit, then we must be trying to 7447 // match SHFL so we're only allowed to shift 1/4 of the width. 7448 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7449 return None; 7450 7451 SDValue Src = Op.getOperand(0); 7452 7453 // The expected mask is shifted left when the AND is found around SHL 7454 // patterns. 7455 // ((x >> 1) & 0x55555555) 7456 // ((x << 1) & 0xAAAAAAAA) 7457 bool SHLExpMask = IsSHL; 7458 7459 if (!Mask) { 7460 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7461 // the mask is all ones: consume that now. 7462 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7463 Mask = Src.getConstantOperandVal(1); 7464 Src = Src.getOperand(0); 7465 // The expected mask is now in fact shifted left for SRL, so reverse the 7466 // decision. 7467 // ((x & 0xAAAAAAAA) >> 1) 7468 // ((x & 0x55555555) << 1) 7469 SHLExpMask = !SHLExpMask; 7470 } else { 7471 // Use a default shifted mask of all-ones if there's no AND, truncated 7472 // down to the expected width. This simplifies the logic later on. 7473 Mask = maskTrailingOnes<uint64_t>(Width); 7474 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7475 } 7476 } 7477 7478 unsigned MaskIdx = Log2_32(ShAmt); 7479 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7480 7481 if (SHLExpMask) 7482 ExpMask <<= ShAmt; 7483 7484 if (Mask != ExpMask) 7485 return None; 7486 7487 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7488 } 7489 7490 // Matches any of the following bit-manipulation patterns: 7491 // (and (shl x, 1), (0x55555555 << 1)) 7492 // (and (srl x, 1), 0x55555555) 7493 // (shl (and x, 0x55555555), 1) 7494 // (srl (and x, (0x55555555 << 1)), 1) 7495 // where the shift amount and mask may vary thus: 7496 // [1] = 0x55555555 / 0xAAAAAAAA 7497 // [2] = 0x33333333 / 0xCCCCCCCC 7498 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7499 // [8] = 0x00FF00FF / 0xFF00FF00 7500 // [16] = 0x0000FFFF / 0xFFFFFFFF 7501 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7502 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7503 // These are the unshifted masks which we use to match bit-manipulation 7504 // patterns. They may be shifted left in certain circumstances. 7505 static const uint64_t BitmanipMasks[] = { 7506 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7507 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7508 7509 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7510 } 7511 7512 // Try to fold (<bop> x, (reduction.<bop> vec, start)) 7513 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) { 7514 auto BinOpToRVVReduce = [](unsigned Opc) { 7515 switch (Opc) { 7516 default: 7517 llvm_unreachable("Unhandled binary to transfrom reduction"); 7518 case ISD::ADD: 7519 return RISCVISD::VECREDUCE_ADD_VL; 7520 case ISD::UMAX: 7521 return RISCVISD::VECREDUCE_UMAX_VL; 7522 case ISD::SMAX: 7523 return RISCVISD::VECREDUCE_SMAX_VL; 7524 case ISD::UMIN: 7525 return RISCVISD::VECREDUCE_UMIN_VL; 7526 case ISD::SMIN: 7527 return RISCVISD::VECREDUCE_SMIN_VL; 7528 case ISD::AND: 7529 return RISCVISD::VECREDUCE_AND_VL; 7530 case ISD::OR: 7531 return RISCVISD::VECREDUCE_OR_VL; 7532 case ISD::XOR: 7533 return RISCVISD::VECREDUCE_XOR_VL; 7534 case ISD::FADD: 7535 return RISCVISD::VECREDUCE_FADD_VL; 7536 case ISD::FMAXNUM: 7537 return RISCVISD::VECREDUCE_FMAX_VL; 7538 case ISD::FMINNUM: 7539 return RISCVISD::VECREDUCE_FMIN_VL; 7540 } 7541 }; 7542 7543 auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) { 7544 return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7545 isNullConstant(V.getOperand(1)) && 7546 V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc); 7547 }; 7548 7549 unsigned Opc = N->getOpcode(); 7550 unsigned ReduceIdx; 7551 if (IsReduction(N->getOperand(0), Opc)) 7552 ReduceIdx = 0; 7553 else if (IsReduction(N->getOperand(1), Opc)) 7554 ReduceIdx = 1; 7555 else 7556 return SDValue(); 7557 7558 // Skip if FADD disallows reassociation but the combiner needs. 7559 if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation()) 7560 return SDValue(); 7561 7562 SDValue Extract = N->getOperand(ReduceIdx); 7563 SDValue Reduce = Extract.getOperand(0); 7564 if (!Reduce.hasOneUse()) 7565 return SDValue(); 7566 7567 SDValue ScalarV = Reduce.getOperand(2); 7568 7569 // Make sure that ScalarV is a splat with VL=1. 7570 if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL && 7571 ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL && 7572 ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL) 7573 return SDValue(); 7574 7575 if (!isOneConstant(ScalarV.getOperand(2))) 7576 return SDValue(); 7577 7578 // TODO: Deal with value other than neutral element. 7579 auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) { 7580 if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() && 7581 isNullFPConstant(V)) 7582 return true; 7583 return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(), 7584 N->getFlags()) == V; 7585 }; 7586 7587 // Check the scalar of ScalarV is neutral element 7588 if (!IsRVVNeutralElement(N, ScalarV.getOperand(1))) 7589 return SDValue(); 7590 7591 if (!ScalarV.hasOneUse()) 7592 return SDValue(); 7593 7594 EVT SplatVT = ScalarV.getValueType(); 7595 SDValue NewStart = N->getOperand(1 - ReduceIdx); 7596 unsigned SplatOpc = RISCVISD::VFMV_S_F_VL; 7597 if (SplatVT.isInteger()) { 7598 auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode()); 7599 if (!C || C->isZero() || !isInt<5>(C->getSExtValue())) 7600 SplatOpc = RISCVISD::VMV_S_X_VL; 7601 else 7602 SplatOpc = RISCVISD::VMV_V_X_VL; 7603 } 7604 7605 SDValue NewScalarV = 7606 DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart, 7607 ScalarV.getOperand(2)); 7608 SDValue NewReduce = 7609 DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(), 7610 Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV, 7611 Reduce.getOperand(3), Reduce.getOperand(4)); 7612 return DAG.getNode(Extract.getOpcode(), SDLoc(Extract), 7613 Extract.getValueType(), NewReduce, Extract.getOperand(1)); 7614 } 7615 7616 // Match the following pattern as a GREVI(W) operation 7617 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7618 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7619 const RISCVSubtarget &Subtarget) { 7620 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7621 EVT VT = Op.getValueType(); 7622 7623 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7624 auto LHS = matchGREVIPat(Op.getOperand(0)); 7625 auto RHS = matchGREVIPat(Op.getOperand(1)); 7626 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7627 SDLoc DL(Op); 7628 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7629 DAG.getConstant(LHS->ShAmt, DL, VT)); 7630 } 7631 } 7632 return SDValue(); 7633 } 7634 7635 // Matches any the following pattern as a GORCI(W) operation 7636 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7637 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7638 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7639 // Note that with the variant of 3., 7640 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7641 // the inner pattern will first be matched as GREVI and then the outer 7642 // pattern will be matched to GORC via the first rule above. 7643 // 4. (or (rotl/rotr x, bitwidth/2), x) 7644 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7645 const RISCVSubtarget &Subtarget) { 7646 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7647 EVT VT = Op.getValueType(); 7648 7649 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7650 SDLoc DL(Op); 7651 SDValue Op0 = Op.getOperand(0); 7652 SDValue Op1 = Op.getOperand(1); 7653 7654 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7655 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7656 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7657 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7658 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7659 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7660 if ((Reverse.getOpcode() == ISD::ROTL || 7661 Reverse.getOpcode() == ISD::ROTR) && 7662 Reverse.getOperand(0) == X && 7663 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7664 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7665 if (RotAmt == (VT.getSizeInBits() / 2)) 7666 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7667 DAG.getConstant(RotAmt, DL, VT)); 7668 } 7669 return SDValue(); 7670 }; 7671 7672 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7673 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7674 return V; 7675 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7676 return V; 7677 7678 // OR is commutable so canonicalize its OR operand to the left 7679 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7680 std::swap(Op0, Op1); 7681 if (Op0.getOpcode() != ISD::OR) 7682 return SDValue(); 7683 SDValue OrOp0 = Op0.getOperand(0); 7684 SDValue OrOp1 = Op0.getOperand(1); 7685 auto LHS = matchGREVIPat(OrOp0); 7686 // OR is commutable so swap the operands and try again: x might have been 7687 // on the left 7688 if (!LHS) { 7689 std::swap(OrOp0, OrOp1); 7690 LHS = matchGREVIPat(OrOp0); 7691 } 7692 auto RHS = matchGREVIPat(Op1); 7693 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7694 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7695 DAG.getConstant(LHS->ShAmt, DL, VT)); 7696 } 7697 } 7698 return SDValue(); 7699 } 7700 7701 // Matches any of the following bit-manipulation patterns: 7702 // (and (shl x, 1), (0x22222222 << 1)) 7703 // (and (srl x, 1), 0x22222222) 7704 // (shl (and x, 0x22222222), 1) 7705 // (srl (and x, (0x22222222 << 1)), 1) 7706 // where the shift amount and mask may vary thus: 7707 // [1] = 0x22222222 / 0x44444444 7708 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7709 // [4] = 0x00F000F0 / 0x0F000F00 7710 // [8] = 0x0000FF00 / 0x00FF0000 7711 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7712 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7713 // These are the unshifted masks which we use to match bit-manipulation 7714 // patterns. They may be shifted left in certain circumstances. 7715 static const uint64_t BitmanipMasks[] = { 7716 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7717 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7718 7719 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7720 } 7721 7722 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7723 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7724 const RISCVSubtarget &Subtarget) { 7725 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7726 EVT VT = Op.getValueType(); 7727 7728 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7729 return SDValue(); 7730 7731 SDValue Op0 = Op.getOperand(0); 7732 SDValue Op1 = Op.getOperand(1); 7733 7734 // Or is commutable so canonicalize the second OR to the LHS. 7735 if (Op0.getOpcode() != ISD::OR) 7736 std::swap(Op0, Op1); 7737 if (Op0.getOpcode() != ISD::OR) 7738 return SDValue(); 7739 7740 // We found an inner OR, so our operands are the operands of the inner OR 7741 // and the other operand of the outer OR. 7742 SDValue A = Op0.getOperand(0); 7743 SDValue B = Op0.getOperand(1); 7744 SDValue C = Op1; 7745 7746 auto Match1 = matchSHFLPat(A); 7747 auto Match2 = matchSHFLPat(B); 7748 7749 // If neither matched, we failed. 7750 if (!Match1 && !Match2) 7751 return SDValue(); 7752 7753 // We had at least one match. if one failed, try the remaining C operand. 7754 if (!Match1) { 7755 std::swap(A, C); 7756 Match1 = matchSHFLPat(A); 7757 if (!Match1) 7758 return SDValue(); 7759 } else if (!Match2) { 7760 std::swap(B, C); 7761 Match2 = matchSHFLPat(B); 7762 if (!Match2) 7763 return SDValue(); 7764 } 7765 assert(Match1 && Match2); 7766 7767 // Make sure our matches pair up. 7768 if (!Match1->formsPairWith(*Match2)) 7769 return SDValue(); 7770 7771 // All the remains is to make sure C is an AND with the same input, that masks 7772 // out the bits that are being shuffled. 7773 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7774 C.getOperand(0) != Match1->Op) 7775 return SDValue(); 7776 7777 uint64_t Mask = C.getConstantOperandVal(1); 7778 7779 static const uint64_t BitmanipMasks[] = { 7780 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7781 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7782 }; 7783 7784 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7785 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7786 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7787 7788 if (Mask != ExpMask) 7789 return SDValue(); 7790 7791 SDLoc DL(Op); 7792 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7793 DAG.getConstant(Match1->ShAmt, DL, VT)); 7794 } 7795 7796 // Optimize (add (shl x, c0), (shl y, c1)) -> 7797 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7798 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7799 const RISCVSubtarget &Subtarget) { 7800 // Perform this optimization only in the zba extension. 7801 if (!Subtarget.hasStdExtZba()) 7802 return SDValue(); 7803 7804 // Skip for vector types and larger types. 7805 EVT VT = N->getValueType(0); 7806 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7807 return SDValue(); 7808 7809 // The two operand nodes must be SHL and have no other use. 7810 SDValue N0 = N->getOperand(0); 7811 SDValue N1 = N->getOperand(1); 7812 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7813 !N0->hasOneUse() || !N1->hasOneUse()) 7814 return SDValue(); 7815 7816 // Check c0 and c1. 7817 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7818 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7819 if (!N0C || !N1C) 7820 return SDValue(); 7821 int64_t C0 = N0C->getSExtValue(); 7822 int64_t C1 = N1C->getSExtValue(); 7823 if (C0 <= 0 || C1 <= 0) 7824 return SDValue(); 7825 7826 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7827 int64_t Bits = std::min(C0, C1); 7828 int64_t Diff = std::abs(C0 - C1); 7829 if (Diff != 1 && Diff != 2 && Diff != 3) 7830 return SDValue(); 7831 7832 // Build nodes. 7833 SDLoc DL(N); 7834 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7835 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7836 SDValue NA0 = 7837 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7838 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7839 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7840 } 7841 7842 // Combine 7843 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7844 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7845 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7846 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7847 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7848 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7849 // The grev patterns represents BSWAP. 7850 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7851 // off the grev. 7852 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7853 const RISCVSubtarget &Subtarget) { 7854 bool IsWInstruction = 7855 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7856 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7857 IsWInstruction) && 7858 "Unexpected opcode!"); 7859 SDValue Src = N->getOperand(0); 7860 EVT VT = N->getValueType(0); 7861 SDLoc DL(N); 7862 7863 if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV) 7864 return SDValue(); 7865 7866 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7867 !isa<ConstantSDNode>(Src.getOperand(1))) 7868 return SDValue(); 7869 7870 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7871 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7872 7873 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7874 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7875 unsigned ShAmt1 = N->getConstantOperandVal(1); 7876 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7877 if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7878 return SDValue(); 7879 7880 Src = Src.getOperand(0); 7881 7882 // Toggle bit the MSB of the shift. 7883 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7884 if (CombinedShAmt == 0) 7885 return Src; 7886 7887 SDValue Res = DAG.getNode( 7888 RISCVISD::GREV, DL, VT, Src, 7889 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7890 if (!IsWInstruction) 7891 return Res; 7892 7893 // Sign extend the result to match the behavior of the rotate. This will be 7894 // selected to GREVIW in isel. 7895 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res, 7896 DAG.getValueType(MVT::i32)); 7897 } 7898 7899 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7900 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7901 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7902 // not undo itself, but they are redundant. 7903 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7904 bool IsGORC = N->getOpcode() == RISCVISD::GORC; 7905 assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode"); 7906 SDValue Src = N->getOperand(0); 7907 7908 if (Src.getOpcode() != N->getOpcode()) 7909 return SDValue(); 7910 7911 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7912 !isa<ConstantSDNode>(Src.getOperand(1))) 7913 return SDValue(); 7914 7915 unsigned ShAmt1 = N->getConstantOperandVal(1); 7916 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7917 Src = Src.getOperand(0); 7918 7919 unsigned CombinedShAmt; 7920 if (IsGORC) 7921 CombinedShAmt = ShAmt1 | ShAmt2; 7922 else 7923 CombinedShAmt = ShAmt1 ^ ShAmt2; 7924 7925 if (CombinedShAmt == 0) 7926 return Src; 7927 7928 SDLoc DL(N); 7929 return DAG.getNode( 7930 N->getOpcode(), DL, N->getValueType(0), Src, 7931 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7932 } 7933 7934 // Combine a constant select operand into its use: 7935 // 7936 // (and (select cond, -1, c), x) 7937 // -> (select cond, x, (and x, c)) [AllOnes=1] 7938 // (or (select cond, 0, c), x) 7939 // -> (select cond, x, (or x, c)) [AllOnes=0] 7940 // (xor (select cond, 0, c), x) 7941 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7942 // (add (select cond, 0, c), x) 7943 // -> (select cond, x, (add x, c)) [AllOnes=0] 7944 // (sub x, (select cond, 0, c)) 7945 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7946 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7947 SelectionDAG &DAG, bool AllOnes) { 7948 EVT VT = N->getValueType(0); 7949 7950 // Skip vectors. 7951 if (VT.isVector()) 7952 return SDValue(); 7953 7954 if ((Slct.getOpcode() != ISD::SELECT && 7955 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7956 !Slct.hasOneUse()) 7957 return SDValue(); 7958 7959 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7960 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7961 }; 7962 7963 bool SwapSelectOps; 7964 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7965 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7966 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7967 SDValue NonConstantVal; 7968 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7969 SwapSelectOps = false; 7970 NonConstantVal = FalseVal; 7971 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7972 SwapSelectOps = true; 7973 NonConstantVal = TrueVal; 7974 } else 7975 return SDValue(); 7976 7977 // Slct is now know to be the desired identity constant when CC is true. 7978 TrueVal = OtherOp; 7979 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7980 // Unless SwapSelectOps says the condition should be false. 7981 if (SwapSelectOps) 7982 std::swap(TrueVal, FalseVal); 7983 7984 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7985 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7986 {Slct.getOperand(0), Slct.getOperand(1), 7987 Slct.getOperand(2), TrueVal, FalseVal}); 7988 7989 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7990 {Slct.getOperand(0), TrueVal, FalseVal}); 7991 } 7992 7993 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7994 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7995 bool AllOnes) { 7996 SDValue N0 = N->getOperand(0); 7997 SDValue N1 = N->getOperand(1); 7998 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7999 return Result; 8000 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 8001 return Result; 8002 return SDValue(); 8003 } 8004 8005 // Transform (add (mul x, c0), c1) -> 8006 // (add (mul (add x, c1/c0), c0), c1%c0). 8007 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 8008 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 8009 // to an infinite loop in DAGCombine if transformed. 8010 // Or transform (add (mul x, c0), c1) -> 8011 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 8012 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 8013 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 8014 // lead to an infinite loop in DAGCombine if transformed. 8015 // Or transform (add (mul x, c0), c1) -> 8016 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 8017 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 8018 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 8019 // lead to an infinite loop in DAGCombine if transformed. 8020 // Or transform (add (mul x, c0), c1) -> 8021 // (mul (add x, c1/c0), c0). 8022 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 8023 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 8024 const RISCVSubtarget &Subtarget) { 8025 // Skip for vector types and larger types. 8026 EVT VT = N->getValueType(0); 8027 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 8028 return SDValue(); 8029 // The first operand node must be a MUL and has no other use. 8030 SDValue N0 = N->getOperand(0); 8031 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 8032 return SDValue(); 8033 // Check if c0 and c1 match above conditions. 8034 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8035 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8036 if (!N0C || !N1C) 8037 return SDValue(); 8038 // If N0C has multiple uses it's possible one of the cases in 8039 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 8040 // in an infinite loop. 8041 if (!N0C->hasOneUse()) 8042 return SDValue(); 8043 int64_t C0 = N0C->getSExtValue(); 8044 int64_t C1 = N1C->getSExtValue(); 8045 int64_t CA, CB; 8046 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 8047 return SDValue(); 8048 // Search for proper CA (non-zero) and CB that both are simm12. 8049 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 8050 !isInt<12>(C0 * (C1 / C0))) { 8051 CA = C1 / C0; 8052 CB = C1 % C0; 8053 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 8054 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 8055 CA = C1 / C0 + 1; 8056 CB = C1 % C0 - C0; 8057 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 8058 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 8059 CA = C1 / C0 - 1; 8060 CB = C1 % C0 + C0; 8061 } else 8062 return SDValue(); 8063 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 8064 SDLoc DL(N); 8065 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 8066 DAG.getConstant(CA, DL, VT)); 8067 SDValue New1 = 8068 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 8069 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 8070 } 8071 8072 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 8073 const RISCVSubtarget &Subtarget) { 8074 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 8075 return V; 8076 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 8077 return V; 8078 if (SDValue V = combineBinOpToReduce(N, DAG)) 8079 return V; 8080 // fold (add (select lhs, rhs, cc, 0, y), x) -> 8081 // (select lhs, rhs, cc, x, (add x, y)) 8082 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8083 } 8084 8085 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 8086 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 8087 // (select lhs, rhs, cc, x, (sub x, y)) 8088 SDValue N0 = N->getOperand(0); 8089 SDValue N1 = N->getOperand(1); 8090 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 8091 } 8092 8093 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG, 8094 const RISCVSubtarget &Subtarget) { 8095 SDValue N0 = N->getOperand(0); 8096 // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero 8097 // extending X. This is safe since we only need the LSB after the shift and 8098 // shift amounts larger than 31 would produce poison. If we wait until 8099 // type legalization, we'll create RISCVISD::SRLW and we can't recover it 8100 // to use a BEXT instruction. 8101 if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() && 8102 N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) && 8103 N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) && 8104 N0.hasOneUse()) { 8105 SDLoc DL(N); 8106 SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0)); 8107 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1)); 8108 SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1); 8109 SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl, 8110 DAG.getConstant(1, DL, MVT::i64)); 8111 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And); 8112 } 8113 8114 if (SDValue V = combineBinOpToReduce(N, DAG)) 8115 return V; 8116 8117 // fold (and (select lhs, rhs, cc, -1, y), x) -> 8118 // (select lhs, rhs, cc, x, (and x, y)) 8119 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 8120 } 8121 8122 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 8123 const RISCVSubtarget &Subtarget) { 8124 if (Subtarget.hasStdExtZbp()) { 8125 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 8126 return GREV; 8127 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 8128 return GORC; 8129 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 8130 return SHFL; 8131 } 8132 8133 if (SDValue V = combineBinOpToReduce(N, DAG)) 8134 return V; 8135 // fold (or (select cond, 0, y), x) -> 8136 // (select cond, x, (or x, y)) 8137 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8138 } 8139 8140 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 8141 SDValue N0 = N->getOperand(0); 8142 SDValue N1 = N->getOperand(1); 8143 8144 // fold (xor (sllw 1, x), -1) -> (rolw ~1, x) 8145 // NOTE: Assumes ROL being legal means ROLW is legal. 8146 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8147 if (N0.getOpcode() == RISCVISD::SLLW && 8148 isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) && 8149 TLI.isOperationLegal(ISD::ROTL, MVT::i64)) { 8150 SDLoc DL(N); 8151 return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64, 8152 DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1)); 8153 } 8154 8155 if (SDValue V = combineBinOpToReduce(N, DAG)) 8156 return V; 8157 // fold (xor (select cond, 0, y), x) -> 8158 // (select cond, x, (xor x, y)) 8159 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8160 } 8161 8162 // Replace (seteq (i64 (and X, 0xffffffff)), C1) with 8163 // (seteq (i64 (sext_inreg (X, i32)), C1')) where C1' is C1 sign extended from 8164 // bit 31. Same for setne. C1' may be cheaper to materialize and the sext_inreg 8165 // can become a sext.w instead of a shift pair. 8166 static SDValue performSETCCCombine(SDNode *N, SelectionDAG &DAG, 8167 const RISCVSubtarget &Subtarget) { 8168 SDValue N0 = N->getOperand(0); 8169 SDValue N1 = N->getOperand(1); 8170 EVT VT = N->getValueType(0); 8171 EVT OpVT = N0.getValueType(); 8172 8173 if (OpVT != MVT::i64 || !Subtarget.is64Bit()) 8174 return SDValue(); 8175 8176 // RHS needs to be a constant. 8177 auto *N1C = dyn_cast<ConstantSDNode>(N1); 8178 if (!N1C) 8179 return SDValue(); 8180 8181 // LHS needs to be (and X, 0xffffffff). 8182 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse() || 8183 !isa<ConstantSDNode>(N0.getOperand(1)) || 8184 N0.getConstantOperandVal(1) != UINT64_C(0xffffffff)) 8185 return SDValue(); 8186 8187 // Looking for an equality compare. 8188 ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8189 if (!isIntEqualitySetCC(Cond)) 8190 return SDValue(); 8191 8192 const APInt &C1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 8193 8194 SDLoc dl(N); 8195 // If the constant is larger than 2^32 - 1 it is impossible for both sides 8196 // to be equal. 8197 if (C1.getActiveBits() > 32) 8198 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT); 8199 8200 SDValue SExtOp = DAG.getNode(ISD::SIGN_EXTEND_INREG, N, OpVT, 8201 N0.getOperand(0), DAG.getValueType(MVT::i32)); 8202 return DAG.getSetCC(dl, VT, SExtOp, DAG.getConstant(C1.trunc(32).sext(64), 8203 dl, OpVT), Cond); 8204 } 8205 8206 static SDValue 8207 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 8208 const RISCVSubtarget &Subtarget) { 8209 SDValue Src = N->getOperand(0); 8210 EVT VT = N->getValueType(0); 8211 8212 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 8213 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8214 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 8215 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 8216 Src.getOperand(0)); 8217 8218 // Fold (i64 (sext_inreg (abs X), i32)) -> 8219 // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits. 8220 // The (sext_inreg (neg X), i32) will be selected to negw by isel. This 8221 // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user 8222 // of the (i32 (abs X)) is a sext or setcc or something else that causes type 8223 // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have 8224 // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg 8225 // may get combined into an earlier operation so we need to use 8226 // ComputeNumSignBits. 8227 // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for 8228 // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so 8229 // we can't assume that X has 33 sign bits. We must check. 8230 if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() && 8231 Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 && 8232 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 && 8233 DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) { 8234 SDLoc DL(N); 8235 SDValue Freeze = DAG.getFreeze(Src.getOperand(0)); 8236 SDValue Neg = 8237 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze); 8238 Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg, 8239 DAG.getValueType(MVT::i32)); 8240 return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg); 8241 } 8242 8243 return SDValue(); 8244 } 8245 8246 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 8247 // vwadd(u).vv/vx or vwsub(u).vv/vx. 8248 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 8249 bool Commute = false) { 8250 assert((N->getOpcode() == RISCVISD::ADD_VL || 8251 N->getOpcode() == RISCVISD::SUB_VL) && 8252 "Unexpected opcode"); 8253 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 8254 SDValue Op0 = N->getOperand(0); 8255 SDValue Op1 = N->getOperand(1); 8256 if (Commute) 8257 std::swap(Op0, Op1); 8258 8259 MVT VT = N->getSimpleValueType(0); 8260 8261 // Determine the narrow size for a widening add/sub. 8262 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8263 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8264 VT.getVectorElementCount()); 8265 8266 SDValue Mask = N->getOperand(2); 8267 SDValue VL = N->getOperand(3); 8268 8269 SDLoc DL(N); 8270 8271 // If the RHS is a sext or zext, we can form a widening op. 8272 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 8273 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 8274 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 8275 unsigned ExtOpc = Op1.getOpcode(); 8276 Op1 = Op1.getOperand(0); 8277 // Re-introduce narrower extends if needed. 8278 if (Op1.getValueType() != NarrowVT) 8279 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8280 8281 unsigned WOpc; 8282 if (ExtOpc == RISCVISD::VSEXT_VL) 8283 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 8284 else 8285 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 8286 8287 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 8288 } 8289 8290 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 8291 // sext/zext? 8292 8293 return SDValue(); 8294 } 8295 8296 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 8297 // vwsub(u).vv/vx. 8298 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 8299 SDValue Op0 = N->getOperand(0); 8300 SDValue Op1 = N->getOperand(1); 8301 SDValue Mask = N->getOperand(2); 8302 SDValue VL = N->getOperand(3); 8303 8304 MVT VT = N->getSimpleValueType(0); 8305 MVT NarrowVT = Op1.getSimpleValueType(); 8306 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 8307 8308 unsigned VOpc; 8309 switch (N->getOpcode()) { 8310 default: llvm_unreachable("Unexpected opcode"); 8311 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 8312 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 8313 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 8314 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 8315 } 8316 8317 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 8318 N->getOpcode() == RISCVISD::VWSUB_W_VL; 8319 8320 SDLoc DL(N); 8321 8322 // If the LHS is a sext or zext, we can narrow this op to the same size as 8323 // the RHS. 8324 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 8325 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 8326 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 8327 unsigned ExtOpc = Op0.getOpcode(); 8328 Op0 = Op0.getOperand(0); 8329 // Re-introduce narrower extends if needed. 8330 if (Op0.getValueType() != NarrowVT) 8331 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8332 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 8333 } 8334 8335 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 8336 N->getOpcode() == RISCVISD::VWADDU_W_VL; 8337 8338 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 8339 // to commute and use a vwadd(u).vx instead. 8340 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 8341 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 8342 Op0 = Op0.getOperand(1); 8343 8344 // See if have enough sign bits or zero bits in the scalar to use a 8345 // widening add/sub by splatting to smaller element size. 8346 unsigned EltBits = VT.getScalarSizeInBits(); 8347 unsigned ScalarBits = Op0.getValueSizeInBits(); 8348 // Make sure we're getting all element bits from the scalar register. 8349 // FIXME: Support implicit sign extension of vmv.v.x? 8350 if (ScalarBits < EltBits) 8351 return SDValue(); 8352 8353 if (IsSigned) { 8354 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 8355 return SDValue(); 8356 } else { 8357 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8358 if (!DAG.MaskedValueIsZero(Op0, Mask)) 8359 return SDValue(); 8360 } 8361 8362 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8363 DAG.getUNDEF(NarrowVT), Op0, VL); 8364 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 8365 } 8366 8367 return SDValue(); 8368 } 8369 8370 // Try to form VWMUL, VWMULU or VWMULSU. 8371 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 8372 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 8373 bool Commute) { 8374 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 8375 SDValue Op0 = N->getOperand(0); 8376 SDValue Op1 = N->getOperand(1); 8377 if (Commute) 8378 std::swap(Op0, Op1); 8379 8380 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 8381 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 8382 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 8383 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 8384 return SDValue(); 8385 8386 SDValue Mask = N->getOperand(2); 8387 SDValue VL = N->getOperand(3); 8388 8389 // Make sure the mask and VL match. 8390 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 8391 return SDValue(); 8392 8393 MVT VT = N->getSimpleValueType(0); 8394 8395 // Determine the narrow size for a widening multiply. 8396 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8397 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8398 VT.getVectorElementCount()); 8399 8400 SDLoc DL(N); 8401 8402 // See if the other operand is the same opcode. 8403 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 8404 if (!Op1.hasOneUse()) 8405 return SDValue(); 8406 8407 // Make sure the mask and VL match. 8408 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 8409 return SDValue(); 8410 8411 Op1 = Op1.getOperand(0); 8412 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 8413 // The operand is a splat of a scalar. 8414 8415 // The pasthru must be undef for tail agnostic 8416 if (!Op1.getOperand(0).isUndef()) 8417 return SDValue(); 8418 // The VL must be the same. 8419 if (Op1.getOperand(2) != VL) 8420 return SDValue(); 8421 8422 // Get the scalar value. 8423 Op1 = Op1.getOperand(1); 8424 8425 // See if have enough sign bits or zero bits in the scalar to use a 8426 // widening multiply by splatting to smaller element size. 8427 unsigned EltBits = VT.getScalarSizeInBits(); 8428 unsigned ScalarBits = Op1.getValueSizeInBits(); 8429 // Make sure we're getting all element bits from the scalar register. 8430 // FIXME: Support implicit sign extension of vmv.v.x? 8431 if (ScalarBits < EltBits) 8432 return SDValue(); 8433 8434 // If the LHS is a sign extend, try to use vwmul. 8435 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 8436 // Can use vwmul. 8437 } else { 8438 // Otherwise try to use vwmulu or vwmulsu. 8439 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8440 if (DAG.MaskedValueIsZero(Op1, Mask)) 8441 IsVWMULSU = IsSignExt; 8442 else 8443 return SDValue(); 8444 } 8445 8446 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8447 DAG.getUNDEF(NarrowVT), Op1, VL); 8448 } else 8449 return SDValue(); 8450 8451 Op0 = Op0.getOperand(0); 8452 8453 // Re-introduce narrower extends if needed. 8454 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 8455 if (Op0.getValueType() != NarrowVT) 8456 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8457 // vwmulsu requires second operand to be zero extended. 8458 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 8459 if (Op1.getValueType() != NarrowVT) 8460 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8461 8462 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 8463 if (!IsVWMULSU) 8464 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 8465 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 8466 } 8467 8468 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 8469 switch (Op.getOpcode()) { 8470 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 8471 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 8472 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 8473 case ISD::FCEIL: return RISCVFPRndMode::RUP; 8474 case ISD::FROUND: return RISCVFPRndMode::RMM; 8475 } 8476 8477 return RISCVFPRndMode::Invalid; 8478 } 8479 8480 // Fold 8481 // (fp_to_int (froundeven X)) -> fcvt X, rne 8482 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 8483 // (fp_to_int (ffloor X)) -> fcvt X, rdn 8484 // (fp_to_int (fceil X)) -> fcvt X, rup 8485 // (fp_to_int (fround X)) -> fcvt X, rmm 8486 static SDValue performFP_TO_INTCombine(SDNode *N, 8487 TargetLowering::DAGCombinerInfo &DCI, 8488 const RISCVSubtarget &Subtarget) { 8489 SelectionDAG &DAG = DCI.DAG; 8490 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8491 MVT XLenVT = Subtarget.getXLenVT(); 8492 8493 // Only handle XLen or i32 types. Other types narrower than XLen will 8494 // eventually be legalized to XLenVT. 8495 EVT VT = N->getValueType(0); 8496 if (VT != MVT::i32 && VT != XLenVT) 8497 return SDValue(); 8498 8499 SDValue Src = N->getOperand(0); 8500 8501 // Ensure the FP type is also legal. 8502 if (!TLI.isTypeLegal(Src.getValueType())) 8503 return SDValue(); 8504 8505 // Don't do this for f16 with Zfhmin and not Zfh. 8506 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8507 return SDValue(); 8508 8509 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8510 if (FRM == RISCVFPRndMode::Invalid) 8511 return SDValue(); 8512 8513 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8514 8515 unsigned Opc; 8516 if (VT == XLenVT) 8517 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8518 else 8519 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8520 8521 SDLoc DL(N); 8522 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 8523 DAG.getTargetConstant(FRM, DL, XLenVT)); 8524 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 8525 } 8526 8527 // Fold 8528 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 8529 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 8530 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8531 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8532 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8533 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8534 TargetLowering::DAGCombinerInfo &DCI, 8535 const RISCVSubtarget &Subtarget) { 8536 SelectionDAG &DAG = DCI.DAG; 8537 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8538 MVT XLenVT = Subtarget.getXLenVT(); 8539 8540 // Only handle XLen types. Other types narrower than XLen will eventually be 8541 // legalized to XLenVT. 8542 EVT DstVT = N->getValueType(0); 8543 if (DstVT != XLenVT) 8544 return SDValue(); 8545 8546 SDValue Src = N->getOperand(0); 8547 8548 // Ensure the FP type is also legal. 8549 if (!TLI.isTypeLegal(Src.getValueType())) 8550 return SDValue(); 8551 8552 // Don't do this for f16 with Zfhmin and not Zfh. 8553 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8554 return SDValue(); 8555 8556 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8557 8558 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8559 if (FRM == RISCVFPRndMode::Invalid) 8560 return SDValue(); 8561 8562 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8563 8564 unsigned Opc; 8565 if (SatVT == DstVT) 8566 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8567 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8568 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8569 else 8570 return SDValue(); 8571 // FIXME: Support other SatVTs by clamping before or after the conversion. 8572 8573 Src = Src.getOperand(0); 8574 8575 SDLoc DL(N); 8576 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8577 DAG.getTargetConstant(FRM, DL, XLenVT)); 8578 8579 // RISCV FP-to-int conversions saturate to the destination register size, but 8580 // don't produce 0 for nan. 8581 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8582 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8583 } 8584 8585 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is 8586 // smaller than XLenVT. 8587 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG, 8588 const RISCVSubtarget &Subtarget) { 8589 assert(Subtarget.hasStdExtZbkb() && "Unexpected extension"); 8590 8591 SDValue Src = N->getOperand(0); 8592 if (Src.getOpcode() != ISD::BSWAP) 8593 return SDValue(); 8594 8595 EVT VT = N->getValueType(0); 8596 if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() || 8597 !isPowerOf2_32(VT.getSizeInBits())) 8598 return SDValue(); 8599 8600 SDLoc DL(N); 8601 return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0), 8602 DAG.getConstant(7, DL, VT)); 8603 } 8604 8605 // Convert from one FMA opcode to another based on whether we are negating the 8606 // multiply result and/or the accumulator. 8607 // NOTE: Only supports RVV operations with VL. 8608 static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc) { 8609 assert((NegMul || NegAcc) && "Not negating anything?"); 8610 8611 // Negating the multiply result changes ADD<->SUB and toggles 'N'. 8612 if (NegMul) { 8613 // clang-format off 8614 switch (Opcode) { 8615 default: llvm_unreachable("Unexpected opcode"); 8616 case RISCVISD::VFMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break; 8617 case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFMADD_VL; break; 8618 case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFMSUB_VL; break; 8619 case RISCVISD::VFMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break; 8620 } 8621 // clang-format on 8622 } 8623 8624 // Negating the accumulator changes ADD<->SUB. 8625 if (NegAcc) { 8626 // clang-format off 8627 switch (Opcode) { 8628 default: llvm_unreachable("Unexpected opcode"); 8629 case RISCVISD::VFMADD_VL: Opcode = RISCVISD::VFMSUB_VL; break; 8630 case RISCVISD::VFMSUB_VL: Opcode = RISCVISD::VFMADD_VL; break; 8631 case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break; 8632 case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break; 8633 } 8634 // clang-format on 8635 } 8636 8637 return Opcode; 8638 } 8639 8640 static SDValue performSRACombine(SDNode *N, SelectionDAG &DAG, 8641 const RISCVSubtarget &Subtarget) { 8642 assert(N->getOpcode() == ISD::SRA && "Unexpected opcode"); 8643 8644 if (N->getValueType(0) != MVT::i64 || !Subtarget.is64Bit()) 8645 return SDValue(); 8646 8647 if (!isa<ConstantSDNode>(N->getOperand(1))) 8648 return SDValue(); 8649 uint64_t ShAmt = N->getConstantOperandVal(1); 8650 if (ShAmt > 32) 8651 return SDValue(); 8652 8653 SDValue N0 = N->getOperand(0); 8654 8655 // Combine (sra (sext_inreg (shl X, C1), i32), C2) -> 8656 // (sra (shl X, C1+32), C2+32) so it gets selected as SLLI+SRAI instead of 8657 // SLLIW+SRAIW. SLLI+SRAI have compressed forms. 8658 if (ShAmt < 32 && 8659 N0.getOpcode() == ISD::SIGN_EXTEND_INREG && N0.hasOneUse() && 8660 cast<VTSDNode>(N0.getOperand(1))->getVT() == MVT::i32 && 8661 N0.getOperand(0).getOpcode() == ISD::SHL && N0.getOperand(0).hasOneUse() && 8662 isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) { 8663 uint64_t LShAmt = N0.getOperand(0).getConstantOperandVal(1); 8664 if (LShAmt < 32) { 8665 SDLoc ShlDL(N0.getOperand(0)); 8666 SDValue Shl = DAG.getNode(ISD::SHL, ShlDL, MVT::i64, 8667 N0.getOperand(0).getOperand(0), 8668 DAG.getConstant(LShAmt + 32, ShlDL, MVT::i64)); 8669 SDLoc DL(N); 8670 return DAG.getNode(ISD::SRA, DL, MVT::i64, Shl, 8671 DAG.getConstant(ShAmt + 32, DL, MVT::i64)); 8672 } 8673 } 8674 8675 // Combine (sra (shl X, 32), 32 - C) -> (shl (sext_inreg X, i32), C) 8676 // FIXME: Should this be a generic combine? There's a similar combine on X86. 8677 // 8678 // Also try these folds where an add or sub is in the middle. 8679 // (sra (add (shl X, 32), C1), 32 - C) -> (shl (sext_inreg (add X, C1), C) 8680 // (sra (sub C1, (shl X, 32)), 32 - C) -> (shl (sext_inreg (sub C1, X), C) 8681 SDValue Shl; 8682 ConstantSDNode *AddC = nullptr; 8683 8684 // We might have an ADD or SUB between the SRA and SHL. 8685 bool IsAdd = N0.getOpcode() == ISD::ADD; 8686 if ((IsAdd || N0.getOpcode() == ISD::SUB)) { 8687 if (!N0.hasOneUse()) 8688 return SDValue(); 8689 // Other operand needs to be a constant we can modify. 8690 AddC = dyn_cast<ConstantSDNode>(N0.getOperand(IsAdd ? 1 : 0)); 8691 if (!AddC) 8692 return SDValue(); 8693 8694 // AddC needs to have at least 32 trailing zeros. 8695 if (AddC->getAPIntValue().countTrailingZeros() < 32) 8696 return SDValue(); 8697 8698 Shl = N0.getOperand(IsAdd ? 0 : 1); 8699 } else { 8700 // Not an ADD or SUB. 8701 Shl = N0; 8702 } 8703 8704 // Look for a shift left by 32. 8705 if (Shl.getOpcode() != ISD::SHL || !Shl.hasOneUse() || 8706 !isa<ConstantSDNode>(Shl.getOperand(1)) || 8707 Shl.getConstantOperandVal(1) != 32) 8708 return SDValue(); 8709 8710 SDLoc DL(N); 8711 SDValue In = Shl.getOperand(0); 8712 8713 // If we looked through an ADD or SUB, we need to rebuild it with the shifted 8714 // constant. 8715 if (AddC) { 8716 SDValue ShiftedAddC = 8717 DAG.getConstant(AddC->getAPIntValue().lshr(32), DL, MVT::i64); 8718 if (IsAdd) 8719 In = DAG.getNode(ISD::ADD, DL, MVT::i64, In, ShiftedAddC); 8720 else 8721 In = DAG.getNode(ISD::SUB, DL, MVT::i64, ShiftedAddC, In); 8722 } 8723 8724 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, In, 8725 DAG.getValueType(MVT::i32)); 8726 if (ShAmt == 32) 8727 return SExt; 8728 8729 return DAG.getNode( 8730 ISD::SHL, DL, MVT::i64, SExt, 8731 DAG.getConstant(32 - ShAmt, DL, MVT::i64)); 8732 } 8733 8734 // Perform common combines for BR_CC and SELECT_CC condtions. 8735 static bool combine_CC(SDValue &LHS, SDValue &RHS, SDValue &CC, const SDLoc &DL, 8736 SelectionDAG &DAG, const RISCVSubtarget &Subtarget) { 8737 ISD::CondCode CCVal = cast<CondCodeSDNode>(CC)->get(); 8738 if (!ISD::isIntEqualitySetCC(CCVal)) 8739 return false; 8740 8741 // Fold ((setlt X, Y), 0, ne) -> (X, Y, lt) 8742 // Sometimes the setcc is introduced after br_cc/select_cc has been formed. 8743 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8744 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8745 // If we're looking for eq 0 instead of ne 0, we need to invert the 8746 // condition. 8747 bool Invert = CCVal == ISD::SETEQ; 8748 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8749 if (Invert) 8750 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8751 8752 RHS = LHS.getOperand(1); 8753 LHS = LHS.getOperand(0); 8754 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8755 8756 CC = DAG.getCondCode(CCVal); 8757 return true; 8758 } 8759 8760 // Fold ((xor X, Y), 0, eq/ne) -> (X, Y, eq/ne) 8761 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) { 8762 RHS = LHS.getOperand(1); 8763 LHS = LHS.getOperand(0); 8764 return true; 8765 } 8766 8767 // Fold ((srl (and X, 1<<C), C), 0, eq/ne) -> ((shl X, XLen-1-C), 0, ge/lt) 8768 if (isNullConstant(RHS) && LHS.getOpcode() == ISD::SRL && LHS.hasOneUse() && 8769 LHS.getOperand(1).getOpcode() == ISD::Constant) { 8770 SDValue LHS0 = LHS.getOperand(0); 8771 if (LHS0.getOpcode() == ISD::AND && 8772 LHS0.getOperand(1).getOpcode() == ISD::Constant) { 8773 uint64_t Mask = LHS0.getConstantOperandVal(1); 8774 uint64_t ShAmt = LHS.getConstantOperandVal(1); 8775 if (isPowerOf2_64(Mask) && Log2_64(Mask) == ShAmt) { 8776 CCVal = CCVal == ISD::SETEQ ? ISD::SETGE : ISD::SETLT; 8777 CC = DAG.getCondCode(CCVal); 8778 8779 ShAmt = LHS.getValueSizeInBits() - 1 - ShAmt; 8780 LHS = LHS0.getOperand(0); 8781 if (ShAmt != 0) 8782 LHS = 8783 DAG.getNode(ISD::SHL, DL, LHS.getValueType(), LHS0.getOperand(0), 8784 DAG.getConstant(ShAmt, DL, LHS.getValueType())); 8785 return true; 8786 } 8787 } 8788 } 8789 8790 // (X, 1, setne) -> // (X, 0, seteq) if we can prove X is 0/1. 8791 // This can occur when legalizing some floating point comparisons. 8792 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8793 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8794 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8795 CC = DAG.getCondCode(CCVal); 8796 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8797 return true; 8798 } 8799 8800 return false; 8801 } 8802 8803 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8804 DAGCombinerInfo &DCI) const { 8805 SelectionDAG &DAG = DCI.DAG; 8806 8807 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8808 // bits are demanded. N will be added to the Worklist if it was not deleted. 8809 // Caller should return SDValue(N, 0) if this returns true. 8810 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8811 SDValue Op = N->getOperand(OpNo); 8812 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8813 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8814 return false; 8815 8816 if (N->getOpcode() != ISD::DELETED_NODE) 8817 DCI.AddToWorklist(N); 8818 return true; 8819 }; 8820 8821 switch (N->getOpcode()) { 8822 default: 8823 break; 8824 case RISCVISD::SplitF64: { 8825 SDValue Op0 = N->getOperand(0); 8826 // If the input to SplitF64 is just BuildPairF64 then the operation is 8827 // redundant. Instead, use BuildPairF64's operands directly. 8828 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8829 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8830 8831 if (Op0->isUndef()) { 8832 SDValue Lo = DAG.getUNDEF(MVT::i32); 8833 SDValue Hi = DAG.getUNDEF(MVT::i32); 8834 return DCI.CombineTo(N, Lo, Hi); 8835 } 8836 8837 SDLoc DL(N); 8838 8839 // It's cheaper to materialise two 32-bit integers than to load a double 8840 // from the constant pool and transfer it to integer registers through the 8841 // stack. 8842 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8843 APInt V = C->getValueAPF().bitcastToAPInt(); 8844 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8845 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8846 return DCI.CombineTo(N, Lo, Hi); 8847 } 8848 8849 // This is a target-specific version of a DAGCombine performed in 8850 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8851 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8852 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8853 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8854 !Op0.getNode()->hasOneUse()) 8855 break; 8856 SDValue NewSplitF64 = 8857 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8858 Op0.getOperand(0)); 8859 SDValue Lo = NewSplitF64.getValue(0); 8860 SDValue Hi = NewSplitF64.getValue(1); 8861 APInt SignBit = APInt::getSignMask(32); 8862 if (Op0.getOpcode() == ISD::FNEG) { 8863 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8864 DAG.getConstant(SignBit, DL, MVT::i32)); 8865 return DCI.CombineTo(N, Lo, NewHi); 8866 } 8867 assert(Op0.getOpcode() == ISD::FABS); 8868 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8869 DAG.getConstant(~SignBit, DL, MVT::i32)); 8870 return DCI.CombineTo(N, Lo, NewHi); 8871 } 8872 case RISCVISD::SLLW: 8873 case RISCVISD::SRAW: 8874 case RISCVISD::SRLW: { 8875 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8876 if (SimplifyDemandedLowBitsHelper(0, 32) || 8877 SimplifyDemandedLowBitsHelper(1, 5)) 8878 return SDValue(N, 0); 8879 8880 break; 8881 } 8882 case ISD::ROTR: 8883 case ISD::ROTL: 8884 case RISCVISD::RORW: 8885 case RISCVISD::ROLW: { 8886 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8887 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8888 if (SimplifyDemandedLowBitsHelper(0, 32) || 8889 SimplifyDemandedLowBitsHelper(1, 5)) 8890 return SDValue(N, 0); 8891 } 8892 8893 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8894 } 8895 case RISCVISD::CLZW: 8896 case RISCVISD::CTZW: { 8897 // Only the lower 32 bits of the first operand are read 8898 if (SimplifyDemandedLowBitsHelper(0, 32)) 8899 return SDValue(N, 0); 8900 break; 8901 } 8902 case RISCVISD::GREV: 8903 case RISCVISD::GORC: { 8904 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8905 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8906 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8907 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8908 return SDValue(N, 0); 8909 8910 return combineGREVI_GORCI(N, DAG); 8911 } 8912 case RISCVISD::GREVW: 8913 case RISCVISD::GORCW: { 8914 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8915 if (SimplifyDemandedLowBitsHelper(0, 32) || 8916 SimplifyDemandedLowBitsHelper(1, 5)) 8917 return SDValue(N, 0); 8918 8919 break; 8920 } 8921 case RISCVISD::SHFL: 8922 case RISCVISD::UNSHFL: { 8923 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8924 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8925 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8926 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8927 return SDValue(N, 0); 8928 8929 break; 8930 } 8931 case RISCVISD::SHFLW: 8932 case RISCVISD::UNSHFLW: { 8933 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8934 if (SimplifyDemandedLowBitsHelper(0, 32) || 8935 SimplifyDemandedLowBitsHelper(1, 4)) 8936 return SDValue(N, 0); 8937 8938 break; 8939 } 8940 case RISCVISD::BCOMPRESSW: 8941 case RISCVISD::BDECOMPRESSW: { 8942 // Only the lower 32 bits of LHS and RHS are read. 8943 if (SimplifyDemandedLowBitsHelper(0, 32) || 8944 SimplifyDemandedLowBitsHelper(1, 32)) 8945 return SDValue(N, 0); 8946 8947 break; 8948 } 8949 case RISCVISD::FSR: 8950 case RISCVISD::FSL: 8951 case RISCVISD::FSRW: 8952 case RISCVISD::FSLW: { 8953 bool IsWInstruction = 8954 N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW; 8955 unsigned BitWidth = 8956 IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits(); 8957 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8958 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 8959 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1)) 8960 return SDValue(N, 0); 8961 8962 break; 8963 } 8964 case RISCVISD::FMV_X_ANYEXTH: 8965 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8966 SDLoc DL(N); 8967 SDValue Op0 = N->getOperand(0); 8968 MVT VT = N->getSimpleValueType(0); 8969 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8970 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8971 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8972 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8973 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8974 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8975 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8976 assert(Op0.getOperand(0).getValueType() == VT && 8977 "Unexpected value type!"); 8978 return Op0.getOperand(0); 8979 } 8980 8981 // This is a target-specific version of a DAGCombine performed in 8982 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8983 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8984 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8985 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8986 !Op0.getNode()->hasOneUse()) 8987 break; 8988 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8989 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8990 APInt SignBit = APInt::getSignMask(FPBits).sext(VT.getSizeInBits()); 8991 if (Op0.getOpcode() == ISD::FNEG) 8992 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8993 DAG.getConstant(SignBit, DL, VT)); 8994 8995 assert(Op0.getOpcode() == ISD::FABS); 8996 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8997 DAG.getConstant(~SignBit, DL, VT)); 8998 } 8999 case ISD::ADD: 9000 return performADDCombine(N, DAG, Subtarget); 9001 case ISD::SUB: 9002 return performSUBCombine(N, DAG); 9003 case ISD::AND: 9004 return performANDCombine(N, DAG, Subtarget); 9005 case ISD::OR: 9006 return performORCombine(N, DAG, Subtarget); 9007 case ISD::XOR: 9008 return performXORCombine(N, DAG); 9009 case ISD::FADD: 9010 case ISD::UMAX: 9011 case ISD::UMIN: 9012 case ISD::SMAX: 9013 case ISD::SMIN: 9014 case ISD::FMAXNUM: 9015 case ISD::FMINNUM: 9016 return combineBinOpToReduce(N, DAG); 9017 case ISD::SETCC: 9018 return performSETCCCombine(N, DAG, Subtarget); 9019 case ISD::SIGN_EXTEND_INREG: 9020 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 9021 case ISD::ZERO_EXTEND: 9022 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 9023 // type legalization. This is safe because fp_to_uint produces poison if 9024 // it overflows. 9025 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 9026 SDValue Src = N->getOperand(0); 9027 if (Src.getOpcode() == ISD::FP_TO_UINT && 9028 isTypeLegal(Src.getOperand(0).getValueType())) 9029 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 9030 Src.getOperand(0)); 9031 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 9032 isTypeLegal(Src.getOperand(1).getValueType())) { 9033 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 9034 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 9035 Src.getOperand(0), Src.getOperand(1)); 9036 DCI.CombineTo(N, Res); 9037 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 9038 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 9039 return SDValue(N, 0); // Return N so it doesn't get rechecked. 9040 } 9041 } 9042 return SDValue(); 9043 case RISCVISD::SELECT_CC: { 9044 // Transform 9045 SDValue LHS = N->getOperand(0); 9046 SDValue RHS = N->getOperand(1); 9047 SDValue CC = N->getOperand(2); 9048 SDValue TrueV = N->getOperand(3); 9049 SDValue FalseV = N->getOperand(4); 9050 SDLoc DL(N); 9051 9052 // If the True and False values are the same, we don't need a select_cc. 9053 if (TrueV == FalseV) 9054 return TrueV; 9055 9056 if (combine_CC(LHS, RHS, CC, DL, DAG, Subtarget)) 9057 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 9058 {LHS, RHS, CC, TrueV, FalseV}); 9059 9060 return SDValue(); 9061 } 9062 case RISCVISD::BR_CC: { 9063 SDValue LHS = N->getOperand(1); 9064 SDValue RHS = N->getOperand(2); 9065 SDValue CC = N->getOperand(3); 9066 SDLoc DL(N); 9067 9068 if (combine_CC(LHS, RHS, CC, DL, DAG, Subtarget)) 9069 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 9070 N->getOperand(0), LHS, RHS, CC, N->getOperand(4)); 9071 9072 return SDValue(); 9073 } 9074 case ISD::BITREVERSE: 9075 return performBITREVERSECombine(N, DAG, Subtarget); 9076 case ISD::FP_TO_SINT: 9077 case ISD::FP_TO_UINT: 9078 return performFP_TO_INTCombine(N, DCI, Subtarget); 9079 case ISD::FP_TO_SINT_SAT: 9080 case ISD::FP_TO_UINT_SAT: 9081 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 9082 case ISD::FCOPYSIGN: { 9083 EVT VT = N->getValueType(0); 9084 if (!VT.isVector()) 9085 break; 9086 // There is a form of VFSGNJ which injects the negated sign of its second 9087 // operand. Try and bubble any FNEG up after the extend/round to produce 9088 // this optimized pattern. Avoid modifying cases where FP_ROUND and 9089 // TRUNC=1. 9090 SDValue In2 = N->getOperand(1); 9091 // Avoid cases where the extend/round has multiple uses, as duplicating 9092 // those is typically more expensive than removing a fneg. 9093 if (!In2.hasOneUse()) 9094 break; 9095 if (In2.getOpcode() != ISD::FP_EXTEND && 9096 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 9097 break; 9098 In2 = In2.getOperand(0); 9099 if (In2.getOpcode() != ISD::FNEG) 9100 break; 9101 SDLoc DL(N); 9102 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 9103 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 9104 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 9105 } 9106 case ISD::MGATHER: 9107 case ISD::MSCATTER: 9108 case ISD::VP_GATHER: 9109 case ISD::VP_SCATTER: { 9110 if (!DCI.isBeforeLegalize()) 9111 break; 9112 SDValue Index, ScaleOp; 9113 bool IsIndexScaled = false; 9114 bool IsIndexSigned = false; 9115 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 9116 Index = VPGSN->getIndex(); 9117 ScaleOp = VPGSN->getScale(); 9118 IsIndexScaled = VPGSN->isIndexScaled(); 9119 IsIndexSigned = VPGSN->isIndexSigned(); 9120 } else { 9121 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 9122 Index = MGSN->getIndex(); 9123 ScaleOp = MGSN->getScale(); 9124 IsIndexScaled = MGSN->isIndexScaled(); 9125 IsIndexSigned = MGSN->isIndexSigned(); 9126 } 9127 EVT IndexVT = Index.getValueType(); 9128 MVT XLenVT = Subtarget.getXLenVT(); 9129 // RISCV indexed loads only support the "unsigned unscaled" addressing 9130 // mode, so anything else must be manually legalized. 9131 bool NeedsIdxLegalization = 9132 IsIndexScaled || 9133 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 9134 if (!NeedsIdxLegalization) 9135 break; 9136 9137 SDLoc DL(N); 9138 9139 // Any index legalization should first promote to XLenVT, so we don't lose 9140 // bits when scaling. This may create an illegal index type so we let 9141 // LLVM's legalization take care of the splitting. 9142 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 9143 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 9144 IndexVT = IndexVT.changeVectorElementType(XLenVT); 9145 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 9146 DL, IndexVT, Index); 9147 } 9148 9149 if (IsIndexScaled) { 9150 // Manually scale the indices. 9151 // TODO: Sanitize the scale operand here? 9152 // TODO: For VP nodes, should we use VP_SHL here? 9153 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 9154 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 9155 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 9156 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 9157 ScaleOp = DAG.getTargetConstant(1, DL, ScaleOp.getValueType()); 9158 } 9159 9160 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_SCALED; 9161 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 9162 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 9163 {VPGN->getChain(), VPGN->getBasePtr(), Index, 9164 ScaleOp, VPGN->getMask(), 9165 VPGN->getVectorLength()}, 9166 VPGN->getMemOperand(), NewIndexTy); 9167 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 9168 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 9169 {VPSN->getChain(), VPSN->getValue(), 9170 VPSN->getBasePtr(), Index, ScaleOp, 9171 VPSN->getMask(), VPSN->getVectorLength()}, 9172 VPSN->getMemOperand(), NewIndexTy); 9173 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 9174 return DAG.getMaskedGather( 9175 N->getVTList(), MGN->getMemoryVT(), DL, 9176 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 9177 MGN->getBasePtr(), Index, ScaleOp}, 9178 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 9179 const auto *MSN = cast<MaskedScatterSDNode>(N); 9180 return DAG.getMaskedScatter( 9181 N->getVTList(), MSN->getMemoryVT(), DL, 9182 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 9183 Index, ScaleOp}, 9184 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 9185 } 9186 case RISCVISD::SRA_VL: 9187 case RISCVISD::SRL_VL: 9188 case RISCVISD::SHL_VL: { 9189 SDValue ShAmt = N->getOperand(1); 9190 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 9191 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 9192 SDLoc DL(N); 9193 SDValue VL = N->getOperand(3); 9194 EVT VT = N->getValueType(0); 9195 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 9196 ShAmt.getOperand(1), VL); 9197 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 9198 N->getOperand(2), N->getOperand(3)); 9199 } 9200 break; 9201 } 9202 case ISD::SRA: 9203 if (SDValue V = performSRACombine(N, DAG, Subtarget)) 9204 return V; 9205 LLVM_FALLTHROUGH; 9206 case ISD::SRL: 9207 case ISD::SHL: { 9208 SDValue ShAmt = N->getOperand(1); 9209 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 9210 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 9211 SDLoc DL(N); 9212 EVT VT = N->getValueType(0); 9213 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 9214 ShAmt.getOperand(1), 9215 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 9216 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 9217 } 9218 break; 9219 } 9220 case RISCVISD::ADD_VL: 9221 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 9222 return V; 9223 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 9224 case RISCVISD::SUB_VL: 9225 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 9226 case RISCVISD::VWADD_W_VL: 9227 case RISCVISD::VWADDU_W_VL: 9228 case RISCVISD::VWSUB_W_VL: 9229 case RISCVISD::VWSUBU_W_VL: 9230 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 9231 case RISCVISD::MUL_VL: 9232 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 9233 return V; 9234 // Mul is commutative. 9235 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 9236 case RISCVISD::VFMADD_VL: 9237 case RISCVISD::VFNMADD_VL: 9238 case RISCVISD::VFMSUB_VL: 9239 case RISCVISD::VFNMSUB_VL: { 9240 // Fold FNEG_VL into FMA opcodes. 9241 SDValue A = N->getOperand(0); 9242 SDValue B = N->getOperand(1); 9243 SDValue C = N->getOperand(2); 9244 SDValue Mask = N->getOperand(3); 9245 SDValue VL = N->getOperand(4); 9246 9247 auto invertIfNegative = [&Mask, &VL](SDValue &V) { 9248 if (V.getOpcode() == RISCVISD::FNEG_VL && V.getOperand(1) == Mask && 9249 V.getOperand(2) == VL) { 9250 // Return the negated input. 9251 V = V.getOperand(0); 9252 return true; 9253 } 9254 9255 return false; 9256 }; 9257 9258 bool NegA = invertIfNegative(A); 9259 bool NegB = invertIfNegative(B); 9260 bool NegC = invertIfNegative(C); 9261 9262 // If no operands are negated, we're done. 9263 if (!NegA && !NegB && !NegC) 9264 return SDValue(); 9265 9266 unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC); 9267 return DAG.getNode(NewOpcode, SDLoc(N), N->getValueType(0), A, B, C, Mask, 9268 VL); 9269 } 9270 case ISD::STORE: { 9271 auto *Store = cast<StoreSDNode>(N); 9272 SDValue Val = Store->getValue(); 9273 // Combine store of vmv.x.s to vse with VL of 1. 9274 // FIXME: Support FP. 9275 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 9276 SDValue Src = Val.getOperand(0); 9277 MVT VecVT = Src.getSimpleValueType(); 9278 EVT MemVT = Store->getMemoryVT(); 9279 // The memory VT and the element type must match. 9280 if (MemVT == VecVT.getVectorElementType()) { 9281 SDLoc DL(N); 9282 MVT MaskVT = getMaskTypeFor(VecVT); 9283 return DAG.getStoreVP( 9284 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 9285 DAG.getConstant(1, DL, MaskVT), 9286 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 9287 Store->getMemOperand(), Store->getAddressingMode(), 9288 Store->isTruncatingStore(), /*IsCompress*/ false); 9289 } 9290 } 9291 9292 break; 9293 } 9294 case ISD::SPLAT_VECTOR: { 9295 EVT VT = N->getValueType(0); 9296 // Only perform this combine on legal MVT types. 9297 if (!isTypeLegal(VT)) 9298 break; 9299 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 9300 DAG, Subtarget)) 9301 return Gather; 9302 break; 9303 } 9304 case RISCVISD::VMV_V_X_VL: { 9305 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 9306 // scalar input. 9307 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 9308 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 9309 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 9310 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 9311 return SDValue(N, 0); 9312 9313 break; 9314 } 9315 case ISD::INTRINSIC_WO_CHAIN: { 9316 unsigned IntNo = N->getConstantOperandVal(0); 9317 switch (IntNo) { 9318 // By default we do not combine any intrinsic. 9319 default: 9320 return SDValue(); 9321 case Intrinsic::riscv_vcpop: 9322 case Intrinsic::riscv_vcpop_mask: 9323 case Intrinsic::riscv_vfirst: 9324 case Intrinsic::riscv_vfirst_mask: { 9325 SDValue VL = N->getOperand(2); 9326 if (IntNo == Intrinsic::riscv_vcpop_mask || 9327 IntNo == Intrinsic::riscv_vfirst_mask) 9328 VL = N->getOperand(3); 9329 if (!isNullConstant(VL)) 9330 return SDValue(); 9331 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 9332 SDLoc DL(N); 9333 EVT VT = N->getValueType(0); 9334 if (IntNo == Intrinsic::riscv_vfirst || 9335 IntNo == Intrinsic::riscv_vfirst_mask) 9336 return DAG.getConstant(-1, DL, VT); 9337 return DAG.getConstant(0, DL, VT); 9338 } 9339 } 9340 } 9341 case ISD::BITCAST: { 9342 assert(Subtarget.useRVVForFixedLengthVectors()); 9343 SDValue N0 = N->getOperand(0); 9344 EVT VT = N->getValueType(0); 9345 EVT SrcVT = N0.getValueType(); 9346 // If this is a bitcast between a MVT::v4i1/v2i1/v1i1 and an illegal integer 9347 // type, widen both sides to avoid a trip through memory. 9348 if ((SrcVT == MVT::v1i1 || SrcVT == MVT::v2i1 || SrcVT == MVT::v4i1) && 9349 VT.isScalarInteger()) { 9350 unsigned NumConcats = 8 / SrcVT.getVectorNumElements(); 9351 SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT)); 9352 Ops[0] = N0; 9353 SDLoc DL(N); 9354 N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i1, Ops); 9355 N0 = DAG.getBitcast(MVT::i8, N0); 9356 return DAG.getNode(ISD::TRUNCATE, DL, VT, N0); 9357 } 9358 9359 return SDValue(); 9360 } 9361 } 9362 9363 return SDValue(); 9364 } 9365 9366 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 9367 const SDNode *N, CombineLevel Level) const { 9368 assert((N->getOpcode() == ISD::SHL || N->getOpcode() == ISD::SRA || 9369 N->getOpcode() == ISD::SRL) && 9370 "Expected shift op"); 9371 9372 // The following folds are only desirable if `(OP _, c1 << c2)` can be 9373 // materialised in fewer instructions than `(OP _, c1)`: 9374 // 9375 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 9376 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 9377 SDValue N0 = N->getOperand(0); 9378 EVT Ty = N0.getValueType(); 9379 if (Ty.isScalarInteger() && 9380 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 9381 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 9382 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9383 if (C1 && C2) { 9384 const APInt &C1Int = C1->getAPIntValue(); 9385 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 9386 9387 // We can materialise `c1 << c2` into an add immediate, so it's "free", 9388 // and the combine should happen, to potentially allow further combines 9389 // later. 9390 if (ShiftedC1Int.getMinSignedBits() <= 64 && 9391 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 9392 return true; 9393 9394 // We can materialise `c1` in an add immediate, so it's "free", and the 9395 // combine should be prevented. 9396 if (C1Int.getMinSignedBits() <= 64 && 9397 isLegalAddImmediate(C1Int.getSExtValue())) 9398 return false; 9399 9400 // Neither constant will fit into an immediate, so find materialisation 9401 // costs. 9402 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 9403 Subtarget.getFeatureBits(), 9404 /*CompressionCost*/true); 9405 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 9406 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 9407 /*CompressionCost*/true); 9408 9409 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 9410 // combine should be prevented. 9411 if (C1Cost < ShiftedC1Cost) 9412 return false; 9413 } 9414 } 9415 return true; 9416 } 9417 9418 bool RISCVTargetLowering::targetShrinkDemandedConstant( 9419 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 9420 TargetLoweringOpt &TLO) const { 9421 // Delay this optimization as late as possible. 9422 if (!TLO.LegalOps) 9423 return false; 9424 9425 EVT VT = Op.getValueType(); 9426 if (VT.isVector()) 9427 return false; 9428 9429 // Only handle AND for now. 9430 unsigned Opcode = Op.getOpcode(); 9431 if (Opcode != ISD::AND && Opcode != ISD::OR && Opcode != ISD::XOR) 9432 return false; 9433 9434 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 9435 if (!C) 9436 return false; 9437 9438 const APInt &Mask = C->getAPIntValue(); 9439 9440 // Clear all non-demanded bits initially. 9441 APInt ShrunkMask = Mask & DemandedBits; 9442 9443 // Try to make a smaller immediate by setting undemanded bits. 9444 9445 APInt ExpandedMask = Mask | ~DemandedBits; 9446 9447 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 9448 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 9449 }; 9450 auto UseMask = [Mask, Op, &TLO](const APInt &NewMask) -> bool { 9451 if (NewMask == Mask) 9452 return true; 9453 SDLoc DL(Op); 9454 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, Op.getValueType()); 9455 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), DL, Op.getValueType(), 9456 Op.getOperand(0), NewC); 9457 return TLO.CombineTo(Op, NewOp); 9458 }; 9459 9460 // If the shrunk mask fits in sign extended 12 bits, let the target 9461 // independent code apply it. 9462 if (ShrunkMask.isSignedIntN(12)) 9463 return false; 9464 9465 // And has a few special cases for zext. 9466 if (Opcode == ISD::AND) { 9467 // Preserve (and X, 0xffff) when zext.h is supported. 9468 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 9469 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 9470 if (IsLegalMask(NewMask)) 9471 return UseMask(NewMask); 9472 } 9473 9474 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 9475 if (VT == MVT::i64) { 9476 APInt NewMask = APInt(64, 0xffffffff); 9477 if (IsLegalMask(NewMask)) 9478 return UseMask(NewMask); 9479 } 9480 } 9481 9482 // For the remaining optimizations, we need to be able to make a negative 9483 // number through a combination of mask and undemanded bits. 9484 if (!ExpandedMask.isNegative()) 9485 return false; 9486 9487 // What is the fewest number of bits we need to represent the negative number. 9488 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 9489 9490 // Try to make a 12 bit negative immediate. If that fails try to make a 32 9491 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 9492 // If we can't create a simm12, we shouldn't change opaque constants. 9493 APInt NewMask = ShrunkMask; 9494 if (MinSignedBits <= 12) 9495 NewMask.setBitsFrom(11); 9496 else if (!C->isOpaque() && MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 9497 NewMask.setBitsFrom(31); 9498 else 9499 return false; 9500 9501 // Check that our new mask is a subset of the demanded mask. 9502 assert(IsLegalMask(NewMask)); 9503 return UseMask(NewMask); 9504 } 9505 9506 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) { 9507 static const uint64_t GREVMasks[] = { 9508 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 9509 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 9510 9511 for (unsigned Stage = 0; Stage != 6; ++Stage) { 9512 unsigned Shift = 1 << Stage; 9513 if (ShAmt & Shift) { 9514 uint64_t Mask = GREVMasks[Stage]; 9515 uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask); 9516 if (IsGORC) 9517 Res |= x; 9518 x = Res; 9519 } 9520 } 9521 9522 return x; 9523 } 9524 9525 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 9526 KnownBits &Known, 9527 const APInt &DemandedElts, 9528 const SelectionDAG &DAG, 9529 unsigned Depth) const { 9530 unsigned BitWidth = Known.getBitWidth(); 9531 unsigned Opc = Op.getOpcode(); 9532 assert((Opc >= ISD::BUILTIN_OP_END || 9533 Opc == ISD::INTRINSIC_WO_CHAIN || 9534 Opc == ISD::INTRINSIC_W_CHAIN || 9535 Opc == ISD::INTRINSIC_VOID) && 9536 "Should use MaskedValueIsZero if you don't know whether Op" 9537 " is a target node!"); 9538 9539 Known.resetAll(); 9540 switch (Opc) { 9541 default: break; 9542 case RISCVISD::SELECT_CC: { 9543 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 9544 // If we don't know any bits, early out. 9545 if (Known.isUnknown()) 9546 break; 9547 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 9548 9549 // Only known if known in both the LHS and RHS. 9550 Known = KnownBits::commonBits(Known, Known2); 9551 break; 9552 } 9553 case RISCVISD::REMUW: { 9554 KnownBits Known2; 9555 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9556 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9557 // We only care about the lower 32 bits. 9558 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 9559 // Restore the original width by sign extending. 9560 Known = Known.sext(BitWidth); 9561 break; 9562 } 9563 case RISCVISD::DIVUW: { 9564 KnownBits Known2; 9565 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9566 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9567 // We only care about the lower 32 bits. 9568 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 9569 // Restore the original width by sign extending. 9570 Known = Known.sext(BitWidth); 9571 break; 9572 } 9573 case RISCVISD::CTZW: { 9574 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9575 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 9576 unsigned LowBits = Log2_32(PossibleTZ) + 1; 9577 Known.Zero.setBitsFrom(LowBits); 9578 break; 9579 } 9580 case RISCVISD::CLZW: { 9581 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9582 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 9583 unsigned LowBits = Log2_32(PossibleLZ) + 1; 9584 Known.Zero.setBitsFrom(LowBits); 9585 break; 9586 } 9587 case RISCVISD::GREV: 9588 case RISCVISD::GORC: { 9589 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 9590 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9591 unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1); 9592 bool IsGORC = Op.getOpcode() == RISCVISD::GORC; 9593 // To compute zeros, we need to invert the value and invert it back after. 9594 Known.Zero = 9595 ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC); 9596 Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC); 9597 } 9598 break; 9599 } 9600 case RISCVISD::READ_VLENB: { 9601 // We can use the minimum and maximum VLEN values to bound VLENB. We 9602 // know VLEN must be a power of two. 9603 const unsigned MinVLenB = Subtarget.getRealMinVLen() / 8; 9604 const unsigned MaxVLenB = Subtarget.getRealMaxVLen() / 8; 9605 assert(MinVLenB > 0 && "READ_VLENB without vector extension enabled?"); 9606 Known.Zero.setLowBits(Log2_32(MinVLenB)); 9607 Known.Zero.setBitsFrom(Log2_32(MaxVLenB)+1); 9608 if (MaxVLenB == MinVLenB) 9609 Known.One.setBit(Log2_32(MinVLenB)); 9610 break; 9611 } 9612 case ISD::INTRINSIC_W_CHAIN: 9613 case ISD::INTRINSIC_WO_CHAIN: { 9614 unsigned IntNo = 9615 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 9616 switch (IntNo) { 9617 default: 9618 // We can't do anything for most intrinsics. 9619 break; 9620 case Intrinsic::riscv_vsetvli: 9621 case Intrinsic::riscv_vsetvlimax: 9622 case Intrinsic::riscv_vsetvli_opt: 9623 case Intrinsic::riscv_vsetvlimax_opt: 9624 // Assume that VL output is positive and would fit in an int32_t. 9625 // TODO: VLEN might be capped at 16 bits in a future V spec update. 9626 if (BitWidth >= 32) 9627 Known.Zero.setBitsFrom(31); 9628 break; 9629 } 9630 break; 9631 } 9632 } 9633 } 9634 9635 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 9636 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 9637 unsigned Depth) const { 9638 switch (Op.getOpcode()) { 9639 default: 9640 break; 9641 case RISCVISD::SELECT_CC: { 9642 unsigned Tmp = 9643 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 9644 if (Tmp == 1) return 1; // Early out. 9645 unsigned Tmp2 = 9646 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 9647 return std::min(Tmp, Tmp2); 9648 } 9649 case RISCVISD::SLLW: 9650 case RISCVISD::SRAW: 9651 case RISCVISD::SRLW: 9652 case RISCVISD::DIVW: 9653 case RISCVISD::DIVUW: 9654 case RISCVISD::REMUW: 9655 case RISCVISD::ROLW: 9656 case RISCVISD::RORW: 9657 case RISCVISD::GREVW: 9658 case RISCVISD::GORCW: 9659 case RISCVISD::FSLW: 9660 case RISCVISD::FSRW: 9661 case RISCVISD::SHFLW: 9662 case RISCVISD::UNSHFLW: 9663 case RISCVISD::BCOMPRESSW: 9664 case RISCVISD::BDECOMPRESSW: 9665 case RISCVISD::BFPW: 9666 case RISCVISD::FCVT_W_RV64: 9667 case RISCVISD::FCVT_WU_RV64: 9668 case RISCVISD::STRICT_FCVT_W_RV64: 9669 case RISCVISD::STRICT_FCVT_WU_RV64: 9670 // TODO: As the result is sign-extended, this is conservatively correct. A 9671 // more precise answer could be calculated for SRAW depending on known 9672 // bits in the shift amount. 9673 return 33; 9674 case RISCVISD::SHFL: 9675 case RISCVISD::UNSHFL: { 9676 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 9677 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 9678 // will stay within the upper 32 bits. If there were more than 32 sign bits 9679 // before there will be at least 33 sign bits after. 9680 if (Op.getValueType() == MVT::i64 && 9681 isa<ConstantSDNode>(Op.getOperand(1)) && 9682 (Op.getConstantOperandVal(1) & 0x10) == 0) { 9683 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 9684 if (Tmp > 32) 9685 return 33; 9686 } 9687 break; 9688 } 9689 case RISCVISD::VMV_X_S: { 9690 // The number of sign bits of the scalar result is computed by obtaining the 9691 // element type of the input vector operand, subtracting its width from the 9692 // XLEN, and then adding one (sign bit within the element type). If the 9693 // element type is wider than XLen, the least-significant XLEN bits are 9694 // taken. 9695 unsigned XLen = Subtarget.getXLen(); 9696 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 9697 if (EltBits <= XLen) 9698 return XLen - EltBits + 1; 9699 break; 9700 } 9701 } 9702 9703 return 1; 9704 } 9705 9706 const Constant * 9707 RISCVTargetLowering::getTargetConstantFromLoad(LoadSDNode *Ld) const { 9708 assert(Ld && "Unexpected null LoadSDNode"); 9709 if (!ISD::isNormalLoad(Ld)) 9710 return nullptr; 9711 9712 SDValue Ptr = Ld->getBasePtr(); 9713 9714 // Only constant pools with no offset are supported. 9715 auto GetSupportedConstantPool = [](SDValue Ptr) -> ConstantPoolSDNode * { 9716 auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr); 9717 if (!CNode || CNode->isMachineConstantPoolEntry() || 9718 CNode->getOffset() != 0) 9719 return nullptr; 9720 9721 return CNode; 9722 }; 9723 9724 // Simple case, LLA. 9725 if (Ptr.getOpcode() == RISCVISD::LLA) { 9726 auto *CNode = GetSupportedConstantPool(Ptr); 9727 if (!CNode || CNode->getTargetFlags() != 0) 9728 return nullptr; 9729 9730 return CNode->getConstVal(); 9731 } 9732 9733 // Look for a HI and ADD_LO pair. 9734 if (Ptr.getOpcode() != RISCVISD::ADD_LO || 9735 Ptr.getOperand(0).getOpcode() != RISCVISD::HI) 9736 return nullptr; 9737 9738 auto *CNodeLo = GetSupportedConstantPool(Ptr.getOperand(1)); 9739 auto *CNodeHi = GetSupportedConstantPool(Ptr.getOperand(0).getOperand(0)); 9740 9741 if (!CNodeLo || CNodeLo->getTargetFlags() != RISCVII::MO_LO || 9742 !CNodeHi || CNodeHi->getTargetFlags() != RISCVII::MO_HI) 9743 return nullptr; 9744 9745 if (CNodeLo->getConstVal() != CNodeHi->getConstVal()) 9746 return nullptr; 9747 9748 return CNodeLo->getConstVal(); 9749 } 9750 9751 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 9752 MachineBasicBlock *BB) { 9753 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 9754 9755 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 9756 // Should the count have wrapped while it was being read, we need to try 9757 // again. 9758 // ... 9759 // read: 9760 // rdcycleh x3 # load high word of cycle 9761 // rdcycle x2 # load low word of cycle 9762 // rdcycleh x4 # load high word of cycle 9763 // bne x3, x4, read # check if high word reads match, otherwise try again 9764 // ... 9765 9766 MachineFunction &MF = *BB->getParent(); 9767 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9768 MachineFunction::iterator It = ++BB->getIterator(); 9769 9770 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9771 MF.insert(It, LoopMBB); 9772 9773 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9774 MF.insert(It, DoneMBB); 9775 9776 // Transfer the remainder of BB and its successor edges to DoneMBB. 9777 DoneMBB->splice(DoneMBB->begin(), BB, 9778 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9779 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 9780 9781 BB->addSuccessor(LoopMBB); 9782 9783 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9784 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9785 Register LoReg = MI.getOperand(0).getReg(); 9786 Register HiReg = MI.getOperand(1).getReg(); 9787 DebugLoc DL = MI.getDebugLoc(); 9788 9789 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 9790 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 9791 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9792 .addReg(RISCV::X0); 9793 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 9794 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 9795 .addReg(RISCV::X0); 9796 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 9797 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9798 .addReg(RISCV::X0); 9799 9800 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 9801 .addReg(HiReg) 9802 .addReg(ReadAgainReg) 9803 .addMBB(LoopMBB); 9804 9805 LoopMBB->addSuccessor(LoopMBB); 9806 LoopMBB->addSuccessor(DoneMBB); 9807 9808 MI.eraseFromParent(); 9809 9810 return DoneMBB; 9811 } 9812 9813 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9814 MachineBasicBlock *BB) { 9815 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9816 9817 MachineFunction &MF = *BB->getParent(); 9818 DebugLoc DL = MI.getDebugLoc(); 9819 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9820 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9821 Register LoReg = MI.getOperand(0).getReg(); 9822 Register HiReg = MI.getOperand(1).getReg(); 9823 Register SrcReg = MI.getOperand(2).getReg(); 9824 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9825 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9826 9827 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9828 RI); 9829 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9830 MachineMemOperand *MMOLo = 9831 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9832 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9833 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9834 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9835 .addFrameIndex(FI) 9836 .addImm(0) 9837 .addMemOperand(MMOLo); 9838 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9839 .addFrameIndex(FI) 9840 .addImm(4) 9841 .addMemOperand(MMOHi); 9842 MI.eraseFromParent(); // The pseudo instruction is gone now. 9843 return BB; 9844 } 9845 9846 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9847 MachineBasicBlock *BB) { 9848 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9849 "Unexpected instruction"); 9850 9851 MachineFunction &MF = *BB->getParent(); 9852 DebugLoc DL = MI.getDebugLoc(); 9853 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9854 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9855 Register DstReg = MI.getOperand(0).getReg(); 9856 Register LoReg = MI.getOperand(1).getReg(); 9857 Register HiReg = MI.getOperand(2).getReg(); 9858 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9859 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9860 9861 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9862 MachineMemOperand *MMOLo = 9863 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9864 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9865 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9866 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9867 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9868 .addFrameIndex(FI) 9869 .addImm(0) 9870 .addMemOperand(MMOLo); 9871 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9872 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9873 .addFrameIndex(FI) 9874 .addImm(4) 9875 .addMemOperand(MMOHi); 9876 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9877 MI.eraseFromParent(); // The pseudo instruction is gone now. 9878 return BB; 9879 } 9880 9881 static bool isSelectPseudo(MachineInstr &MI) { 9882 switch (MI.getOpcode()) { 9883 default: 9884 return false; 9885 case RISCV::Select_GPR_Using_CC_GPR: 9886 case RISCV::Select_FPR16_Using_CC_GPR: 9887 case RISCV::Select_FPR32_Using_CC_GPR: 9888 case RISCV::Select_FPR64_Using_CC_GPR: 9889 return true; 9890 } 9891 } 9892 9893 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9894 unsigned RelOpcode, unsigned EqOpcode, 9895 const RISCVSubtarget &Subtarget) { 9896 DebugLoc DL = MI.getDebugLoc(); 9897 Register DstReg = MI.getOperand(0).getReg(); 9898 Register Src1Reg = MI.getOperand(1).getReg(); 9899 Register Src2Reg = MI.getOperand(2).getReg(); 9900 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9901 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9902 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9903 9904 // Save the current FFLAGS. 9905 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9906 9907 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9908 .addReg(Src1Reg) 9909 .addReg(Src2Reg); 9910 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9911 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9912 9913 // Restore the FFLAGS. 9914 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9915 .addReg(SavedFFlags, RegState::Kill); 9916 9917 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9918 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9919 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9920 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9921 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9922 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9923 9924 // Erase the pseudoinstruction. 9925 MI.eraseFromParent(); 9926 return BB; 9927 } 9928 9929 static MachineBasicBlock * 9930 EmitLoweredCascadedSelect(MachineInstr &First, MachineInstr &Second, 9931 MachineBasicBlock *ThisMBB, 9932 const RISCVSubtarget &Subtarget) { 9933 // Select_FPRX_ (rs1, rs2, imm, rs4, (Select_FPRX_ rs1, rs2, imm, rs4, rs5) 9934 // Without this, custom-inserter would have generated: 9935 // 9936 // A 9937 // | \ 9938 // | B 9939 // | / 9940 // C 9941 // | \ 9942 // | D 9943 // | / 9944 // E 9945 // 9946 // A: X = ...; Y = ... 9947 // B: empty 9948 // C: Z = PHI [X, A], [Y, B] 9949 // D: empty 9950 // E: PHI [X, C], [Z, D] 9951 // 9952 // If we lower both Select_FPRX_ in a single step, we can instead generate: 9953 // 9954 // A 9955 // | \ 9956 // | C 9957 // | /| 9958 // |/ | 9959 // | | 9960 // | D 9961 // | / 9962 // E 9963 // 9964 // A: X = ...; Y = ... 9965 // D: empty 9966 // E: PHI [X, A], [X, C], [Y, D] 9967 9968 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9969 const DebugLoc &DL = First.getDebugLoc(); 9970 const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock(); 9971 MachineFunction *F = ThisMBB->getParent(); 9972 MachineBasicBlock *FirstMBB = F->CreateMachineBasicBlock(LLVM_BB); 9973 MachineBasicBlock *SecondMBB = F->CreateMachineBasicBlock(LLVM_BB); 9974 MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9975 MachineFunction::iterator It = ++ThisMBB->getIterator(); 9976 F->insert(It, FirstMBB); 9977 F->insert(It, SecondMBB); 9978 F->insert(It, SinkMBB); 9979 9980 // Transfer the remainder of ThisMBB and its successor edges to SinkMBB. 9981 SinkMBB->splice(SinkMBB->begin(), ThisMBB, 9982 std::next(MachineBasicBlock::iterator(First)), 9983 ThisMBB->end()); 9984 SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB); 9985 9986 // Fallthrough block for ThisMBB. 9987 ThisMBB->addSuccessor(FirstMBB); 9988 // Fallthrough block for FirstMBB. 9989 FirstMBB->addSuccessor(SecondMBB); 9990 ThisMBB->addSuccessor(SinkMBB); 9991 FirstMBB->addSuccessor(SinkMBB); 9992 // This is fallthrough. 9993 SecondMBB->addSuccessor(SinkMBB); 9994 9995 auto FirstCC = static_cast<RISCVCC::CondCode>(First.getOperand(3).getImm()); 9996 Register FLHS = First.getOperand(1).getReg(); 9997 Register FRHS = First.getOperand(2).getReg(); 9998 // Insert appropriate branch. 9999 BuildMI(FirstMBB, DL, TII.getBrCond(FirstCC)) 10000 .addReg(FLHS) 10001 .addReg(FRHS) 10002 .addMBB(SinkMBB); 10003 10004 Register SLHS = Second.getOperand(1).getReg(); 10005 Register SRHS = Second.getOperand(2).getReg(); 10006 Register Op1Reg4 = First.getOperand(4).getReg(); 10007 Register Op1Reg5 = First.getOperand(5).getReg(); 10008 10009 auto SecondCC = static_cast<RISCVCC::CondCode>(Second.getOperand(3).getImm()); 10010 // Insert appropriate branch. 10011 BuildMI(ThisMBB, DL, TII.getBrCond(SecondCC)) 10012 .addReg(SLHS) 10013 .addReg(SRHS) 10014 .addMBB(SinkMBB); 10015 10016 Register DestReg = Second.getOperand(0).getReg(); 10017 Register Op2Reg4 = Second.getOperand(4).getReg(); 10018 BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII.get(RISCV::PHI), DestReg) 10019 .addReg(Op2Reg4) 10020 .addMBB(ThisMBB) 10021 .addReg(Op1Reg4) 10022 .addMBB(FirstMBB) 10023 .addReg(Op1Reg5) 10024 .addMBB(SecondMBB); 10025 10026 // Now remove the Select_FPRX_s. 10027 First.eraseFromParent(); 10028 Second.eraseFromParent(); 10029 return SinkMBB; 10030 } 10031 10032 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 10033 MachineBasicBlock *BB, 10034 const RISCVSubtarget &Subtarget) { 10035 // To "insert" Select_* instructions, we actually have to insert the triangle 10036 // control-flow pattern. The incoming instructions know the destination vreg 10037 // to set, the condition code register to branch on, the true/false values to 10038 // select between, and the condcode to use to select the appropriate branch. 10039 // 10040 // We produce the following control flow: 10041 // HeadMBB 10042 // | \ 10043 // | IfFalseMBB 10044 // | / 10045 // TailMBB 10046 // 10047 // When we find a sequence of selects we attempt to optimize their emission 10048 // by sharing the control flow. Currently we only handle cases where we have 10049 // multiple selects with the exact same condition (same LHS, RHS and CC). 10050 // The selects may be interleaved with other instructions if the other 10051 // instructions meet some requirements we deem safe: 10052 // - They are debug instructions. Otherwise, 10053 // - They do not have side-effects, do not access memory and their inputs do 10054 // not depend on the results of the select pseudo-instructions. 10055 // The TrueV/FalseV operands of the selects cannot depend on the result of 10056 // previous selects in the sequence. 10057 // These conditions could be further relaxed. See the X86 target for a 10058 // related approach and more information. 10059 // 10060 // Select_FPRX_ (rs1, rs2, imm, rs4, (Select_FPRX_ rs1, rs2, imm, rs4, rs5)) 10061 // is checked here and handled by a separate function - 10062 // EmitLoweredCascadedSelect. 10063 Register LHS = MI.getOperand(1).getReg(); 10064 Register RHS = MI.getOperand(2).getReg(); 10065 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 10066 10067 SmallVector<MachineInstr *, 4> SelectDebugValues; 10068 SmallSet<Register, 4> SelectDests; 10069 SelectDests.insert(MI.getOperand(0).getReg()); 10070 10071 MachineInstr *LastSelectPseudo = &MI; 10072 auto Next = next_nodbg(MI.getIterator(), BB->instr_end()); 10073 if (MI.getOpcode() != RISCV::Select_GPR_Using_CC_GPR && Next != BB->end() && 10074 Next->getOpcode() == MI.getOpcode() && 10075 Next->getOperand(5).getReg() == MI.getOperand(0).getReg() && 10076 Next->getOperand(5).isKill()) { 10077 return EmitLoweredCascadedSelect(MI, *Next, BB, Subtarget); 10078 } 10079 10080 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 10081 SequenceMBBI != E; ++SequenceMBBI) { 10082 if (SequenceMBBI->isDebugInstr()) 10083 continue; 10084 if (isSelectPseudo(*SequenceMBBI)) { 10085 if (SequenceMBBI->getOperand(1).getReg() != LHS || 10086 SequenceMBBI->getOperand(2).getReg() != RHS || 10087 SequenceMBBI->getOperand(3).getImm() != CC || 10088 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 10089 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 10090 break; 10091 LastSelectPseudo = &*SequenceMBBI; 10092 SequenceMBBI->collectDebugValues(SelectDebugValues); 10093 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 10094 continue; 10095 } 10096 if (SequenceMBBI->hasUnmodeledSideEffects() || 10097 SequenceMBBI->mayLoadOrStore()) 10098 break; 10099 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 10100 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 10101 })) 10102 break; 10103 } 10104 10105 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 10106 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10107 DebugLoc DL = MI.getDebugLoc(); 10108 MachineFunction::iterator I = ++BB->getIterator(); 10109 10110 MachineBasicBlock *HeadMBB = BB; 10111 MachineFunction *F = BB->getParent(); 10112 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 10113 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 10114 10115 F->insert(I, IfFalseMBB); 10116 F->insert(I, TailMBB); 10117 10118 // Transfer debug instructions associated with the selects to TailMBB. 10119 for (MachineInstr *DebugInstr : SelectDebugValues) { 10120 TailMBB->push_back(DebugInstr->removeFromParent()); 10121 } 10122 10123 // Move all instructions after the sequence to TailMBB. 10124 TailMBB->splice(TailMBB->end(), HeadMBB, 10125 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 10126 // Update machine-CFG edges by transferring all successors of the current 10127 // block to the new block which will contain the Phi nodes for the selects. 10128 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 10129 // Set the successors for HeadMBB. 10130 HeadMBB->addSuccessor(IfFalseMBB); 10131 HeadMBB->addSuccessor(TailMBB); 10132 10133 // Insert appropriate branch. 10134 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 10135 .addReg(LHS) 10136 .addReg(RHS) 10137 .addMBB(TailMBB); 10138 10139 // IfFalseMBB just falls through to TailMBB. 10140 IfFalseMBB->addSuccessor(TailMBB); 10141 10142 // Create PHIs for all of the select pseudo-instructions. 10143 auto SelectMBBI = MI.getIterator(); 10144 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 10145 auto InsertionPoint = TailMBB->begin(); 10146 while (SelectMBBI != SelectEnd) { 10147 auto Next = std::next(SelectMBBI); 10148 if (isSelectPseudo(*SelectMBBI)) { 10149 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 10150 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 10151 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 10152 .addReg(SelectMBBI->getOperand(4).getReg()) 10153 .addMBB(HeadMBB) 10154 .addReg(SelectMBBI->getOperand(5).getReg()) 10155 .addMBB(IfFalseMBB); 10156 SelectMBBI->eraseFromParent(); 10157 } 10158 SelectMBBI = Next; 10159 } 10160 10161 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 10162 return TailMBB; 10163 } 10164 10165 MachineBasicBlock * 10166 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10167 MachineBasicBlock *BB) const { 10168 switch (MI.getOpcode()) { 10169 default: 10170 llvm_unreachable("Unexpected instr type to insert"); 10171 case RISCV::ReadCycleWide: 10172 assert(!Subtarget.is64Bit() && 10173 "ReadCycleWrite is only to be used on riscv32"); 10174 return emitReadCycleWidePseudo(MI, BB); 10175 case RISCV::Select_GPR_Using_CC_GPR: 10176 case RISCV::Select_FPR16_Using_CC_GPR: 10177 case RISCV::Select_FPR32_Using_CC_GPR: 10178 case RISCV::Select_FPR64_Using_CC_GPR: 10179 return emitSelectPseudo(MI, BB, Subtarget); 10180 case RISCV::BuildPairF64Pseudo: 10181 return emitBuildPairF64Pseudo(MI, BB); 10182 case RISCV::SplitF64Pseudo: 10183 return emitSplitF64Pseudo(MI, BB); 10184 case RISCV::PseudoQuietFLE_H: 10185 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 10186 case RISCV::PseudoQuietFLT_H: 10187 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 10188 case RISCV::PseudoQuietFLE_S: 10189 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 10190 case RISCV::PseudoQuietFLT_S: 10191 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 10192 case RISCV::PseudoQuietFLE_D: 10193 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 10194 case RISCV::PseudoQuietFLT_D: 10195 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 10196 } 10197 } 10198 10199 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10200 SDNode *Node) const { 10201 // Add FRM dependency to any instructions with dynamic rounding mode. 10202 unsigned Opc = MI.getOpcode(); 10203 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 10204 if (Idx < 0) 10205 return; 10206 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 10207 return; 10208 // If the instruction already reads FRM, don't add another read. 10209 if (MI.readsRegister(RISCV::FRM)) 10210 return; 10211 MI.addOperand( 10212 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 10213 } 10214 10215 // Calling Convention Implementation. 10216 // The expectations for frontend ABI lowering vary from target to target. 10217 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 10218 // details, but this is a longer term goal. For now, we simply try to keep the 10219 // role of the frontend as simple and well-defined as possible. The rules can 10220 // be summarised as: 10221 // * Never split up large scalar arguments. We handle them here. 10222 // * If a hardfloat calling convention is being used, and the struct may be 10223 // passed in a pair of registers (fp+fp, int+fp), and both registers are 10224 // available, then pass as two separate arguments. If either the GPRs or FPRs 10225 // are exhausted, then pass according to the rule below. 10226 // * If a struct could never be passed in registers or directly in a stack 10227 // slot (as it is larger than 2*XLEN and the floating point rules don't 10228 // apply), then pass it using a pointer with the byval attribute. 10229 // * If a struct is less than 2*XLEN, then coerce to either a two-element 10230 // word-sized array or a 2*XLEN scalar (depending on alignment). 10231 // * The frontend can determine whether a struct is returned by reference or 10232 // not based on its size and fields. If it will be returned by reference, the 10233 // frontend must modify the prototype so a pointer with the sret annotation is 10234 // passed as the first argument. This is not necessary for large scalar 10235 // returns. 10236 // * Struct return values and varargs should be coerced to structs containing 10237 // register-size fields in the same situations they would be for fixed 10238 // arguments. 10239 10240 static const MCPhysReg ArgGPRs[] = { 10241 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 10242 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 10243 }; 10244 static const MCPhysReg ArgFPR16s[] = { 10245 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 10246 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 10247 }; 10248 static const MCPhysReg ArgFPR32s[] = { 10249 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 10250 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 10251 }; 10252 static const MCPhysReg ArgFPR64s[] = { 10253 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 10254 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 10255 }; 10256 // This is an interim calling convention and it may be changed in the future. 10257 static const MCPhysReg ArgVRs[] = { 10258 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 10259 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 10260 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 10261 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 10262 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 10263 RISCV::V20M2, RISCV::V22M2}; 10264 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 10265 RISCV::V20M4}; 10266 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 10267 10268 // Pass a 2*XLEN argument that has been split into two XLEN values through 10269 // registers or the stack as necessary. 10270 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 10271 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 10272 MVT ValVT2, MVT LocVT2, 10273 ISD::ArgFlagsTy ArgFlags2) { 10274 unsigned XLenInBytes = XLen / 8; 10275 if (Register Reg = State.AllocateReg(ArgGPRs)) { 10276 // At least one half can be passed via register. 10277 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 10278 VA1.getLocVT(), CCValAssign::Full)); 10279 } else { 10280 // Both halves must be passed on the stack, with proper alignment. 10281 Align StackAlign = 10282 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 10283 State.addLoc( 10284 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 10285 State.AllocateStack(XLenInBytes, StackAlign), 10286 VA1.getLocVT(), CCValAssign::Full)); 10287 State.addLoc(CCValAssign::getMem( 10288 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 10289 LocVT2, CCValAssign::Full)); 10290 return false; 10291 } 10292 10293 if (Register Reg = State.AllocateReg(ArgGPRs)) { 10294 // The second half can also be passed via register. 10295 State.addLoc( 10296 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 10297 } else { 10298 // The second half is passed via the stack, without additional alignment. 10299 State.addLoc(CCValAssign::getMem( 10300 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 10301 LocVT2, CCValAssign::Full)); 10302 } 10303 10304 return false; 10305 } 10306 10307 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 10308 Optional<unsigned> FirstMaskArgument, 10309 CCState &State, const RISCVTargetLowering &TLI) { 10310 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 10311 if (RC == &RISCV::VRRegClass) { 10312 // Assign the first mask argument to V0. 10313 // This is an interim calling convention and it may be changed in the 10314 // future. 10315 if (FirstMaskArgument && ValNo == *FirstMaskArgument) 10316 return State.AllocateReg(RISCV::V0); 10317 return State.AllocateReg(ArgVRs); 10318 } 10319 if (RC == &RISCV::VRM2RegClass) 10320 return State.AllocateReg(ArgVRM2s); 10321 if (RC == &RISCV::VRM4RegClass) 10322 return State.AllocateReg(ArgVRM4s); 10323 if (RC == &RISCV::VRM8RegClass) 10324 return State.AllocateReg(ArgVRM8s); 10325 llvm_unreachable("Unhandled register class for ValueType"); 10326 } 10327 10328 // Implements the RISC-V calling convention. Returns true upon failure. 10329 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 10330 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 10331 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 10332 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 10333 Optional<unsigned> FirstMaskArgument) { 10334 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 10335 assert(XLen == 32 || XLen == 64); 10336 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 10337 10338 // Any return value split in to more than two values can't be returned 10339 // directly. Vectors are returned via the available vector registers. 10340 if (!LocVT.isVector() && IsRet && ValNo > 1) 10341 return true; 10342 10343 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 10344 // variadic argument, or if no F16/F32 argument registers are available. 10345 bool UseGPRForF16_F32 = true; 10346 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 10347 // variadic argument, or if no F64 argument registers are available. 10348 bool UseGPRForF64 = true; 10349 10350 switch (ABI) { 10351 default: 10352 llvm_unreachable("Unexpected ABI"); 10353 case RISCVABI::ABI_ILP32: 10354 case RISCVABI::ABI_LP64: 10355 break; 10356 case RISCVABI::ABI_ILP32F: 10357 case RISCVABI::ABI_LP64F: 10358 UseGPRForF16_F32 = !IsFixed; 10359 break; 10360 case RISCVABI::ABI_ILP32D: 10361 case RISCVABI::ABI_LP64D: 10362 UseGPRForF16_F32 = !IsFixed; 10363 UseGPRForF64 = !IsFixed; 10364 break; 10365 } 10366 10367 // FPR16, FPR32, and FPR64 alias each other. 10368 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 10369 UseGPRForF16_F32 = true; 10370 UseGPRForF64 = true; 10371 } 10372 10373 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 10374 // similar local variables rather than directly checking against the target 10375 // ABI. 10376 10377 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 10378 LocVT = XLenVT; 10379 LocInfo = CCValAssign::BCvt; 10380 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 10381 LocVT = MVT::i64; 10382 LocInfo = CCValAssign::BCvt; 10383 } 10384 10385 // If this is a variadic argument, the RISC-V calling convention requires 10386 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 10387 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 10388 // be used regardless of whether the original argument was split during 10389 // legalisation or not. The argument will not be passed by registers if the 10390 // original type is larger than 2*XLEN, so the register alignment rule does 10391 // not apply. 10392 unsigned TwoXLenInBytes = (2 * XLen) / 8; 10393 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 10394 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 10395 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 10396 // Skip 'odd' register if necessary. 10397 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 10398 State.AllocateReg(ArgGPRs); 10399 } 10400 10401 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 10402 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 10403 State.getPendingArgFlags(); 10404 10405 assert(PendingLocs.size() == PendingArgFlags.size() && 10406 "PendingLocs and PendingArgFlags out of sync"); 10407 10408 // Handle passing f64 on RV32D with a soft float ABI or when floating point 10409 // registers are exhausted. 10410 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 10411 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 10412 "Can't lower f64 if it is split"); 10413 // Depending on available argument GPRS, f64 may be passed in a pair of 10414 // GPRs, split between a GPR and the stack, or passed completely on the 10415 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 10416 // cases. 10417 Register Reg = State.AllocateReg(ArgGPRs); 10418 LocVT = MVT::i32; 10419 if (!Reg) { 10420 unsigned StackOffset = State.AllocateStack(8, Align(8)); 10421 State.addLoc( 10422 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10423 return false; 10424 } 10425 if (!State.AllocateReg(ArgGPRs)) 10426 State.AllocateStack(4, Align(4)); 10427 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10428 return false; 10429 } 10430 10431 // Fixed-length vectors are located in the corresponding scalable-vector 10432 // container types. 10433 if (ValVT.isFixedLengthVector()) 10434 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10435 10436 // Split arguments might be passed indirectly, so keep track of the pending 10437 // values. Split vectors are passed via a mix of registers and indirectly, so 10438 // treat them as we would any other argument. 10439 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 10440 LocVT = XLenVT; 10441 LocInfo = CCValAssign::Indirect; 10442 PendingLocs.push_back( 10443 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 10444 PendingArgFlags.push_back(ArgFlags); 10445 if (!ArgFlags.isSplitEnd()) { 10446 return false; 10447 } 10448 } 10449 10450 // If the split argument only had two elements, it should be passed directly 10451 // in registers or on the stack. 10452 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 10453 PendingLocs.size() <= 2) { 10454 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 10455 // Apply the normal calling convention rules to the first half of the 10456 // split argument. 10457 CCValAssign VA = PendingLocs[0]; 10458 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 10459 PendingLocs.clear(); 10460 PendingArgFlags.clear(); 10461 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 10462 ArgFlags); 10463 } 10464 10465 // Allocate to a register if possible, or else a stack slot. 10466 Register Reg; 10467 unsigned StoreSizeBytes = XLen / 8; 10468 Align StackAlign = Align(XLen / 8); 10469 10470 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 10471 Reg = State.AllocateReg(ArgFPR16s); 10472 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 10473 Reg = State.AllocateReg(ArgFPR32s); 10474 else if (ValVT == MVT::f64 && !UseGPRForF64) 10475 Reg = State.AllocateReg(ArgFPR64s); 10476 else if (ValVT.isVector()) { 10477 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 10478 if (!Reg) { 10479 // For return values, the vector must be passed fully via registers or 10480 // via the stack. 10481 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 10482 // but we're using all of them. 10483 if (IsRet) 10484 return true; 10485 // Try using a GPR to pass the address 10486 if ((Reg = State.AllocateReg(ArgGPRs))) { 10487 LocVT = XLenVT; 10488 LocInfo = CCValAssign::Indirect; 10489 } else if (ValVT.isScalableVector()) { 10490 LocVT = XLenVT; 10491 LocInfo = CCValAssign::Indirect; 10492 } else { 10493 // Pass fixed-length vectors on the stack. 10494 LocVT = ValVT; 10495 StoreSizeBytes = ValVT.getStoreSize(); 10496 // Align vectors to their element sizes, being careful for vXi1 10497 // vectors. 10498 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10499 } 10500 } 10501 } else { 10502 Reg = State.AllocateReg(ArgGPRs); 10503 } 10504 10505 unsigned StackOffset = 10506 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 10507 10508 // If we reach this point and PendingLocs is non-empty, we must be at the 10509 // end of a split argument that must be passed indirectly. 10510 if (!PendingLocs.empty()) { 10511 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 10512 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 10513 10514 for (auto &It : PendingLocs) { 10515 if (Reg) 10516 It.convertToReg(Reg); 10517 else 10518 It.convertToMem(StackOffset); 10519 State.addLoc(It); 10520 } 10521 PendingLocs.clear(); 10522 PendingArgFlags.clear(); 10523 return false; 10524 } 10525 10526 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 10527 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 10528 "Expected an XLenVT or vector types at this stage"); 10529 10530 if (Reg) { 10531 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10532 return false; 10533 } 10534 10535 // When a floating-point value is passed on the stack, no bit-conversion is 10536 // needed. 10537 if (ValVT.isFloatingPoint()) { 10538 LocVT = ValVT; 10539 LocInfo = CCValAssign::Full; 10540 } 10541 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10542 return false; 10543 } 10544 10545 template <typename ArgTy> 10546 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 10547 for (const auto &ArgIdx : enumerate(Args)) { 10548 MVT ArgVT = ArgIdx.value().VT; 10549 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 10550 return ArgIdx.index(); 10551 } 10552 return None; 10553 } 10554 10555 void RISCVTargetLowering::analyzeInputArgs( 10556 MachineFunction &MF, CCState &CCInfo, 10557 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 10558 RISCVCCAssignFn Fn) const { 10559 unsigned NumArgs = Ins.size(); 10560 FunctionType *FType = MF.getFunction().getFunctionType(); 10561 10562 Optional<unsigned> FirstMaskArgument; 10563 if (Subtarget.hasVInstructions()) 10564 FirstMaskArgument = preAssignMask(Ins); 10565 10566 for (unsigned i = 0; i != NumArgs; ++i) { 10567 MVT ArgVT = Ins[i].VT; 10568 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 10569 10570 Type *ArgTy = nullptr; 10571 if (IsRet) 10572 ArgTy = FType->getReturnType(); 10573 else if (Ins[i].isOrigArg()) 10574 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 10575 10576 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10577 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10578 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 10579 FirstMaskArgument)) { 10580 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 10581 << EVT(ArgVT).getEVTString() << '\n'); 10582 llvm_unreachable(nullptr); 10583 } 10584 } 10585 } 10586 10587 void RISCVTargetLowering::analyzeOutputArgs( 10588 MachineFunction &MF, CCState &CCInfo, 10589 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 10590 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 10591 unsigned NumArgs = Outs.size(); 10592 10593 Optional<unsigned> FirstMaskArgument; 10594 if (Subtarget.hasVInstructions()) 10595 FirstMaskArgument = preAssignMask(Outs); 10596 10597 for (unsigned i = 0; i != NumArgs; i++) { 10598 MVT ArgVT = Outs[i].VT; 10599 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10600 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 10601 10602 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10603 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10604 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 10605 FirstMaskArgument)) { 10606 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 10607 << EVT(ArgVT).getEVTString() << "\n"); 10608 llvm_unreachable(nullptr); 10609 } 10610 } 10611 } 10612 10613 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 10614 // values. 10615 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 10616 const CCValAssign &VA, const SDLoc &DL, 10617 const RISCVSubtarget &Subtarget) { 10618 switch (VA.getLocInfo()) { 10619 default: 10620 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10621 case CCValAssign::Full: 10622 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 10623 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 10624 break; 10625 case CCValAssign::BCvt: 10626 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10627 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 10628 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10629 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 10630 else 10631 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 10632 break; 10633 } 10634 return Val; 10635 } 10636 10637 // The caller is responsible for loading the full value if the argument is 10638 // passed with CCValAssign::Indirect. 10639 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 10640 const CCValAssign &VA, const SDLoc &DL, 10641 const RISCVTargetLowering &TLI) { 10642 MachineFunction &MF = DAG.getMachineFunction(); 10643 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10644 EVT LocVT = VA.getLocVT(); 10645 SDValue Val; 10646 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 10647 Register VReg = RegInfo.createVirtualRegister(RC); 10648 RegInfo.addLiveIn(VA.getLocReg(), VReg); 10649 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 10650 10651 if (VA.getLocInfo() == CCValAssign::Indirect) 10652 return Val; 10653 10654 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 10655 } 10656 10657 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 10658 const CCValAssign &VA, const SDLoc &DL, 10659 const RISCVSubtarget &Subtarget) { 10660 EVT LocVT = VA.getLocVT(); 10661 10662 switch (VA.getLocInfo()) { 10663 default: 10664 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10665 case CCValAssign::Full: 10666 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 10667 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 10668 break; 10669 case CCValAssign::BCvt: 10670 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10671 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 10672 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10673 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 10674 else 10675 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 10676 break; 10677 } 10678 return Val; 10679 } 10680 10681 // The caller is responsible for loading the full value if the argument is 10682 // passed with CCValAssign::Indirect. 10683 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 10684 const CCValAssign &VA, const SDLoc &DL) { 10685 MachineFunction &MF = DAG.getMachineFunction(); 10686 MachineFrameInfo &MFI = MF.getFrameInfo(); 10687 EVT LocVT = VA.getLocVT(); 10688 EVT ValVT = VA.getValVT(); 10689 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 10690 if (ValVT.isScalableVector()) { 10691 // When the value is a scalable vector, we save the pointer which points to 10692 // the scalable vector value in the stack. The ValVT will be the pointer 10693 // type, instead of the scalable vector type. 10694 ValVT = LocVT; 10695 } 10696 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 10697 /*IsImmutable=*/true); 10698 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 10699 SDValue Val; 10700 10701 ISD::LoadExtType ExtType; 10702 switch (VA.getLocInfo()) { 10703 default: 10704 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10705 case CCValAssign::Full: 10706 case CCValAssign::Indirect: 10707 case CCValAssign::BCvt: 10708 ExtType = ISD::NON_EXTLOAD; 10709 break; 10710 } 10711 Val = DAG.getExtLoad( 10712 ExtType, DL, LocVT, Chain, FIN, 10713 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 10714 return Val; 10715 } 10716 10717 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 10718 const CCValAssign &VA, const SDLoc &DL) { 10719 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 10720 "Unexpected VA"); 10721 MachineFunction &MF = DAG.getMachineFunction(); 10722 MachineFrameInfo &MFI = MF.getFrameInfo(); 10723 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10724 10725 if (VA.isMemLoc()) { 10726 // f64 is passed on the stack. 10727 int FI = 10728 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 10729 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10730 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 10731 MachinePointerInfo::getFixedStack(MF, FI)); 10732 } 10733 10734 assert(VA.isRegLoc() && "Expected register VA assignment"); 10735 10736 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10737 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 10738 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 10739 SDValue Hi; 10740 if (VA.getLocReg() == RISCV::X17) { 10741 // Second half of f64 is passed on the stack. 10742 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 10743 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10744 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 10745 MachinePointerInfo::getFixedStack(MF, FI)); 10746 } else { 10747 // Second half of f64 is passed in another GPR. 10748 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10749 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 10750 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 10751 } 10752 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 10753 } 10754 10755 // FastCC has less than 1% performance improvement for some particular 10756 // benchmark. But theoretically, it may has benenfit for some cases. 10757 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 10758 unsigned ValNo, MVT ValVT, MVT LocVT, 10759 CCValAssign::LocInfo LocInfo, 10760 ISD::ArgFlagsTy ArgFlags, CCState &State, 10761 bool IsFixed, bool IsRet, Type *OrigTy, 10762 const RISCVTargetLowering &TLI, 10763 Optional<unsigned> FirstMaskArgument) { 10764 10765 // X5 and X6 might be used for save-restore libcall. 10766 static const MCPhysReg GPRList[] = { 10767 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 10768 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 10769 RISCV::X29, RISCV::X30, RISCV::X31}; 10770 10771 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10772 if (unsigned Reg = State.AllocateReg(GPRList)) { 10773 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10774 return false; 10775 } 10776 } 10777 10778 if (LocVT == MVT::f16) { 10779 static const MCPhysReg FPR16List[] = { 10780 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 10781 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 10782 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 10783 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 10784 if (unsigned Reg = State.AllocateReg(FPR16List)) { 10785 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10786 return false; 10787 } 10788 } 10789 10790 if (LocVT == MVT::f32) { 10791 static const MCPhysReg FPR32List[] = { 10792 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 10793 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 10794 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 10795 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 10796 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10797 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10798 return false; 10799 } 10800 } 10801 10802 if (LocVT == MVT::f64) { 10803 static const MCPhysReg FPR64List[] = { 10804 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 10805 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 10806 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 10807 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 10808 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10809 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10810 return false; 10811 } 10812 } 10813 10814 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 10815 unsigned Offset4 = State.AllocateStack(4, Align(4)); 10816 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 10817 return false; 10818 } 10819 10820 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 10821 unsigned Offset5 = State.AllocateStack(8, Align(8)); 10822 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 10823 return false; 10824 } 10825 10826 if (LocVT.isVector()) { 10827 if (unsigned Reg = 10828 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 10829 // Fixed-length vectors are located in the corresponding scalable-vector 10830 // container types. 10831 if (ValVT.isFixedLengthVector()) 10832 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10833 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10834 } else { 10835 // Try and pass the address via a "fast" GPR. 10836 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 10837 LocInfo = CCValAssign::Indirect; 10838 LocVT = TLI.getSubtarget().getXLenVT(); 10839 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 10840 } else if (ValVT.isFixedLengthVector()) { 10841 auto StackAlign = 10842 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10843 unsigned StackOffset = 10844 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 10845 State.addLoc( 10846 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10847 } else { 10848 // Can't pass scalable vectors on the stack. 10849 return true; 10850 } 10851 } 10852 10853 return false; 10854 } 10855 10856 return true; // CC didn't match. 10857 } 10858 10859 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 10860 CCValAssign::LocInfo LocInfo, 10861 ISD::ArgFlagsTy ArgFlags, CCState &State) { 10862 10863 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10864 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 10865 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 10866 static const MCPhysReg GPRList[] = { 10867 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 10868 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 10869 if (unsigned Reg = State.AllocateReg(GPRList)) { 10870 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10871 return false; 10872 } 10873 } 10874 10875 if (LocVT == MVT::f32) { 10876 // Pass in STG registers: F1, ..., F6 10877 // fs0 ... fs5 10878 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 10879 RISCV::F18_F, RISCV::F19_F, 10880 RISCV::F20_F, RISCV::F21_F}; 10881 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10882 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10883 return false; 10884 } 10885 } 10886 10887 if (LocVT == MVT::f64) { 10888 // Pass in STG registers: D1, ..., D6 10889 // fs6 ... fs11 10890 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 10891 RISCV::F24_D, RISCV::F25_D, 10892 RISCV::F26_D, RISCV::F27_D}; 10893 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10894 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10895 return false; 10896 } 10897 } 10898 10899 report_fatal_error("No registers left in GHC calling convention"); 10900 return true; 10901 } 10902 10903 // Transform physical registers into virtual registers. 10904 SDValue RISCVTargetLowering::LowerFormalArguments( 10905 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 10906 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 10907 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 10908 10909 MachineFunction &MF = DAG.getMachineFunction(); 10910 10911 switch (CallConv) { 10912 default: 10913 report_fatal_error("Unsupported calling convention"); 10914 case CallingConv::C: 10915 case CallingConv::Fast: 10916 break; 10917 case CallingConv::GHC: 10918 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10919 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10920 report_fatal_error( 10921 "GHC calling convention requires the F and D instruction set extensions"); 10922 } 10923 10924 const Function &Func = MF.getFunction(); 10925 if (Func.hasFnAttribute("interrupt")) { 10926 if (!Func.arg_empty()) 10927 report_fatal_error( 10928 "Functions with the interrupt attribute cannot have arguments!"); 10929 10930 StringRef Kind = 10931 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10932 10933 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10934 report_fatal_error( 10935 "Function interrupt attribute argument not supported!"); 10936 } 10937 10938 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10939 MVT XLenVT = Subtarget.getXLenVT(); 10940 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10941 // Used with vargs to acumulate store chains. 10942 std::vector<SDValue> OutChains; 10943 10944 // Assign locations to all of the incoming arguments. 10945 SmallVector<CCValAssign, 16> ArgLocs; 10946 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10947 10948 if (CallConv == CallingConv::GHC) 10949 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10950 else 10951 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10952 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10953 : CC_RISCV); 10954 10955 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10956 CCValAssign &VA = ArgLocs[i]; 10957 SDValue ArgValue; 10958 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10959 // case. 10960 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10961 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10962 else if (VA.isRegLoc()) 10963 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10964 else 10965 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10966 10967 if (VA.getLocInfo() == CCValAssign::Indirect) { 10968 // If the original argument was split and passed by reference (e.g. i128 10969 // on RV32), we need to load all parts of it here (using the same 10970 // address). Vectors may be partly split to registers and partly to the 10971 // stack, in which case the base address is partly offset and subsequent 10972 // stores are relative to that. 10973 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10974 MachinePointerInfo())); 10975 unsigned ArgIndex = Ins[i].OrigArgIndex; 10976 unsigned ArgPartOffset = Ins[i].PartOffset; 10977 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10978 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10979 CCValAssign &PartVA = ArgLocs[i + 1]; 10980 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10981 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10982 if (PartVA.getValVT().isScalableVector()) 10983 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10984 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10985 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10986 MachinePointerInfo())); 10987 ++i; 10988 } 10989 continue; 10990 } 10991 InVals.push_back(ArgValue); 10992 } 10993 10994 if (IsVarArg) { 10995 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10996 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10997 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10998 MachineFrameInfo &MFI = MF.getFrameInfo(); 10999 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 11000 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 11001 11002 // Offset of the first variable argument from stack pointer, and size of 11003 // the vararg save area. For now, the varargs save area is either zero or 11004 // large enough to hold a0-a7. 11005 int VaArgOffset, VarArgsSaveSize; 11006 11007 // If all registers are allocated, then all varargs must be passed on the 11008 // stack and we don't need to save any argregs. 11009 if (ArgRegs.size() == Idx) { 11010 VaArgOffset = CCInfo.getNextStackOffset(); 11011 VarArgsSaveSize = 0; 11012 } else { 11013 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 11014 VaArgOffset = -VarArgsSaveSize; 11015 } 11016 11017 // Record the frame index of the first variable argument 11018 // which is a value necessary to VASTART. 11019 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 11020 RVFI->setVarArgsFrameIndex(FI); 11021 11022 // If saving an odd number of registers then create an extra stack slot to 11023 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 11024 // offsets to even-numbered registered remain 2*XLEN-aligned. 11025 if (Idx % 2) { 11026 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 11027 VarArgsSaveSize += XLenInBytes; 11028 } 11029 11030 // Copy the integer registers that may have been used for passing varargs 11031 // to the vararg save area. 11032 for (unsigned I = Idx; I < ArgRegs.size(); 11033 ++I, VaArgOffset += XLenInBytes) { 11034 const Register Reg = RegInfo.createVirtualRegister(RC); 11035 RegInfo.addLiveIn(ArgRegs[I], Reg); 11036 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 11037 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 11038 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 11039 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 11040 MachinePointerInfo::getFixedStack(MF, FI)); 11041 cast<StoreSDNode>(Store.getNode()) 11042 ->getMemOperand() 11043 ->setValue((Value *)nullptr); 11044 OutChains.push_back(Store); 11045 } 11046 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 11047 } 11048 11049 // All stores are grouped in one node to allow the matching between 11050 // the size of Ins and InVals. This only happens for vararg functions. 11051 if (!OutChains.empty()) { 11052 OutChains.push_back(Chain); 11053 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 11054 } 11055 11056 return Chain; 11057 } 11058 11059 /// isEligibleForTailCallOptimization - Check whether the call is eligible 11060 /// for tail call optimization. 11061 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 11062 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 11063 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 11064 const SmallVector<CCValAssign, 16> &ArgLocs) const { 11065 11066 auto &Callee = CLI.Callee; 11067 auto CalleeCC = CLI.CallConv; 11068 auto &Outs = CLI.Outs; 11069 auto &Caller = MF.getFunction(); 11070 auto CallerCC = Caller.getCallingConv(); 11071 11072 // Exception-handling functions need a special set of instructions to 11073 // indicate a return to the hardware. Tail-calling another function would 11074 // probably break this. 11075 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 11076 // should be expanded as new function attributes are introduced. 11077 if (Caller.hasFnAttribute("interrupt")) 11078 return false; 11079 11080 // Do not tail call opt if the stack is used to pass parameters. 11081 if (CCInfo.getNextStackOffset() != 0) 11082 return false; 11083 11084 // Do not tail call opt if any parameters need to be passed indirectly. 11085 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 11086 // passed indirectly. So the address of the value will be passed in a 11087 // register, or if not available, then the address is put on the stack. In 11088 // order to pass indirectly, space on the stack often needs to be allocated 11089 // in order to store the value. In this case the CCInfo.getNextStackOffset() 11090 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 11091 // are passed CCValAssign::Indirect. 11092 for (auto &VA : ArgLocs) 11093 if (VA.getLocInfo() == CCValAssign::Indirect) 11094 return false; 11095 11096 // Do not tail call opt if either caller or callee uses struct return 11097 // semantics. 11098 auto IsCallerStructRet = Caller.hasStructRetAttr(); 11099 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 11100 if (IsCallerStructRet || IsCalleeStructRet) 11101 return false; 11102 11103 // Externally-defined functions with weak linkage should not be 11104 // tail-called. The behaviour of branch instructions in this situation (as 11105 // used for tail calls) is implementation-defined, so we cannot rely on the 11106 // linker replacing the tail call with a return. 11107 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 11108 const GlobalValue *GV = G->getGlobal(); 11109 if (GV->hasExternalWeakLinkage()) 11110 return false; 11111 } 11112 11113 // The callee has to preserve all registers the caller needs to preserve. 11114 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11115 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 11116 if (CalleeCC != CallerCC) { 11117 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 11118 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 11119 return false; 11120 } 11121 11122 // Byval parameters hand the function a pointer directly into the stack area 11123 // we want to reuse during a tail call. Working around this *is* possible 11124 // but less efficient and uglier in LowerCall. 11125 for (auto &Arg : Outs) 11126 if (Arg.Flags.isByVal()) 11127 return false; 11128 11129 return true; 11130 } 11131 11132 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 11133 return DAG.getDataLayout().getPrefTypeAlign( 11134 VT.getTypeForEVT(*DAG.getContext())); 11135 } 11136 11137 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 11138 // and output parameter nodes. 11139 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 11140 SmallVectorImpl<SDValue> &InVals) const { 11141 SelectionDAG &DAG = CLI.DAG; 11142 SDLoc &DL = CLI.DL; 11143 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 11144 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 11145 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 11146 SDValue Chain = CLI.Chain; 11147 SDValue Callee = CLI.Callee; 11148 bool &IsTailCall = CLI.IsTailCall; 11149 CallingConv::ID CallConv = CLI.CallConv; 11150 bool IsVarArg = CLI.IsVarArg; 11151 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 11152 MVT XLenVT = Subtarget.getXLenVT(); 11153 11154 MachineFunction &MF = DAG.getMachineFunction(); 11155 11156 // Analyze the operands of the call, assigning locations to each operand. 11157 SmallVector<CCValAssign, 16> ArgLocs; 11158 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 11159 11160 if (CallConv == CallingConv::GHC) 11161 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 11162 else 11163 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 11164 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 11165 : CC_RISCV); 11166 11167 // Check if it's really possible to do a tail call. 11168 if (IsTailCall) 11169 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 11170 11171 if (IsTailCall) 11172 ++NumTailCalls; 11173 else if (CLI.CB && CLI.CB->isMustTailCall()) 11174 report_fatal_error("failed to perform tail call elimination on a call " 11175 "site marked musttail"); 11176 11177 // Get a count of how many bytes are to be pushed on the stack. 11178 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 11179 11180 // Create local copies for byval args 11181 SmallVector<SDValue, 8> ByValArgs; 11182 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 11183 ISD::ArgFlagsTy Flags = Outs[i].Flags; 11184 if (!Flags.isByVal()) 11185 continue; 11186 11187 SDValue Arg = OutVals[i]; 11188 unsigned Size = Flags.getByValSize(); 11189 Align Alignment = Flags.getNonZeroByValAlign(); 11190 11191 int FI = 11192 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 11193 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 11194 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 11195 11196 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 11197 /*IsVolatile=*/false, 11198 /*AlwaysInline=*/false, IsTailCall, 11199 MachinePointerInfo(), MachinePointerInfo()); 11200 ByValArgs.push_back(FIPtr); 11201 } 11202 11203 if (!IsTailCall) 11204 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 11205 11206 // Copy argument values to their designated locations. 11207 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 11208 SmallVector<SDValue, 8> MemOpChains; 11209 SDValue StackPtr; 11210 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 11211 CCValAssign &VA = ArgLocs[i]; 11212 SDValue ArgValue = OutVals[i]; 11213 ISD::ArgFlagsTy Flags = Outs[i].Flags; 11214 11215 // Handle passing f64 on RV32D with a soft float ABI as a special case. 11216 bool IsF64OnRV32DSoftABI = 11217 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 11218 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 11219 SDValue SplitF64 = DAG.getNode( 11220 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 11221 SDValue Lo = SplitF64.getValue(0); 11222 SDValue Hi = SplitF64.getValue(1); 11223 11224 Register RegLo = VA.getLocReg(); 11225 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 11226 11227 if (RegLo == RISCV::X17) { 11228 // Second half of f64 is passed on the stack. 11229 // Work out the address of the stack slot. 11230 if (!StackPtr.getNode()) 11231 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 11232 // Emit the store. 11233 MemOpChains.push_back( 11234 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 11235 } else { 11236 // Second half of f64 is passed in another GPR. 11237 assert(RegLo < RISCV::X31 && "Invalid register pair"); 11238 Register RegHigh = RegLo + 1; 11239 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 11240 } 11241 continue; 11242 } 11243 11244 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 11245 // as any other MemLoc. 11246 11247 // Promote the value if needed. 11248 // For now, only handle fully promoted and indirect arguments. 11249 if (VA.getLocInfo() == CCValAssign::Indirect) { 11250 // Store the argument in a stack slot and pass its address. 11251 Align StackAlign = 11252 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 11253 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 11254 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 11255 // If the original argument was split (e.g. i128), we need 11256 // to store the required parts of it here (and pass just one address). 11257 // Vectors may be partly split to registers and partly to the stack, in 11258 // which case the base address is partly offset and subsequent stores are 11259 // relative to that. 11260 unsigned ArgIndex = Outs[i].OrigArgIndex; 11261 unsigned ArgPartOffset = Outs[i].PartOffset; 11262 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 11263 // Calculate the total size to store. We don't have access to what we're 11264 // actually storing other than performing the loop and collecting the 11265 // info. 11266 SmallVector<std::pair<SDValue, SDValue>> Parts; 11267 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 11268 SDValue PartValue = OutVals[i + 1]; 11269 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 11270 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 11271 EVT PartVT = PartValue.getValueType(); 11272 if (PartVT.isScalableVector()) 11273 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 11274 StoredSize += PartVT.getStoreSize(); 11275 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 11276 Parts.push_back(std::make_pair(PartValue, Offset)); 11277 ++i; 11278 } 11279 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 11280 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 11281 MemOpChains.push_back( 11282 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 11283 MachinePointerInfo::getFixedStack(MF, FI))); 11284 for (const auto &Part : Parts) { 11285 SDValue PartValue = Part.first; 11286 SDValue PartOffset = Part.second; 11287 SDValue Address = 11288 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 11289 MemOpChains.push_back( 11290 DAG.getStore(Chain, DL, PartValue, Address, 11291 MachinePointerInfo::getFixedStack(MF, FI))); 11292 } 11293 ArgValue = SpillSlot; 11294 } else { 11295 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 11296 } 11297 11298 // Use local copy if it is a byval arg. 11299 if (Flags.isByVal()) 11300 ArgValue = ByValArgs[j++]; 11301 11302 if (VA.isRegLoc()) { 11303 // Queue up the argument copies and emit them at the end. 11304 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 11305 } else { 11306 assert(VA.isMemLoc() && "Argument not register or memory"); 11307 assert(!IsTailCall && "Tail call not allowed if stack is used " 11308 "for passing parameters"); 11309 11310 // Work out the address of the stack slot. 11311 if (!StackPtr.getNode()) 11312 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 11313 SDValue Address = 11314 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 11315 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 11316 11317 // Emit the store. 11318 MemOpChains.push_back( 11319 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 11320 } 11321 } 11322 11323 // Join the stores, which are independent of one another. 11324 if (!MemOpChains.empty()) 11325 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 11326 11327 SDValue Glue; 11328 11329 // Build a sequence of copy-to-reg nodes, chained and glued together. 11330 for (auto &Reg : RegsToPass) { 11331 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 11332 Glue = Chain.getValue(1); 11333 } 11334 11335 // Validate that none of the argument registers have been marked as 11336 // reserved, if so report an error. Do the same for the return address if this 11337 // is not a tailcall. 11338 validateCCReservedRegs(RegsToPass, MF); 11339 if (!IsTailCall && 11340 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 11341 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11342 MF.getFunction(), 11343 "Return address register required, but has been reserved."}); 11344 11345 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 11346 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 11347 // split it and then direct call can be matched by PseudoCALL. 11348 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 11349 const GlobalValue *GV = S->getGlobal(); 11350 11351 unsigned OpFlags = RISCVII::MO_CALL; 11352 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 11353 OpFlags = RISCVII::MO_PLT; 11354 11355 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 11356 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 11357 unsigned OpFlags = RISCVII::MO_CALL; 11358 11359 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 11360 nullptr)) 11361 OpFlags = RISCVII::MO_PLT; 11362 11363 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 11364 } 11365 11366 // The first call operand is the chain and the second is the target address. 11367 SmallVector<SDValue, 8> Ops; 11368 Ops.push_back(Chain); 11369 Ops.push_back(Callee); 11370 11371 // Add argument registers to the end of the list so that they are 11372 // known live into the call. 11373 for (auto &Reg : RegsToPass) 11374 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 11375 11376 if (!IsTailCall) { 11377 // Add a register mask operand representing the call-preserved registers. 11378 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11379 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 11380 assert(Mask && "Missing call preserved mask for calling convention"); 11381 Ops.push_back(DAG.getRegisterMask(Mask)); 11382 } 11383 11384 // Glue the call to the argument copies, if any. 11385 if (Glue.getNode()) 11386 Ops.push_back(Glue); 11387 11388 // Emit the call. 11389 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 11390 11391 if (IsTailCall) { 11392 MF.getFrameInfo().setHasTailCall(); 11393 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 11394 } 11395 11396 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 11397 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 11398 Glue = Chain.getValue(1); 11399 11400 // Mark the end of the call, which is glued to the call itself. 11401 Chain = DAG.getCALLSEQ_END(Chain, 11402 DAG.getConstant(NumBytes, DL, PtrVT, true), 11403 DAG.getConstant(0, DL, PtrVT, true), 11404 Glue, DL); 11405 Glue = Chain.getValue(1); 11406 11407 // Assign locations to each value returned by this call. 11408 SmallVector<CCValAssign, 16> RVLocs; 11409 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 11410 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 11411 11412 // Copy all of the result registers out of their specified physreg. 11413 for (auto &VA : RVLocs) { 11414 // Copy the value out 11415 SDValue RetValue = 11416 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 11417 // Glue the RetValue to the end of the call sequence 11418 Chain = RetValue.getValue(1); 11419 Glue = RetValue.getValue(2); 11420 11421 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 11422 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 11423 SDValue RetValue2 = 11424 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 11425 Chain = RetValue2.getValue(1); 11426 Glue = RetValue2.getValue(2); 11427 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 11428 RetValue2); 11429 } 11430 11431 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 11432 11433 InVals.push_back(RetValue); 11434 } 11435 11436 return Chain; 11437 } 11438 11439 bool RISCVTargetLowering::CanLowerReturn( 11440 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 11441 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 11442 SmallVector<CCValAssign, 16> RVLocs; 11443 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 11444 11445 Optional<unsigned> FirstMaskArgument; 11446 if (Subtarget.hasVInstructions()) 11447 FirstMaskArgument = preAssignMask(Outs); 11448 11449 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 11450 MVT VT = Outs[i].VT; 11451 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 11452 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 11453 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 11454 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 11455 *this, FirstMaskArgument)) 11456 return false; 11457 } 11458 return true; 11459 } 11460 11461 SDValue 11462 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 11463 bool IsVarArg, 11464 const SmallVectorImpl<ISD::OutputArg> &Outs, 11465 const SmallVectorImpl<SDValue> &OutVals, 11466 const SDLoc &DL, SelectionDAG &DAG) const { 11467 const MachineFunction &MF = DAG.getMachineFunction(); 11468 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 11469 11470 // Stores the assignment of the return value to a location. 11471 SmallVector<CCValAssign, 16> RVLocs; 11472 11473 // Info about the registers and stack slot. 11474 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 11475 *DAG.getContext()); 11476 11477 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 11478 nullptr, CC_RISCV); 11479 11480 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 11481 report_fatal_error("GHC functions return void only"); 11482 11483 SDValue Glue; 11484 SmallVector<SDValue, 4> RetOps(1, Chain); 11485 11486 // Copy the result values into the output registers. 11487 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 11488 SDValue Val = OutVals[i]; 11489 CCValAssign &VA = RVLocs[i]; 11490 assert(VA.isRegLoc() && "Can only return in registers!"); 11491 11492 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 11493 // Handle returning f64 on RV32D with a soft float ABI. 11494 assert(VA.isRegLoc() && "Expected return via registers"); 11495 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 11496 DAG.getVTList(MVT::i32, MVT::i32), Val); 11497 SDValue Lo = SplitF64.getValue(0); 11498 SDValue Hi = SplitF64.getValue(1); 11499 Register RegLo = VA.getLocReg(); 11500 assert(RegLo < RISCV::X31 && "Invalid register pair"); 11501 Register RegHi = RegLo + 1; 11502 11503 if (STI.isRegisterReservedByUser(RegLo) || 11504 STI.isRegisterReservedByUser(RegHi)) 11505 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11506 MF.getFunction(), 11507 "Return value register required, but has been reserved."}); 11508 11509 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 11510 Glue = Chain.getValue(1); 11511 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 11512 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 11513 Glue = Chain.getValue(1); 11514 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 11515 } else { 11516 // Handle a 'normal' return. 11517 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 11518 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 11519 11520 if (STI.isRegisterReservedByUser(VA.getLocReg())) 11521 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11522 MF.getFunction(), 11523 "Return value register required, but has been reserved."}); 11524 11525 // Guarantee that all emitted copies are stuck together. 11526 Glue = Chain.getValue(1); 11527 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 11528 } 11529 } 11530 11531 RetOps[0] = Chain; // Update chain. 11532 11533 // Add the glue node if we have it. 11534 if (Glue.getNode()) { 11535 RetOps.push_back(Glue); 11536 } 11537 11538 unsigned RetOpc = RISCVISD::RET_FLAG; 11539 // Interrupt service routines use different return instructions. 11540 const Function &Func = DAG.getMachineFunction().getFunction(); 11541 if (Func.hasFnAttribute("interrupt")) { 11542 if (!Func.getReturnType()->isVoidTy()) 11543 report_fatal_error( 11544 "Functions with the interrupt attribute must have void return type!"); 11545 11546 MachineFunction &MF = DAG.getMachineFunction(); 11547 StringRef Kind = 11548 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 11549 11550 if (Kind == "user") 11551 RetOpc = RISCVISD::URET_FLAG; 11552 else if (Kind == "supervisor") 11553 RetOpc = RISCVISD::SRET_FLAG; 11554 else 11555 RetOpc = RISCVISD::MRET_FLAG; 11556 } 11557 11558 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 11559 } 11560 11561 void RISCVTargetLowering::validateCCReservedRegs( 11562 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 11563 MachineFunction &MF) const { 11564 const Function &F = MF.getFunction(); 11565 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 11566 11567 if (llvm::any_of(Regs, [&STI](auto Reg) { 11568 return STI.isRegisterReservedByUser(Reg.first); 11569 })) 11570 F.getContext().diagnose(DiagnosticInfoUnsupported{ 11571 F, "Argument register required, but has been reserved."}); 11572 } 11573 11574 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 11575 return CI->isTailCall(); 11576 } 11577 11578 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 11579 #define NODE_NAME_CASE(NODE) \ 11580 case RISCVISD::NODE: \ 11581 return "RISCVISD::" #NODE; 11582 // clang-format off 11583 switch ((RISCVISD::NodeType)Opcode) { 11584 case RISCVISD::FIRST_NUMBER: 11585 break; 11586 NODE_NAME_CASE(RET_FLAG) 11587 NODE_NAME_CASE(URET_FLAG) 11588 NODE_NAME_CASE(SRET_FLAG) 11589 NODE_NAME_CASE(MRET_FLAG) 11590 NODE_NAME_CASE(CALL) 11591 NODE_NAME_CASE(SELECT_CC) 11592 NODE_NAME_CASE(BR_CC) 11593 NODE_NAME_CASE(BuildPairF64) 11594 NODE_NAME_CASE(SplitF64) 11595 NODE_NAME_CASE(TAIL) 11596 NODE_NAME_CASE(ADD_LO) 11597 NODE_NAME_CASE(HI) 11598 NODE_NAME_CASE(LLA) 11599 NODE_NAME_CASE(ADD_TPREL) 11600 NODE_NAME_CASE(LA) 11601 NODE_NAME_CASE(LA_TLS_IE) 11602 NODE_NAME_CASE(LA_TLS_GD) 11603 NODE_NAME_CASE(MULHSU) 11604 NODE_NAME_CASE(SLLW) 11605 NODE_NAME_CASE(SRAW) 11606 NODE_NAME_CASE(SRLW) 11607 NODE_NAME_CASE(DIVW) 11608 NODE_NAME_CASE(DIVUW) 11609 NODE_NAME_CASE(REMUW) 11610 NODE_NAME_CASE(ROLW) 11611 NODE_NAME_CASE(RORW) 11612 NODE_NAME_CASE(CLZW) 11613 NODE_NAME_CASE(CTZW) 11614 NODE_NAME_CASE(FSLW) 11615 NODE_NAME_CASE(FSRW) 11616 NODE_NAME_CASE(FSL) 11617 NODE_NAME_CASE(FSR) 11618 NODE_NAME_CASE(FMV_H_X) 11619 NODE_NAME_CASE(FMV_X_ANYEXTH) 11620 NODE_NAME_CASE(FMV_X_SIGNEXTH) 11621 NODE_NAME_CASE(FMV_W_X_RV64) 11622 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 11623 NODE_NAME_CASE(FCVT_X) 11624 NODE_NAME_CASE(FCVT_XU) 11625 NODE_NAME_CASE(FCVT_W_RV64) 11626 NODE_NAME_CASE(FCVT_WU_RV64) 11627 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 11628 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 11629 NODE_NAME_CASE(READ_CYCLE_WIDE) 11630 NODE_NAME_CASE(GREV) 11631 NODE_NAME_CASE(GREVW) 11632 NODE_NAME_CASE(GORC) 11633 NODE_NAME_CASE(GORCW) 11634 NODE_NAME_CASE(SHFL) 11635 NODE_NAME_CASE(SHFLW) 11636 NODE_NAME_CASE(UNSHFL) 11637 NODE_NAME_CASE(UNSHFLW) 11638 NODE_NAME_CASE(BFP) 11639 NODE_NAME_CASE(BFPW) 11640 NODE_NAME_CASE(BCOMPRESS) 11641 NODE_NAME_CASE(BCOMPRESSW) 11642 NODE_NAME_CASE(BDECOMPRESS) 11643 NODE_NAME_CASE(BDECOMPRESSW) 11644 NODE_NAME_CASE(VMV_V_X_VL) 11645 NODE_NAME_CASE(VFMV_V_F_VL) 11646 NODE_NAME_CASE(VMV_X_S) 11647 NODE_NAME_CASE(VMV_S_X_VL) 11648 NODE_NAME_CASE(VFMV_S_F_VL) 11649 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 11650 NODE_NAME_CASE(READ_VLENB) 11651 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 11652 NODE_NAME_CASE(VSLIDEUP_VL) 11653 NODE_NAME_CASE(VSLIDE1UP_VL) 11654 NODE_NAME_CASE(VSLIDEDOWN_VL) 11655 NODE_NAME_CASE(VSLIDE1DOWN_VL) 11656 NODE_NAME_CASE(VID_VL) 11657 NODE_NAME_CASE(VFNCVT_ROD_VL) 11658 NODE_NAME_CASE(VECREDUCE_ADD_VL) 11659 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 11660 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 11661 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 11662 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 11663 NODE_NAME_CASE(VECREDUCE_AND_VL) 11664 NODE_NAME_CASE(VECREDUCE_OR_VL) 11665 NODE_NAME_CASE(VECREDUCE_XOR_VL) 11666 NODE_NAME_CASE(VECREDUCE_FADD_VL) 11667 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 11668 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 11669 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 11670 NODE_NAME_CASE(ADD_VL) 11671 NODE_NAME_CASE(AND_VL) 11672 NODE_NAME_CASE(MUL_VL) 11673 NODE_NAME_CASE(OR_VL) 11674 NODE_NAME_CASE(SDIV_VL) 11675 NODE_NAME_CASE(SHL_VL) 11676 NODE_NAME_CASE(SREM_VL) 11677 NODE_NAME_CASE(SRA_VL) 11678 NODE_NAME_CASE(SRL_VL) 11679 NODE_NAME_CASE(SUB_VL) 11680 NODE_NAME_CASE(UDIV_VL) 11681 NODE_NAME_CASE(UREM_VL) 11682 NODE_NAME_CASE(XOR_VL) 11683 NODE_NAME_CASE(SADDSAT_VL) 11684 NODE_NAME_CASE(UADDSAT_VL) 11685 NODE_NAME_CASE(SSUBSAT_VL) 11686 NODE_NAME_CASE(USUBSAT_VL) 11687 NODE_NAME_CASE(FADD_VL) 11688 NODE_NAME_CASE(FSUB_VL) 11689 NODE_NAME_CASE(FMUL_VL) 11690 NODE_NAME_CASE(FDIV_VL) 11691 NODE_NAME_CASE(FNEG_VL) 11692 NODE_NAME_CASE(FABS_VL) 11693 NODE_NAME_CASE(FSQRT_VL) 11694 NODE_NAME_CASE(VFMADD_VL) 11695 NODE_NAME_CASE(VFNMADD_VL) 11696 NODE_NAME_CASE(VFMSUB_VL) 11697 NODE_NAME_CASE(VFNMSUB_VL) 11698 NODE_NAME_CASE(FCOPYSIGN_VL) 11699 NODE_NAME_CASE(SMIN_VL) 11700 NODE_NAME_CASE(SMAX_VL) 11701 NODE_NAME_CASE(UMIN_VL) 11702 NODE_NAME_CASE(UMAX_VL) 11703 NODE_NAME_CASE(FMINNUM_VL) 11704 NODE_NAME_CASE(FMAXNUM_VL) 11705 NODE_NAME_CASE(MULHS_VL) 11706 NODE_NAME_CASE(MULHU_VL) 11707 NODE_NAME_CASE(FP_TO_SINT_VL) 11708 NODE_NAME_CASE(FP_TO_UINT_VL) 11709 NODE_NAME_CASE(SINT_TO_FP_VL) 11710 NODE_NAME_CASE(UINT_TO_FP_VL) 11711 NODE_NAME_CASE(FP_EXTEND_VL) 11712 NODE_NAME_CASE(FP_ROUND_VL) 11713 NODE_NAME_CASE(VWMUL_VL) 11714 NODE_NAME_CASE(VWMULU_VL) 11715 NODE_NAME_CASE(VWMULSU_VL) 11716 NODE_NAME_CASE(VWADD_VL) 11717 NODE_NAME_CASE(VWADDU_VL) 11718 NODE_NAME_CASE(VWSUB_VL) 11719 NODE_NAME_CASE(VWSUBU_VL) 11720 NODE_NAME_CASE(VWADD_W_VL) 11721 NODE_NAME_CASE(VWADDU_W_VL) 11722 NODE_NAME_CASE(VWSUB_W_VL) 11723 NODE_NAME_CASE(VWSUBU_W_VL) 11724 NODE_NAME_CASE(SETCC_VL) 11725 NODE_NAME_CASE(VSELECT_VL) 11726 NODE_NAME_CASE(VP_MERGE_VL) 11727 NODE_NAME_CASE(VMAND_VL) 11728 NODE_NAME_CASE(VMOR_VL) 11729 NODE_NAME_CASE(VMXOR_VL) 11730 NODE_NAME_CASE(VMCLR_VL) 11731 NODE_NAME_CASE(VMSET_VL) 11732 NODE_NAME_CASE(VRGATHER_VX_VL) 11733 NODE_NAME_CASE(VRGATHER_VV_VL) 11734 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 11735 NODE_NAME_CASE(VSEXT_VL) 11736 NODE_NAME_CASE(VZEXT_VL) 11737 NODE_NAME_CASE(VCPOP_VL) 11738 NODE_NAME_CASE(READ_CSR) 11739 NODE_NAME_CASE(WRITE_CSR) 11740 NODE_NAME_CASE(SWAP_CSR) 11741 } 11742 // clang-format on 11743 return nullptr; 11744 #undef NODE_NAME_CASE 11745 } 11746 11747 /// getConstraintType - Given a constraint letter, return the type of 11748 /// constraint it is for this target. 11749 RISCVTargetLowering::ConstraintType 11750 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 11751 if (Constraint.size() == 1) { 11752 switch (Constraint[0]) { 11753 default: 11754 break; 11755 case 'f': 11756 return C_RegisterClass; 11757 case 'I': 11758 case 'J': 11759 case 'K': 11760 return C_Immediate; 11761 case 'A': 11762 return C_Memory; 11763 case 'S': // A symbolic address 11764 return C_Other; 11765 } 11766 } else { 11767 if (Constraint == "vr" || Constraint == "vm") 11768 return C_RegisterClass; 11769 } 11770 return TargetLowering::getConstraintType(Constraint); 11771 } 11772 11773 std::pair<unsigned, const TargetRegisterClass *> 11774 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11775 StringRef Constraint, 11776 MVT VT) const { 11777 // First, see if this is a constraint that directly corresponds to a 11778 // RISCV register class. 11779 if (Constraint.size() == 1) { 11780 switch (Constraint[0]) { 11781 case 'r': 11782 // TODO: Support fixed vectors up to XLen for P extension? 11783 if (VT.isVector()) 11784 break; 11785 return std::make_pair(0U, &RISCV::GPRRegClass); 11786 case 'f': 11787 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 11788 return std::make_pair(0U, &RISCV::FPR16RegClass); 11789 if (Subtarget.hasStdExtF() && VT == MVT::f32) 11790 return std::make_pair(0U, &RISCV::FPR32RegClass); 11791 if (Subtarget.hasStdExtD() && VT == MVT::f64) 11792 return std::make_pair(0U, &RISCV::FPR64RegClass); 11793 break; 11794 default: 11795 break; 11796 } 11797 } else if (Constraint == "vr") { 11798 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 11799 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11800 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 11801 return std::make_pair(0U, RC); 11802 } 11803 } else if (Constraint == "vm") { 11804 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 11805 return std::make_pair(0U, &RISCV::VMV0RegClass); 11806 } 11807 11808 // Clang will correctly decode the usage of register name aliases into their 11809 // official names. However, other frontends like `rustc` do not. This allows 11810 // users of these frontends to use the ABI names for registers in LLVM-style 11811 // register constraints. 11812 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 11813 .Case("{zero}", RISCV::X0) 11814 .Case("{ra}", RISCV::X1) 11815 .Case("{sp}", RISCV::X2) 11816 .Case("{gp}", RISCV::X3) 11817 .Case("{tp}", RISCV::X4) 11818 .Case("{t0}", RISCV::X5) 11819 .Case("{t1}", RISCV::X6) 11820 .Case("{t2}", RISCV::X7) 11821 .Cases("{s0}", "{fp}", RISCV::X8) 11822 .Case("{s1}", RISCV::X9) 11823 .Case("{a0}", RISCV::X10) 11824 .Case("{a1}", RISCV::X11) 11825 .Case("{a2}", RISCV::X12) 11826 .Case("{a3}", RISCV::X13) 11827 .Case("{a4}", RISCV::X14) 11828 .Case("{a5}", RISCV::X15) 11829 .Case("{a6}", RISCV::X16) 11830 .Case("{a7}", RISCV::X17) 11831 .Case("{s2}", RISCV::X18) 11832 .Case("{s3}", RISCV::X19) 11833 .Case("{s4}", RISCV::X20) 11834 .Case("{s5}", RISCV::X21) 11835 .Case("{s6}", RISCV::X22) 11836 .Case("{s7}", RISCV::X23) 11837 .Case("{s8}", RISCV::X24) 11838 .Case("{s9}", RISCV::X25) 11839 .Case("{s10}", RISCV::X26) 11840 .Case("{s11}", RISCV::X27) 11841 .Case("{t3}", RISCV::X28) 11842 .Case("{t4}", RISCV::X29) 11843 .Case("{t5}", RISCV::X30) 11844 .Case("{t6}", RISCV::X31) 11845 .Default(RISCV::NoRegister); 11846 if (XRegFromAlias != RISCV::NoRegister) 11847 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 11848 11849 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 11850 // TableGen record rather than the AsmName to choose registers for InlineAsm 11851 // constraints, plus we want to match those names to the widest floating point 11852 // register type available, manually select floating point registers here. 11853 // 11854 // The second case is the ABI name of the register, so that frontends can also 11855 // use the ABI names in register constraint lists. 11856 if (Subtarget.hasStdExtF()) { 11857 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 11858 .Cases("{f0}", "{ft0}", RISCV::F0_F) 11859 .Cases("{f1}", "{ft1}", RISCV::F1_F) 11860 .Cases("{f2}", "{ft2}", RISCV::F2_F) 11861 .Cases("{f3}", "{ft3}", RISCV::F3_F) 11862 .Cases("{f4}", "{ft4}", RISCV::F4_F) 11863 .Cases("{f5}", "{ft5}", RISCV::F5_F) 11864 .Cases("{f6}", "{ft6}", RISCV::F6_F) 11865 .Cases("{f7}", "{ft7}", RISCV::F7_F) 11866 .Cases("{f8}", "{fs0}", RISCV::F8_F) 11867 .Cases("{f9}", "{fs1}", RISCV::F9_F) 11868 .Cases("{f10}", "{fa0}", RISCV::F10_F) 11869 .Cases("{f11}", "{fa1}", RISCV::F11_F) 11870 .Cases("{f12}", "{fa2}", RISCV::F12_F) 11871 .Cases("{f13}", "{fa3}", RISCV::F13_F) 11872 .Cases("{f14}", "{fa4}", RISCV::F14_F) 11873 .Cases("{f15}", "{fa5}", RISCV::F15_F) 11874 .Cases("{f16}", "{fa6}", RISCV::F16_F) 11875 .Cases("{f17}", "{fa7}", RISCV::F17_F) 11876 .Cases("{f18}", "{fs2}", RISCV::F18_F) 11877 .Cases("{f19}", "{fs3}", RISCV::F19_F) 11878 .Cases("{f20}", "{fs4}", RISCV::F20_F) 11879 .Cases("{f21}", "{fs5}", RISCV::F21_F) 11880 .Cases("{f22}", "{fs6}", RISCV::F22_F) 11881 .Cases("{f23}", "{fs7}", RISCV::F23_F) 11882 .Cases("{f24}", "{fs8}", RISCV::F24_F) 11883 .Cases("{f25}", "{fs9}", RISCV::F25_F) 11884 .Cases("{f26}", "{fs10}", RISCV::F26_F) 11885 .Cases("{f27}", "{fs11}", RISCV::F27_F) 11886 .Cases("{f28}", "{ft8}", RISCV::F28_F) 11887 .Cases("{f29}", "{ft9}", RISCV::F29_F) 11888 .Cases("{f30}", "{ft10}", RISCV::F30_F) 11889 .Cases("{f31}", "{ft11}", RISCV::F31_F) 11890 .Default(RISCV::NoRegister); 11891 if (FReg != RISCV::NoRegister) { 11892 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 11893 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 11894 unsigned RegNo = FReg - RISCV::F0_F; 11895 unsigned DReg = RISCV::F0_D + RegNo; 11896 return std::make_pair(DReg, &RISCV::FPR64RegClass); 11897 } 11898 if (VT == MVT::f32 || VT == MVT::Other) 11899 return std::make_pair(FReg, &RISCV::FPR32RegClass); 11900 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 11901 unsigned RegNo = FReg - RISCV::F0_F; 11902 unsigned HReg = RISCV::F0_H + RegNo; 11903 return std::make_pair(HReg, &RISCV::FPR16RegClass); 11904 } 11905 } 11906 } 11907 11908 if (Subtarget.hasVInstructions()) { 11909 Register VReg = StringSwitch<Register>(Constraint.lower()) 11910 .Case("{v0}", RISCV::V0) 11911 .Case("{v1}", RISCV::V1) 11912 .Case("{v2}", RISCV::V2) 11913 .Case("{v3}", RISCV::V3) 11914 .Case("{v4}", RISCV::V4) 11915 .Case("{v5}", RISCV::V5) 11916 .Case("{v6}", RISCV::V6) 11917 .Case("{v7}", RISCV::V7) 11918 .Case("{v8}", RISCV::V8) 11919 .Case("{v9}", RISCV::V9) 11920 .Case("{v10}", RISCV::V10) 11921 .Case("{v11}", RISCV::V11) 11922 .Case("{v12}", RISCV::V12) 11923 .Case("{v13}", RISCV::V13) 11924 .Case("{v14}", RISCV::V14) 11925 .Case("{v15}", RISCV::V15) 11926 .Case("{v16}", RISCV::V16) 11927 .Case("{v17}", RISCV::V17) 11928 .Case("{v18}", RISCV::V18) 11929 .Case("{v19}", RISCV::V19) 11930 .Case("{v20}", RISCV::V20) 11931 .Case("{v21}", RISCV::V21) 11932 .Case("{v22}", RISCV::V22) 11933 .Case("{v23}", RISCV::V23) 11934 .Case("{v24}", RISCV::V24) 11935 .Case("{v25}", RISCV::V25) 11936 .Case("{v26}", RISCV::V26) 11937 .Case("{v27}", RISCV::V27) 11938 .Case("{v28}", RISCV::V28) 11939 .Case("{v29}", RISCV::V29) 11940 .Case("{v30}", RISCV::V30) 11941 .Case("{v31}", RISCV::V31) 11942 .Default(RISCV::NoRegister); 11943 if (VReg != RISCV::NoRegister) { 11944 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11945 return std::make_pair(VReg, &RISCV::VMRegClass); 11946 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11947 return std::make_pair(VReg, &RISCV::VRRegClass); 11948 for (const auto *RC : 11949 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11950 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11951 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11952 return std::make_pair(VReg, RC); 11953 } 11954 } 11955 } 11956 } 11957 11958 std::pair<Register, const TargetRegisterClass *> Res = 11959 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11960 11961 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11962 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11963 // Subtarget into account. 11964 if (Res.second == &RISCV::GPRF16RegClass || 11965 Res.second == &RISCV::GPRF32RegClass || 11966 Res.second == &RISCV::GPRF64RegClass) 11967 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11968 11969 return Res; 11970 } 11971 11972 unsigned 11973 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11974 // Currently only support length 1 constraints. 11975 if (ConstraintCode.size() == 1) { 11976 switch (ConstraintCode[0]) { 11977 case 'A': 11978 return InlineAsm::Constraint_A; 11979 default: 11980 break; 11981 } 11982 } 11983 11984 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11985 } 11986 11987 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11988 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11989 SelectionDAG &DAG) const { 11990 // Currently only support length 1 constraints. 11991 if (Constraint.length() == 1) { 11992 switch (Constraint[0]) { 11993 case 'I': 11994 // Validate & create a 12-bit signed immediate operand. 11995 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11996 uint64_t CVal = C->getSExtValue(); 11997 if (isInt<12>(CVal)) 11998 Ops.push_back( 11999 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 12000 } 12001 return; 12002 case 'J': 12003 // Validate & create an integer zero operand. 12004 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 12005 if (C->getZExtValue() == 0) 12006 Ops.push_back( 12007 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 12008 return; 12009 case 'K': 12010 // Validate & create a 5-bit unsigned immediate operand. 12011 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 12012 uint64_t CVal = C->getZExtValue(); 12013 if (isUInt<5>(CVal)) 12014 Ops.push_back( 12015 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 12016 } 12017 return; 12018 case 'S': 12019 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 12020 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 12021 GA->getValueType(0))); 12022 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 12023 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 12024 BA->getValueType(0))); 12025 } 12026 return; 12027 default: 12028 break; 12029 } 12030 } 12031 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 12032 } 12033 12034 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 12035 Instruction *Inst, 12036 AtomicOrdering Ord) const { 12037 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 12038 return Builder.CreateFence(Ord); 12039 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 12040 return Builder.CreateFence(AtomicOrdering::Release); 12041 return nullptr; 12042 } 12043 12044 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 12045 Instruction *Inst, 12046 AtomicOrdering Ord) const { 12047 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 12048 return Builder.CreateFence(AtomicOrdering::Acquire); 12049 return nullptr; 12050 } 12051 12052 TargetLowering::AtomicExpansionKind 12053 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 12054 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 12055 // point operations can't be used in an lr/sc sequence without breaking the 12056 // forward-progress guarantee. 12057 if (AI->isFloatingPointOperation()) 12058 return AtomicExpansionKind::CmpXChg; 12059 12060 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 12061 if (Size == 8 || Size == 16) 12062 return AtomicExpansionKind::MaskedIntrinsic; 12063 return AtomicExpansionKind::None; 12064 } 12065 12066 static Intrinsic::ID 12067 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 12068 if (XLen == 32) { 12069 switch (BinOp) { 12070 default: 12071 llvm_unreachable("Unexpected AtomicRMW BinOp"); 12072 case AtomicRMWInst::Xchg: 12073 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 12074 case AtomicRMWInst::Add: 12075 return Intrinsic::riscv_masked_atomicrmw_add_i32; 12076 case AtomicRMWInst::Sub: 12077 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 12078 case AtomicRMWInst::Nand: 12079 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 12080 case AtomicRMWInst::Max: 12081 return Intrinsic::riscv_masked_atomicrmw_max_i32; 12082 case AtomicRMWInst::Min: 12083 return Intrinsic::riscv_masked_atomicrmw_min_i32; 12084 case AtomicRMWInst::UMax: 12085 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 12086 case AtomicRMWInst::UMin: 12087 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 12088 } 12089 } 12090 12091 if (XLen == 64) { 12092 switch (BinOp) { 12093 default: 12094 llvm_unreachable("Unexpected AtomicRMW BinOp"); 12095 case AtomicRMWInst::Xchg: 12096 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 12097 case AtomicRMWInst::Add: 12098 return Intrinsic::riscv_masked_atomicrmw_add_i64; 12099 case AtomicRMWInst::Sub: 12100 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 12101 case AtomicRMWInst::Nand: 12102 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 12103 case AtomicRMWInst::Max: 12104 return Intrinsic::riscv_masked_atomicrmw_max_i64; 12105 case AtomicRMWInst::Min: 12106 return Intrinsic::riscv_masked_atomicrmw_min_i64; 12107 case AtomicRMWInst::UMax: 12108 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 12109 case AtomicRMWInst::UMin: 12110 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 12111 } 12112 } 12113 12114 llvm_unreachable("Unexpected XLen\n"); 12115 } 12116 12117 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 12118 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 12119 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 12120 unsigned XLen = Subtarget.getXLen(); 12121 Value *Ordering = 12122 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 12123 Type *Tys[] = {AlignedAddr->getType()}; 12124 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 12125 AI->getModule(), 12126 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 12127 12128 if (XLen == 64) { 12129 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 12130 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 12131 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 12132 } 12133 12134 Value *Result; 12135 12136 // Must pass the shift amount needed to sign extend the loaded value prior 12137 // to performing a signed comparison for min/max. ShiftAmt is the number of 12138 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 12139 // is the number of bits to left+right shift the value in order to 12140 // sign-extend. 12141 if (AI->getOperation() == AtomicRMWInst::Min || 12142 AI->getOperation() == AtomicRMWInst::Max) { 12143 const DataLayout &DL = AI->getModule()->getDataLayout(); 12144 unsigned ValWidth = 12145 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 12146 Value *SextShamt = 12147 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 12148 Result = Builder.CreateCall(LrwOpScwLoop, 12149 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 12150 } else { 12151 Result = 12152 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 12153 } 12154 12155 if (XLen == 64) 12156 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 12157 return Result; 12158 } 12159 12160 TargetLowering::AtomicExpansionKind 12161 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 12162 AtomicCmpXchgInst *CI) const { 12163 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 12164 if (Size == 8 || Size == 16) 12165 return AtomicExpansionKind::MaskedIntrinsic; 12166 return AtomicExpansionKind::None; 12167 } 12168 12169 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 12170 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 12171 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 12172 unsigned XLen = Subtarget.getXLen(); 12173 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 12174 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 12175 if (XLen == 64) { 12176 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 12177 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 12178 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 12179 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 12180 } 12181 Type *Tys[] = {AlignedAddr->getType()}; 12182 Function *MaskedCmpXchg = 12183 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 12184 Value *Result = Builder.CreateCall( 12185 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 12186 if (XLen == 64) 12187 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 12188 return Result; 12189 } 12190 12191 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT, 12192 EVT DataVT) const { 12193 return false; 12194 } 12195 12196 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 12197 EVT VT) const { 12198 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 12199 return false; 12200 12201 switch (FPVT.getSimpleVT().SimpleTy) { 12202 case MVT::f16: 12203 return Subtarget.hasStdExtZfh(); 12204 case MVT::f32: 12205 return Subtarget.hasStdExtF(); 12206 case MVT::f64: 12207 return Subtarget.hasStdExtD(); 12208 default: 12209 return false; 12210 } 12211 } 12212 12213 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 12214 // If we are using the small code model, we can reduce size of jump table 12215 // entry to 4 bytes. 12216 if (Subtarget.is64Bit() && !isPositionIndependent() && 12217 getTargetMachine().getCodeModel() == CodeModel::Small) { 12218 return MachineJumpTableInfo::EK_Custom32; 12219 } 12220 return TargetLowering::getJumpTableEncoding(); 12221 } 12222 12223 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 12224 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 12225 unsigned uid, MCContext &Ctx) const { 12226 assert(Subtarget.is64Bit() && !isPositionIndependent() && 12227 getTargetMachine().getCodeModel() == CodeModel::Small); 12228 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 12229 } 12230 12231 bool RISCVTargetLowering::isVScaleKnownToBeAPowerOfTwo() const { 12232 // We define vscale to be VLEN/RVVBitsPerBlock. VLEN is always a power 12233 // of two >= 64, and RVVBitsPerBlock is 64. Thus, vscale must be 12234 // a power of two as well. 12235 // FIXME: This doesn't work for zve32, but that's already broken 12236 // elsewhere for the same reason. 12237 assert(Subtarget.getRealMinVLen() >= 64 && "zve32* unsupported"); 12238 static_assert(RISCV::RVVBitsPerBlock == 64, 12239 "RVVBitsPerBlock changed, audit needed"); 12240 return true; 12241 } 12242 12243 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 12244 EVT VT) const { 12245 VT = VT.getScalarType(); 12246 12247 if (!VT.isSimple()) 12248 return false; 12249 12250 switch (VT.getSimpleVT().SimpleTy) { 12251 case MVT::f16: 12252 return Subtarget.hasStdExtZfh(); 12253 case MVT::f32: 12254 return Subtarget.hasStdExtF(); 12255 case MVT::f64: 12256 return Subtarget.hasStdExtD(); 12257 default: 12258 break; 12259 } 12260 12261 return false; 12262 } 12263 12264 Register RISCVTargetLowering::getExceptionPointerRegister( 12265 const Constant *PersonalityFn) const { 12266 return RISCV::X10; 12267 } 12268 12269 Register RISCVTargetLowering::getExceptionSelectorRegister( 12270 const Constant *PersonalityFn) const { 12271 return RISCV::X11; 12272 } 12273 12274 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 12275 // Return false to suppress the unnecessary extensions if the LibCall 12276 // arguments or return value is f32 type for LP64 ABI. 12277 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 12278 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 12279 return false; 12280 12281 return true; 12282 } 12283 12284 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 12285 if (Subtarget.is64Bit() && Type == MVT::i32) 12286 return true; 12287 12288 return IsSigned; 12289 } 12290 12291 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 12292 SDValue C) const { 12293 // Check integral scalar types. 12294 const bool HasExtMOrZmmul = 12295 Subtarget.hasStdExtM() || Subtarget.hasStdExtZmmul(); 12296 if (VT.isScalarInteger()) { 12297 // Omit the optimization if the sub target has the M extension and the data 12298 // size exceeds XLen. 12299 if (HasExtMOrZmmul && VT.getSizeInBits() > Subtarget.getXLen()) 12300 return false; 12301 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 12302 // Break the MUL to a SLLI and an ADD/SUB. 12303 const APInt &Imm = ConstNode->getAPIntValue(); 12304 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 12305 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 12306 return true; 12307 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 12308 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 12309 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 12310 (Imm - 8).isPowerOf2())) 12311 return true; 12312 // Omit the following optimization if the sub target has the M extension 12313 // and the data size >= XLen. 12314 if (HasExtMOrZmmul && VT.getSizeInBits() >= Subtarget.getXLen()) 12315 return false; 12316 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 12317 // a pair of LUI/ADDI. 12318 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 12319 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 12320 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 12321 (1 - ImmS).isPowerOf2()) 12322 return true; 12323 } 12324 } 12325 } 12326 12327 return false; 12328 } 12329 12330 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 12331 SDValue ConstNode) const { 12332 // Let the DAGCombiner decide for vectors. 12333 EVT VT = AddNode.getValueType(); 12334 if (VT.isVector()) 12335 return true; 12336 12337 // Let the DAGCombiner decide for larger types. 12338 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 12339 return true; 12340 12341 // It is worse if c1 is simm12 while c1*c2 is not. 12342 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 12343 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 12344 const APInt &C1 = C1Node->getAPIntValue(); 12345 const APInt &C2 = C2Node->getAPIntValue(); 12346 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 12347 return false; 12348 12349 // Default to true and let the DAGCombiner decide. 12350 return true; 12351 } 12352 12353 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 12354 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 12355 bool *Fast) const { 12356 if (!VT.isVector()) { 12357 if (Fast) 12358 *Fast = false; 12359 return Subtarget.enableUnalignedScalarMem(); 12360 } 12361 12362 // All vector implementations must support element alignment 12363 EVT ElemVT = VT.getVectorElementType(); 12364 if (Alignment >= ElemVT.getStoreSize()) { 12365 if (Fast) 12366 *Fast = true; 12367 return true; 12368 } 12369 12370 return false; 12371 } 12372 12373 bool RISCVTargetLowering::splitValueIntoRegisterParts( 12374 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 12375 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 12376 bool IsABIRegCopy = CC.has_value(); 12377 EVT ValueVT = Val.getValueType(); 12378 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 12379 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 12380 // and cast to f32. 12381 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 12382 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 12383 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 12384 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 12385 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 12386 Parts[0] = Val; 12387 return true; 12388 } 12389 12390 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 12391 LLVMContext &Context = *DAG.getContext(); 12392 EVT ValueEltVT = ValueVT.getVectorElementType(); 12393 EVT PartEltVT = PartVT.getVectorElementType(); 12394 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 12395 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 12396 if (PartVTBitSize % ValueVTBitSize == 0) { 12397 assert(PartVTBitSize >= ValueVTBitSize); 12398 // If the element types are different, bitcast to the same element type of 12399 // PartVT first. 12400 // Give an example here, we want copy a <vscale x 1 x i8> value to 12401 // <vscale x 4 x i16>. 12402 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 12403 // subvector, then we can bitcast to <vscale x 4 x i16>. 12404 if (ValueEltVT != PartEltVT) { 12405 if (PartVTBitSize > ValueVTBitSize) { 12406 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 12407 assert(Count != 0 && "The number of element should not be zero."); 12408 EVT SameEltTypeVT = 12409 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 12410 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 12411 DAG.getUNDEF(SameEltTypeVT), Val, 12412 DAG.getVectorIdxConstant(0, DL)); 12413 } 12414 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 12415 } else { 12416 Val = 12417 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 12418 Val, DAG.getVectorIdxConstant(0, DL)); 12419 } 12420 Parts[0] = Val; 12421 return true; 12422 } 12423 } 12424 return false; 12425 } 12426 12427 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 12428 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 12429 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 12430 bool IsABIRegCopy = CC.has_value(); 12431 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 12432 SDValue Val = Parts[0]; 12433 12434 // Cast the f32 to i32, truncate to i16, and cast back to f16. 12435 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 12436 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 12437 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 12438 return Val; 12439 } 12440 12441 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 12442 LLVMContext &Context = *DAG.getContext(); 12443 SDValue Val = Parts[0]; 12444 EVT ValueEltVT = ValueVT.getVectorElementType(); 12445 EVT PartEltVT = PartVT.getVectorElementType(); 12446 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 12447 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 12448 if (PartVTBitSize % ValueVTBitSize == 0) { 12449 assert(PartVTBitSize >= ValueVTBitSize); 12450 EVT SameEltTypeVT = ValueVT; 12451 // If the element types are different, convert it to the same element type 12452 // of PartVT. 12453 // Give an example here, we want copy a <vscale x 1 x i8> value from 12454 // <vscale x 4 x i16>. 12455 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 12456 // then we can extract <vscale x 1 x i8>. 12457 if (ValueEltVT != PartEltVT) { 12458 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 12459 assert(Count != 0 && "The number of element should not be zero."); 12460 SameEltTypeVT = 12461 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 12462 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 12463 } 12464 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 12465 DAG.getVectorIdxConstant(0, DL)); 12466 return Val; 12467 } 12468 } 12469 return SDValue(); 12470 } 12471 12472 SDValue 12473 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 12474 SelectionDAG &DAG, 12475 SmallVectorImpl<SDNode *> &Created) const { 12476 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 12477 if (isIntDivCheap(N->getValueType(0), Attr)) 12478 return SDValue(N, 0); // Lower SDIV as SDIV 12479 12480 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 12481 "Unexpected divisor!"); 12482 12483 // Conditional move is needed, so do the transformation iff Zbt is enabled. 12484 if (!Subtarget.hasStdExtZbt()) 12485 return SDValue(); 12486 12487 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 12488 // Besides, more critical path instructions will be generated when dividing 12489 // by 2. So we keep using the original DAGs for these cases. 12490 unsigned Lg2 = Divisor.countTrailingZeros(); 12491 if (Lg2 == 1 || Lg2 >= 12) 12492 return SDValue(); 12493 12494 // fold (sdiv X, pow2) 12495 EVT VT = N->getValueType(0); 12496 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 12497 return SDValue(); 12498 12499 SDLoc DL(N); 12500 SDValue N0 = N->getOperand(0); 12501 SDValue Zero = DAG.getConstant(0, DL, VT); 12502 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 12503 12504 // Add (N0 < 0) ? Pow2 - 1 : 0; 12505 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 12506 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 12507 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 12508 12509 Created.push_back(Cmp.getNode()); 12510 Created.push_back(Add.getNode()); 12511 Created.push_back(Sel.getNode()); 12512 12513 // Divide by pow2. 12514 SDValue SRA = 12515 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 12516 12517 // If we're dividing by a positive value, we're done. Otherwise, we must 12518 // negate the result. 12519 if (Divisor.isNonNegative()) 12520 return SRA; 12521 12522 Created.push_back(SRA.getNode()); 12523 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 12524 } 12525 12526 #define GET_REGISTER_MATCHER 12527 #include "RISCVGenAsmMatcher.inc" 12528 12529 Register 12530 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 12531 const MachineFunction &MF) const { 12532 Register Reg = MatchRegisterAltName(RegName); 12533 if (Reg == RISCV::NoRegister) 12534 Reg = MatchRegisterName(RegName); 12535 if (Reg == RISCV::NoRegister) 12536 report_fatal_error( 12537 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 12538 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 12539 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 12540 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 12541 StringRef(RegName) + "\".")); 12542 return Reg; 12543 } 12544 12545 namespace llvm { 12546 namespace RISCVVIntrinsicsTable { 12547 12548 #define GET_RISCVVIntrinsicsTable_IMPL 12549 #include "RISCVGenSearchableTables.inc" 12550 12551 } // namespace RISCVVIntrinsicsTable 12552 12553 } // namespace llvm 12554