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::isOffsetFoldingLegal( 1317 const GlobalAddressSDNode *GA) const { 1318 // In order to maximise the opportunity for common subexpression elimination, 1319 // keep a separate ADD node for the global address offset instead of folding 1320 // it in the global address node. Later peephole optimisations may choose to 1321 // fold it back in when profitable. 1322 return false; 1323 } 1324 1325 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1326 bool ForCodeSize) const { 1327 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1328 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1329 return false; 1330 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1331 return false; 1332 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1333 return false; 1334 return Imm.isZero(); 1335 } 1336 1337 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1338 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1339 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1340 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1341 } 1342 1343 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1344 CallingConv::ID CC, 1345 EVT VT) const { 1346 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1347 // We might still end up using a GPR but that will be decided based on ABI. 1348 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1349 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1350 return MVT::f32; 1351 1352 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1353 } 1354 1355 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1356 CallingConv::ID CC, 1357 EVT VT) const { 1358 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1359 // We might still end up using a GPR but that will be decided based on ABI. 1360 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1361 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1362 return 1; 1363 1364 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1365 } 1366 1367 // Changes the condition code and swaps operands if necessary, so the SetCC 1368 // operation matches one of the comparisons supported directly by branches 1369 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1370 // with 1/-1. 1371 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1372 ISD::CondCode &CC, SelectionDAG &DAG) { 1373 // Convert X > -1 to X >= 0. 1374 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1375 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1376 CC = ISD::SETGE; 1377 return; 1378 } 1379 // Convert X < 1 to 0 >= X. 1380 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1381 RHS = LHS; 1382 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1383 CC = ISD::SETGE; 1384 return; 1385 } 1386 1387 switch (CC) { 1388 default: 1389 break; 1390 case ISD::SETGT: 1391 case ISD::SETLE: 1392 case ISD::SETUGT: 1393 case ISD::SETULE: 1394 CC = ISD::getSetCCSwappedOperands(CC); 1395 std::swap(LHS, RHS); 1396 break; 1397 } 1398 } 1399 1400 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1401 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1402 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1403 if (VT.getVectorElementType() == MVT::i1) 1404 KnownSize *= 8; 1405 1406 switch (KnownSize) { 1407 default: 1408 llvm_unreachable("Invalid LMUL."); 1409 case 8: 1410 return RISCVII::VLMUL::LMUL_F8; 1411 case 16: 1412 return RISCVII::VLMUL::LMUL_F4; 1413 case 32: 1414 return RISCVII::VLMUL::LMUL_F2; 1415 case 64: 1416 return RISCVII::VLMUL::LMUL_1; 1417 case 128: 1418 return RISCVII::VLMUL::LMUL_2; 1419 case 256: 1420 return RISCVII::VLMUL::LMUL_4; 1421 case 512: 1422 return RISCVII::VLMUL::LMUL_8; 1423 } 1424 } 1425 1426 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1427 switch (LMul) { 1428 default: 1429 llvm_unreachable("Invalid LMUL."); 1430 case RISCVII::VLMUL::LMUL_F8: 1431 case RISCVII::VLMUL::LMUL_F4: 1432 case RISCVII::VLMUL::LMUL_F2: 1433 case RISCVII::VLMUL::LMUL_1: 1434 return RISCV::VRRegClassID; 1435 case RISCVII::VLMUL::LMUL_2: 1436 return RISCV::VRM2RegClassID; 1437 case RISCVII::VLMUL::LMUL_4: 1438 return RISCV::VRM4RegClassID; 1439 case RISCVII::VLMUL::LMUL_8: 1440 return RISCV::VRM8RegClassID; 1441 } 1442 } 1443 1444 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1445 RISCVII::VLMUL LMUL = getLMUL(VT); 1446 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1447 LMUL == RISCVII::VLMUL::LMUL_F4 || 1448 LMUL == RISCVII::VLMUL::LMUL_F2 || 1449 LMUL == RISCVII::VLMUL::LMUL_1) { 1450 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1451 "Unexpected subreg numbering"); 1452 return RISCV::sub_vrm1_0 + Index; 1453 } 1454 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1455 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1456 "Unexpected subreg numbering"); 1457 return RISCV::sub_vrm2_0 + Index; 1458 } 1459 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1460 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1461 "Unexpected subreg numbering"); 1462 return RISCV::sub_vrm4_0 + Index; 1463 } 1464 llvm_unreachable("Invalid vector type."); 1465 } 1466 1467 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1468 if (VT.getVectorElementType() == MVT::i1) 1469 return RISCV::VRRegClassID; 1470 return getRegClassIDForLMUL(getLMUL(VT)); 1471 } 1472 1473 // Attempt to decompose a subvector insert/extract between VecVT and 1474 // SubVecVT via subregister indices. Returns the subregister index that 1475 // can perform the subvector insert/extract with the given element index, as 1476 // well as the index corresponding to any leftover subvectors that must be 1477 // further inserted/extracted within the register class for SubVecVT. 1478 std::pair<unsigned, unsigned> 1479 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1480 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1481 const RISCVRegisterInfo *TRI) { 1482 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1483 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1484 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1485 "Register classes not ordered"); 1486 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1487 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1488 // Try to compose a subregister index that takes us from the incoming 1489 // LMUL>1 register class down to the outgoing one. At each step we half 1490 // the LMUL: 1491 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1492 // Note that this is not guaranteed to find a subregister index, such as 1493 // when we are extracting from one VR type to another. 1494 unsigned SubRegIdx = RISCV::NoSubRegister; 1495 for (const unsigned RCID : 1496 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1497 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1498 VecVT = VecVT.getHalfNumVectorElementsVT(); 1499 bool IsHi = 1500 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1501 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1502 getSubregIndexByMVT(VecVT, IsHi)); 1503 if (IsHi) 1504 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1505 } 1506 return {SubRegIdx, InsertExtractIdx}; 1507 } 1508 1509 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1510 // stores for those types. 1511 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1512 return !Subtarget.useRVVForFixedLengthVectors() || 1513 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1514 } 1515 1516 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1517 if (ScalarTy->isPointerTy()) 1518 return true; 1519 1520 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1521 ScalarTy->isIntegerTy(32)) 1522 return true; 1523 1524 if (ScalarTy->isIntegerTy(64)) 1525 return Subtarget.hasVInstructionsI64(); 1526 1527 if (ScalarTy->isHalfTy()) 1528 return Subtarget.hasVInstructionsF16(); 1529 if (ScalarTy->isFloatTy()) 1530 return Subtarget.hasVInstructionsF32(); 1531 if (ScalarTy->isDoubleTy()) 1532 return Subtarget.hasVInstructionsF64(); 1533 1534 return false; 1535 } 1536 1537 static SDValue getVLOperand(SDValue Op) { 1538 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1539 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1540 "Unexpected opcode"); 1541 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1542 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1543 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1544 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1545 if (!II) 1546 return SDValue(); 1547 return Op.getOperand(II->VLOperand + 1 + HasChain); 1548 } 1549 1550 static bool useRVVForFixedLengthVectorVT(MVT VT, 1551 const RISCVSubtarget &Subtarget) { 1552 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1553 if (!Subtarget.useRVVForFixedLengthVectors()) 1554 return false; 1555 1556 // We only support a set of vector types with a consistent maximum fixed size 1557 // across all supported vector element types to avoid legalization issues. 1558 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1559 // fixed-length vector type we support is 1024 bytes. 1560 if (VT.getFixedSizeInBits() > 1024 * 8) 1561 return false; 1562 1563 unsigned MinVLen = Subtarget.getRealMinVLen(); 1564 1565 MVT EltVT = VT.getVectorElementType(); 1566 1567 // Don't use RVV for vectors we cannot scalarize if required. 1568 switch (EltVT.SimpleTy) { 1569 // i1 is supported but has different rules. 1570 default: 1571 return false; 1572 case MVT::i1: 1573 // Masks can only use a single register. 1574 if (VT.getVectorNumElements() > MinVLen) 1575 return false; 1576 MinVLen /= 8; 1577 break; 1578 case MVT::i8: 1579 case MVT::i16: 1580 case MVT::i32: 1581 break; 1582 case MVT::i64: 1583 if (!Subtarget.hasVInstructionsI64()) 1584 return false; 1585 break; 1586 case MVT::f16: 1587 if (!Subtarget.hasVInstructionsF16()) 1588 return false; 1589 break; 1590 case MVT::f32: 1591 if (!Subtarget.hasVInstructionsF32()) 1592 return false; 1593 break; 1594 case MVT::f64: 1595 if (!Subtarget.hasVInstructionsF64()) 1596 return false; 1597 break; 1598 } 1599 1600 // Reject elements larger than ELEN. 1601 if (EltVT.getSizeInBits() > Subtarget.getELEN()) 1602 return false; 1603 1604 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1605 // Don't use RVV for types that don't fit. 1606 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1607 return false; 1608 1609 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1610 // the base fixed length RVV support in place. 1611 if (!VT.isPow2VectorType()) 1612 return false; 1613 1614 return true; 1615 } 1616 1617 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1618 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1619 } 1620 1621 // Return the largest legal scalable vector type that matches VT's element type. 1622 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1623 const RISCVSubtarget &Subtarget) { 1624 // This may be called before legal types are setup. 1625 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1626 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1627 "Expected legal fixed length vector!"); 1628 1629 unsigned MinVLen = Subtarget.getRealMinVLen(); 1630 unsigned MaxELen = Subtarget.getELEN(); 1631 1632 MVT EltVT = VT.getVectorElementType(); 1633 switch (EltVT.SimpleTy) { 1634 default: 1635 llvm_unreachable("unexpected element type for RVV container"); 1636 case MVT::i1: 1637 case MVT::i8: 1638 case MVT::i16: 1639 case MVT::i32: 1640 case MVT::i64: 1641 case MVT::f16: 1642 case MVT::f32: 1643 case MVT::f64: { 1644 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1645 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1646 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1647 unsigned NumElts = 1648 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1649 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1650 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1651 return MVT::getScalableVectorVT(EltVT, NumElts); 1652 } 1653 } 1654 } 1655 1656 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1657 const RISCVSubtarget &Subtarget) { 1658 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1659 Subtarget); 1660 } 1661 1662 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1663 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1664 } 1665 1666 // Grow V to consume an entire RVV register. 1667 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1668 const RISCVSubtarget &Subtarget) { 1669 assert(VT.isScalableVector() && 1670 "Expected to convert into a scalable vector!"); 1671 assert(V.getValueType().isFixedLengthVector() && 1672 "Expected a fixed length vector operand!"); 1673 SDLoc DL(V); 1674 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1675 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1676 } 1677 1678 // Shrink V so it's just big enough to maintain a VT's worth of data. 1679 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1680 const RISCVSubtarget &Subtarget) { 1681 assert(VT.isFixedLengthVector() && 1682 "Expected to convert into a fixed length vector!"); 1683 assert(V.getValueType().isScalableVector() && 1684 "Expected a scalable vector operand!"); 1685 SDLoc DL(V); 1686 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1687 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1688 } 1689 1690 /// Return the type of the mask type suitable for masking the provided 1691 /// vector type. This is simply an i1 element type vector of the same 1692 /// (possibly scalable) length. 1693 static MVT getMaskTypeFor(MVT VecVT) { 1694 assert(VecVT.isVector()); 1695 ElementCount EC = VecVT.getVectorElementCount(); 1696 return MVT::getVectorVT(MVT::i1, EC); 1697 } 1698 1699 /// Creates an all ones mask suitable for masking a vector of type VecTy with 1700 /// vector length VL. . 1701 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL, 1702 SelectionDAG &DAG) { 1703 MVT MaskVT = getMaskTypeFor(VecVT); 1704 return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1705 } 1706 1707 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1708 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1709 // the vector type that it is contained in. 1710 static std::pair<SDValue, SDValue> 1711 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1712 const RISCVSubtarget &Subtarget) { 1713 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1714 MVT XLenVT = Subtarget.getXLenVT(); 1715 SDValue VL = VecVT.isFixedLengthVector() 1716 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1717 : DAG.getRegister(RISCV::X0, XLenVT); 1718 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 1719 return {Mask, VL}; 1720 } 1721 1722 // As above but assuming the given type is a scalable vector type. 1723 static std::pair<SDValue, SDValue> 1724 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1725 const RISCVSubtarget &Subtarget) { 1726 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1727 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1728 } 1729 1730 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1731 // of either is (currently) supported. This can get us into an infinite loop 1732 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1733 // as a ..., etc. 1734 // Until either (or both) of these can reliably lower any node, reporting that 1735 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1736 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1737 // which is not desirable. 1738 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1739 EVT VT, unsigned DefinedValues) const { 1740 return false; 1741 } 1742 1743 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1744 const RISCVSubtarget &Subtarget) { 1745 // RISCV FP-to-int conversions saturate to the destination register size, but 1746 // don't produce 0 for nan. We can use a conversion instruction and fix the 1747 // nan case with a compare and a select. 1748 SDValue Src = Op.getOperand(0); 1749 1750 EVT DstVT = Op.getValueType(); 1751 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1752 1753 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1754 unsigned Opc; 1755 if (SatVT == DstVT) 1756 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1757 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1758 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1759 else 1760 return SDValue(); 1761 // FIXME: Support other SatVTs by clamping before or after the conversion. 1762 1763 SDLoc DL(Op); 1764 SDValue FpToInt = DAG.getNode( 1765 Opc, DL, DstVT, Src, 1766 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1767 1768 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1769 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1770 } 1771 1772 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1773 // and back. Taking care to avoid converting values that are nan or already 1774 // correct. 1775 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1776 // have FRM dependencies modeled yet. 1777 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1778 MVT VT = Op.getSimpleValueType(); 1779 assert(VT.isVector() && "Unexpected type"); 1780 1781 SDLoc DL(Op); 1782 1783 // Freeze the source since we are increasing the number of uses. 1784 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1785 1786 // Truncate to integer and convert back to FP. 1787 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1788 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1789 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1790 1791 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1792 1793 if (Op.getOpcode() == ISD::FCEIL) { 1794 // If the truncated value is the greater than or equal to the original 1795 // value, we've computed the ceil. Otherwise, we went the wrong way and 1796 // need to increase by 1. 1797 // FIXME: This should use a masked operation. Handle here or in isel? 1798 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1799 DAG.getConstantFP(1.0, DL, VT)); 1800 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1801 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1802 } else if (Op.getOpcode() == ISD::FFLOOR) { 1803 // If the truncated value is the less than or equal to the original value, 1804 // we've computed the floor. Otherwise, we went the wrong way and need to 1805 // decrease by 1. 1806 // FIXME: This should use a masked operation. Handle here or in isel? 1807 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1808 DAG.getConstantFP(1.0, DL, VT)); 1809 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1810 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1811 } 1812 1813 // Restore the original sign so that -0.0 is preserved. 1814 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1815 1816 // Determine the largest integer that can be represented exactly. This and 1817 // values larger than it don't have any fractional bits so don't need to 1818 // be converted. 1819 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1820 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1821 APFloat MaxVal = APFloat(FltSem); 1822 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1823 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1824 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1825 1826 // If abs(Src) was larger than MaxVal or nan, keep it. 1827 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1828 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1829 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1830 } 1831 1832 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1833 // This mode isn't supported in vector hardware on RISCV. But as long as we 1834 // aren't compiling with trapping math, we can emulate this with 1835 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1836 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1837 // dependencies modeled yet. 1838 // FIXME: Use masked operations to avoid final merge. 1839 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1840 MVT VT = Op.getSimpleValueType(); 1841 assert(VT.isVector() && "Unexpected type"); 1842 1843 SDLoc DL(Op); 1844 1845 // Freeze the source since we are increasing the number of uses. 1846 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1847 1848 // We do the conversion on the absolute value and fix the sign at the end. 1849 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1850 1851 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1852 bool Ignored; 1853 APFloat Point5Pred = APFloat(0.5f); 1854 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1855 Point5Pred.next(/*nextDown*/ true); 1856 1857 // Add the adjustment. 1858 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1859 DAG.getConstantFP(Point5Pred, DL, VT)); 1860 1861 // Truncate to integer and convert back to fp. 1862 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1863 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1864 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1865 1866 // Restore the original sign. 1867 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1868 1869 // Determine the largest integer that can be represented exactly. This and 1870 // values larger than it don't have any fractional bits so don't need to 1871 // be converted. 1872 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1873 APFloat MaxVal = APFloat(FltSem); 1874 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1875 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1876 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1877 1878 // If abs(Src) was larger than MaxVal or nan, keep it. 1879 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1880 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1881 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1882 } 1883 1884 struct VIDSequence { 1885 int64_t StepNumerator; 1886 unsigned StepDenominator; 1887 int64_t Addend; 1888 }; 1889 1890 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1891 // to the (non-zero) step S and start value X. This can be then lowered as the 1892 // RVV sequence (VID * S) + X, for example. 1893 // The step S is represented as an integer numerator divided by a positive 1894 // denominator. Note that the implementation currently only identifies 1895 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1896 // cannot detect 2/3, for example. 1897 // Note that this method will also match potentially unappealing index 1898 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1899 // determine whether this is worth generating code for. 1900 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1901 unsigned NumElts = Op.getNumOperands(); 1902 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1903 if (!Op.getValueType().isInteger()) 1904 return None; 1905 1906 Optional<unsigned> SeqStepDenom; 1907 Optional<int64_t> SeqStepNum, SeqAddend; 1908 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1909 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1910 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1911 // Assume undef elements match the sequence; we just have to be careful 1912 // when interpolating across them. 1913 if (Op.getOperand(Idx).isUndef()) 1914 continue; 1915 // The BUILD_VECTOR must be all constants. 1916 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1917 return None; 1918 1919 uint64_t Val = Op.getConstantOperandVal(Idx) & 1920 maskTrailingOnes<uint64_t>(EltSizeInBits); 1921 1922 if (PrevElt) { 1923 // Calculate the step since the last non-undef element, and ensure 1924 // it's consistent across the entire sequence. 1925 unsigned IdxDiff = Idx - PrevElt->second; 1926 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1927 1928 // A zero-value value difference means that we're somewhere in the middle 1929 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1930 // step change before evaluating the sequence. 1931 if (ValDiff == 0) 1932 continue; 1933 1934 int64_t Remainder = ValDiff % IdxDiff; 1935 // Normalize the step if it's greater than 1. 1936 if (Remainder != ValDiff) { 1937 // The difference must cleanly divide the element span. 1938 if (Remainder != 0) 1939 return None; 1940 ValDiff /= IdxDiff; 1941 IdxDiff = 1; 1942 } 1943 1944 if (!SeqStepNum) 1945 SeqStepNum = ValDiff; 1946 else if (ValDiff != SeqStepNum) 1947 return None; 1948 1949 if (!SeqStepDenom) 1950 SeqStepDenom = IdxDiff; 1951 else if (IdxDiff != *SeqStepDenom) 1952 return None; 1953 } 1954 1955 // Record this non-undef element for later. 1956 if (!PrevElt || PrevElt->first != Val) 1957 PrevElt = std::make_pair(Val, Idx); 1958 } 1959 1960 // We need to have logged a step for this to count as a legal index sequence. 1961 if (!SeqStepNum || !SeqStepDenom) 1962 return None; 1963 1964 // Loop back through the sequence and validate elements we might have skipped 1965 // while waiting for a valid step. While doing this, log any sequence addend. 1966 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1967 if (Op.getOperand(Idx).isUndef()) 1968 continue; 1969 uint64_t Val = Op.getConstantOperandVal(Idx) & 1970 maskTrailingOnes<uint64_t>(EltSizeInBits); 1971 uint64_t ExpectedVal = 1972 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1973 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1974 if (!SeqAddend) 1975 SeqAddend = Addend; 1976 else if (Addend != SeqAddend) 1977 return None; 1978 } 1979 1980 assert(SeqAddend && "Must have an addend if we have a step"); 1981 1982 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1983 } 1984 1985 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1986 // and lower it as a VRGATHER_VX_VL from the source vector. 1987 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 1988 SelectionDAG &DAG, 1989 const RISCVSubtarget &Subtarget) { 1990 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1991 return SDValue(); 1992 SDValue Vec = SplatVal.getOperand(0); 1993 // Only perform this optimization on vectors of the same size for simplicity. 1994 // Don't perform this optimization for i1 vectors. 1995 // FIXME: Support i1 vectors, maybe by promoting to i8? 1996 if (Vec.getValueType() != VT || VT.getVectorElementType() == MVT::i1) 1997 return SDValue(); 1998 SDValue Idx = SplatVal.getOperand(1); 1999 // The index must be a legal type. 2000 if (Idx.getValueType() != Subtarget.getXLenVT()) 2001 return SDValue(); 2002 2003 MVT ContainerVT = VT; 2004 if (VT.isFixedLengthVector()) { 2005 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2006 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 2007 } 2008 2009 SDValue Mask, VL; 2010 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2011 2012 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 2013 Idx, Mask, DAG.getUNDEF(ContainerVT), VL); 2014 2015 if (!VT.isFixedLengthVector()) 2016 return Gather; 2017 2018 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2019 } 2020 2021 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 2022 const RISCVSubtarget &Subtarget) { 2023 MVT VT = Op.getSimpleValueType(); 2024 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 2025 2026 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2027 2028 SDLoc DL(Op); 2029 SDValue Mask, VL; 2030 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2031 2032 MVT XLenVT = Subtarget.getXLenVT(); 2033 unsigned NumElts = Op.getNumOperands(); 2034 2035 if (VT.getVectorElementType() == MVT::i1) { 2036 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 2037 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 2038 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 2039 } 2040 2041 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 2042 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 2043 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 2044 } 2045 2046 // Lower constant mask BUILD_VECTORs via an integer vector type, in 2047 // scalar integer chunks whose bit-width depends on the number of mask 2048 // bits and XLEN. 2049 // First, determine the most appropriate scalar integer type to use. This 2050 // is at most XLenVT, but may be shrunk to a smaller vector element type 2051 // according to the size of the final vector - use i8 chunks rather than 2052 // XLenVT if we're producing a v8i1. This results in more consistent 2053 // codegen across RV32 and RV64. 2054 unsigned NumViaIntegerBits = 2055 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 2056 NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN()); 2057 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 2058 // If we have to use more than one INSERT_VECTOR_ELT then this 2059 // optimization is likely to increase code size; avoid peforming it in 2060 // such a case. We can use a load from a constant pool in this case. 2061 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 2062 return SDValue(); 2063 // Now we can create our integer vector type. Note that it may be larger 2064 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2065 MVT IntegerViaVecVT = 2066 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2067 divideCeil(NumElts, NumViaIntegerBits)); 2068 2069 uint64_t Bits = 0; 2070 unsigned BitPos = 0, IntegerEltIdx = 0; 2071 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2072 2073 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2074 // Once we accumulate enough bits to fill our scalar type, insert into 2075 // our vector and clear our accumulated data. 2076 if (I != 0 && I % NumViaIntegerBits == 0) { 2077 if (NumViaIntegerBits <= 32) 2078 Bits = SignExtend64<32>(Bits); 2079 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2080 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2081 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2082 Bits = 0; 2083 BitPos = 0; 2084 IntegerEltIdx++; 2085 } 2086 SDValue V = Op.getOperand(I); 2087 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2088 Bits |= ((uint64_t)BitValue << BitPos); 2089 } 2090 2091 // Insert the (remaining) scalar value into position in our integer 2092 // vector type. 2093 if (NumViaIntegerBits <= 32) 2094 Bits = SignExtend64<32>(Bits); 2095 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2096 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2097 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2098 2099 if (NumElts < NumViaIntegerBits) { 2100 // If we're producing a smaller vector than our minimum legal integer 2101 // type, bitcast to the equivalent (known-legal) mask type, and extract 2102 // our final mask. 2103 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2104 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2105 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2106 DAG.getConstant(0, DL, XLenVT)); 2107 } else { 2108 // Else we must have produced an integer type with the same size as the 2109 // mask type; bitcast for the final result. 2110 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2111 Vec = DAG.getBitcast(VT, Vec); 2112 } 2113 2114 return Vec; 2115 } 2116 2117 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2118 // vector type, we have a legal equivalently-sized i8 type, so we can use 2119 // that. 2120 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2121 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2122 2123 SDValue WideVec; 2124 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2125 // For a splat, perform a scalar truncate before creating the wider 2126 // vector. 2127 assert(Splat.getValueType() == XLenVT && 2128 "Unexpected type for i1 splat value"); 2129 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2130 DAG.getConstant(1, DL, XLenVT)); 2131 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2132 } else { 2133 SmallVector<SDValue, 8> Ops(Op->op_values()); 2134 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2135 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2136 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2137 } 2138 2139 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2140 } 2141 2142 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2143 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2144 return Gather; 2145 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2146 : RISCVISD::VMV_V_X_VL; 2147 Splat = 2148 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2149 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2150 } 2151 2152 // Try and match index sequences, which we can lower to the vid instruction 2153 // with optional modifications. An all-undef vector is matched by 2154 // getSplatValue, above. 2155 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2156 int64_t StepNumerator = SimpleVID->StepNumerator; 2157 unsigned StepDenominator = SimpleVID->StepDenominator; 2158 int64_t Addend = SimpleVID->Addend; 2159 2160 assert(StepNumerator != 0 && "Invalid step"); 2161 bool Negate = false; 2162 int64_t SplatStepVal = StepNumerator; 2163 unsigned StepOpcode = ISD::MUL; 2164 if (StepNumerator != 1) { 2165 if (isPowerOf2_64(std::abs(StepNumerator))) { 2166 Negate = StepNumerator < 0; 2167 StepOpcode = ISD::SHL; 2168 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2169 } 2170 } 2171 2172 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2173 // threshold since it's the immediate value many RVV instructions accept. 2174 // There is no vmul.vi instruction so ensure multiply constant can fit in 2175 // a single addi instruction. 2176 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2177 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2178 isPowerOf2_32(StepDenominator) && 2179 (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) { 2180 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2181 // Convert right out of the scalable type so we can use standard ISD 2182 // nodes for the rest of the computation. If we used scalable types with 2183 // these, we'd lose the fixed-length vector info and generate worse 2184 // vsetvli code. 2185 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2186 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2187 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2188 SDValue SplatStep = DAG.getSplatBuildVector( 2189 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2190 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2191 } 2192 if (StepDenominator != 1) { 2193 SDValue SplatStep = DAG.getSplatBuildVector( 2194 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2195 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2196 } 2197 if (Addend != 0 || Negate) { 2198 SDValue SplatAddend = DAG.getSplatBuildVector( 2199 VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2200 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2201 } 2202 return VID; 2203 } 2204 } 2205 2206 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2207 // when re-interpreted as a vector with a larger element type. For example, 2208 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2209 // could be instead splat as 2210 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2211 // TODO: This optimization could also work on non-constant splats, but it 2212 // would require bit-manipulation instructions to construct the splat value. 2213 SmallVector<SDValue> Sequence; 2214 unsigned EltBitSize = VT.getScalarSizeInBits(); 2215 const auto *BV = cast<BuildVectorSDNode>(Op); 2216 if (VT.isInteger() && EltBitSize < 64 && 2217 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2218 BV->getRepeatedSequence(Sequence) && 2219 (Sequence.size() * EltBitSize) <= 64) { 2220 unsigned SeqLen = Sequence.size(); 2221 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2222 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2223 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2224 ViaIntVT == MVT::i64) && 2225 "Unexpected sequence type"); 2226 2227 unsigned EltIdx = 0; 2228 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2229 uint64_t SplatValue = 0; 2230 // Construct the amalgamated value which can be splatted as this larger 2231 // vector type. 2232 for (const auto &SeqV : Sequence) { 2233 if (!SeqV.isUndef()) 2234 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2235 << (EltIdx * EltBitSize)); 2236 EltIdx++; 2237 } 2238 2239 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2240 // achieve better constant materializion. 2241 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2242 SplatValue = SignExtend64<32>(SplatValue); 2243 2244 // Since we can't introduce illegal i64 types at this stage, we can only 2245 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2246 // way we can use RVV instructions to splat. 2247 assert((ViaIntVT.bitsLE(XLenVT) || 2248 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2249 "Unexpected bitcast sequence"); 2250 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2251 SDValue ViaVL = 2252 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2253 MVT ViaContainerVT = 2254 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2255 SDValue Splat = 2256 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2257 DAG.getUNDEF(ViaContainerVT), 2258 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2259 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2260 return DAG.getBitcast(VT, Splat); 2261 } 2262 } 2263 2264 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2265 // which constitute a large proportion of the elements. In such cases we can 2266 // splat a vector with the dominant element and make up the shortfall with 2267 // INSERT_VECTOR_ELTs. 2268 // Note that this includes vectors of 2 elements by association. The 2269 // upper-most element is the "dominant" one, allowing us to use a splat to 2270 // "insert" the upper element, and an insert of the lower element at position 2271 // 0, which improves codegen. 2272 SDValue DominantValue; 2273 unsigned MostCommonCount = 0; 2274 DenseMap<SDValue, unsigned> ValueCounts; 2275 unsigned NumUndefElts = 2276 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2277 2278 // Track the number of scalar loads we know we'd be inserting, estimated as 2279 // any non-zero floating-point constant. Other kinds of element are either 2280 // already in registers or are materialized on demand. The threshold at which 2281 // a vector load is more desirable than several scalar materializion and 2282 // vector-insertion instructions is not known. 2283 unsigned NumScalarLoads = 0; 2284 2285 for (SDValue V : Op->op_values()) { 2286 if (V.isUndef()) 2287 continue; 2288 2289 ValueCounts.insert(std::make_pair(V, 0)); 2290 unsigned &Count = ValueCounts[V]; 2291 2292 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2293 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2294 2295 // Is this value dominant? In case of a tie, prefer the highest element as 2296 // it's cheaper to insert near the beginning of a vector than it is at the 2297 // end. 2298 if (++Count >= MostCommonCount) { 2299 DominantValue = V; 2300 MostCommonCount = Count; 2301 } 2302 } 2303 2304 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2305 unsigned NumDefElts = NumElts - NumUndefElts; 2306 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2307 2308 // Don't perform this optimization when optimizing for size, since 2309 // materializing elements and inserting them tends to cause code bloat. 2310 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2311 ((MostCommonCount > DominantValueCountThreshold) || 2312 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2313 // Start by splatting the most common element. 2314 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2315 2316 DenseSet<SDValue> Processed{DominantValue}; 2317 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2318 for (const auto &OpIdx : enumerate(Op->ops())) { 2319 const SDValue &V = OpIdx.value(); 2320 if (V.isUndef() || !Processed.insert(V).second) 2321 continue; 2322 if (ValueCounts[V] == 1) { 2323 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2324 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2325 } else { 2326 // Blend in all instances of this value using a VSELECT, using a 2327 // mask where each bit signals whether that element is the one 2328 // we're after. 2329 SmallVector<SDValue> Ops; 2330 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2331 return DAG.getConstant(V == V1, DL, XLenVT); 2332 }); 2333 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2334 DAG.getBuildVector(SelMaskTy, DL, Ops), 2335 DAG.getSplatBuildVector(VT, DL, V), Vec); 2336 } 2337 } 2338 2339 return Vec; 2340 } 2341 2342 return SDValue(); 2343 } 2344 2345 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2346 SDValue Lo, SDValue Hi, SDValue VL, 2347 SelectionDAG &DAG) { 2348 if (!Passthru) 2349 Passthru = DAG.getUNDEF(VT); 2350 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2351 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2352 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2353 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2354 // node in order to try and match RVV vector/scalar instructions. 2355 if ((LoC >> 31) == HiC) 2356 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2357 2358 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2359 // vmv.v.x whose EEW = 32 to lower it. 2360 auto *Const = dyn_cast<ConstantSDNode>(VL); 2361 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2362 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2363 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2364 // access the subtarget here now. 2365 auto InterVec = DAG.getNode( 2366 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2367 DAG.getRegister(RISCV::X0, MVT::i32)); 2368 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2369 } 2370 } 2371 2372 // Fall back to a stack store and stride x0 vector load. 2373 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2374 Hi, VL); 2375 } 2376 2377 // Called by type legalization to handle splat of i64 on RV32. 2378 // FIXME: We can optimize this when the type has sign or zero bits in one 2379 // of the halves. 2380 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2381 SDValue Scalar, SDValue VL, 2382 SelectionDAG &DAG) { 2383 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2384 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2385 DAG.getConstant(0, DL, MVT::i32)); 2386 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2387 DAG.getConstant(1, DL, MVT::i32)); 2388 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2389 } 2390 2391 // This function lowers a splat of a scalar operand Splat with the vector 2392 // length VL. It ensures the final sequence is type legal, which is useful when 2393 // lowering a splat after type legalization. 2394 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2395 MVT VT, SDLoc DL, SelectionDAG &DAG, 2396 const RISCVSubtarget &Subtarget) { 2397 bool HasPassthru = Passthru && !Passthru.isUndef(); 2398 if (!HasPassthru && !Passthru) 2399 Passthru = DAG.getUNDEF(VT); 2400 if (VT.isFloatingPoint()) { 2401 // If VL is 1, we could use vfmv.s.f. 2402 if (isOneConstant(VL)) 2403 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2404 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2405 } 2406 2407 MVT XLenVT = Subtarget.getXLenVT(); 2408 2409 // Simplest case is that the operand needs to be promoted to XLenVT. 2410 if (Scalar.getValueType().bitsLE(XLenVT)) { 2411 // If the operand is a constant, sign extend to increase our chances 2412 // of being able to use a .vi instruction. ANY_EXTEND would become a 2413 // a zero extend and the simm5 check in isel would fail. 2414 // FIXME: Should we ignore the upper bits in isel instead? 2415 unsigned ExtOpc = 2416 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2417 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2418 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2419 // If VL is 1 and the scalar value won't benefit from immediate, we could 2420 // use vmv.s.x. 2421 if (isOneConstant(VL) && 2422 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2423 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2424 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2425 } 2426 2427 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2428 "Unexpected scalar for splat lowering!"); 2429 2430 if (isOneConstant(VL) && isNullConstant(Scalar)) 2431 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2432 DAG.getConstant(0, DL, XLenVT), VL); 2433 2434 // Otherwise use the more complicated splatting algorithm. 2435 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2436 } 2437 2438 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2439 const RISCVSubtarget &Subtarget) { 2440 // We need to be able to widen elements to the next larger integer type. 2441 if (VT.getScalarSizeInBits() >= Subtarget.getELEN()) 2442 return false; 2443 2444 int Size = Mask.size(); 2445 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2446 2447 int Srcs[] = {-1, -1}; 2448 for (int i = 0; i != Size; ++i) { 2449 // Ignore undef elements. 2450 if (Mask[i] < 0) 2451 continue; 2452 2453 // Is this an even or odd element. 2454 int Pol = i % 2; 2455 2456 // Ensure we consistently use the same source for this element polarity. 2457 int Src = Mask[i] / Size; 2458 if (Srcs[Pol] < 0) 2459 Srcs[Pol] = Src; 2460 if (Srcs[Pol] != Src) 2461 return false; 2462 2463 // Make sure the element within the source is appropriate for this element 2464 // in the destination. 2465 int Elt = Mask[i] % Size; 2466 if (Elt != i / 2) 2467 return false; 2468 } 2469 2470 // We need to find a source for each polarity and they can't be the same. 2471 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2472 return false; 2473 2474 // Swap the sources if the second source was in the even polarity. 2475 SwapSources = Srcs[0] > Srcs[1]; 2476 2477 return true; 2478 } 2479 2480 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2481 /// and then extract the original number of elements from the rotated result. 2482 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2483 /// returned rotation amount is for a rotate right, where elements move from 2484 /// higher elements to lower elements. \p LoSrc indicates the first source 2485 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2486 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2487 /// 0 or 1 if a rotation is found. 2488 /// 2489 /// NOTE: We talk about rotate to the right which matches how bit shift and 2490 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2491 /// and the table below write vectors with the lowest elements on the left. 2492 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2493 int Size = Mask.size(); 2494 2495 // We need to detect various ways of spelling a rotation: 2496 // [11, 12, 13, 14, 15, 0, 1, 2] 2497 // [-1, 12, 13, 14, -1, -1, 1, -1] 2498 // [-1, -1, -1, -1, -1, -1, 1, 2] 2499 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2500 // [-1, 4, 5, 6, -1, -1, 9, -1] 2501 // [-1, 4, 5, 6, -1, -1, -1, -1] 2502 int Rotation = 0; 2503 LoSrc = -1; 2504 HiSrc = -1; 2505 for (int i = 0; i != Size; ++i) { 2506 int M = Mask[i]; 2507 if (M < 0) 2508 continue; 2509 2510 // Determine where a rotate vector would have started. 2511 int StartIdx = i - (M % Size); 2512 // The identity rotation isn't interesting, stop. 2513 if (StartIdx == 0) 2514 return -1; 2515 2516 // If we found the tail of a vector the rotation must be the missing 2517 // front. If we found the head of a vector, it must be how much of the 2518 // head. 2519 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2520 2521 if (Rotation == 0) 2522 Rotation = CandidateRotation; 2523 else if (Rotation != CandidateRotation) 2524 // The rotations don't match, so we can't match this mask. 2525 return -1; 2526 2527 // Compute which value this mask is pointing at. 2528 int MaskSrc = M < Size ? 0 : 1; 2529 2530 // Compute which of the two target values this index should be assigned to. 2531 // This reflects whether the high elements are remaining or the low elemnts 2532 // are remaining. 2533 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2534 2535 // Either set up this value if we've not encountered it before, or check 2536 // that it remains consistent. 2537 if (TargetSrc < 0) 2538 TargetSrc = MaskSrc; 2539 else if (TargetSrc != MaskSrc) 2540 // This may be a rotation, but it pulls from the inputs in some 2541 // unsupported interleaving. 2542 return -1; 2543 } 2544 2545 // Check that we successfully analyzed the mask, and normalize the results. 2546 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2547 assert((LoSrc >= 0 || HiSrc >= 0) && 2548 "Failed to find a rotated input vector!"); 2549 2550 return Rotation; 2551 } 2552 2553 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2554 const RISCVSubtarget &Subtarget) { 2555 SDValue V1 = Op.getOperand(0); 2556 SDValue V2 = Op.getOperand(1); 2557 SDLoc DL(Op); 2558 MVT XLenVT = Subtarget.getXLenVT(); 2559 MVT VT = Op.getSimpleValueType(); 2560 unsigned NumElts = VT.getVectorNumElements(); 2561 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2562 2563 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2564 2565 SDValue TrueMask, VL; 2566 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2567 2568 if (SVN->isSplat()) { 2569 const int Lane = SVN->getSplatIndex(); 2570 if (Lane >= 0) { 2571 MVT SVT = VT.getVectorElementType(); 2572 2573 // Turn splatted vector load into a strided load with an X0 stride. 2574 SDValue V = V1; 2575 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2576 // with undef. 2577 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2578 int Offset = Lane; 2579 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2580 int OpElements = 2581 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2582 V = V.getOperand(Offset / OpElements); 2583 Offset %= OpElements; 2584 } 2585 2586 // We need to ensure the load isn't atomic or volatile. 2587 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2588 auto *Ld = cast<LoadSDNode>(V); 2589 Offset *= SVT.getStoreSize(); 2590 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2591 TypeSize::Fixed(Offset), DL); 2592 2593 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2594 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2595 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2596 SDValue IntID = 2597 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2598 SDValue Ops[] = {Ld->getChain(), 2599 IntID, 2600 DAG.getUNDEF(ContainerVT), 2601 NewAddr, 2602 DAG.getRegister(RISCV::X0, XLenVT), 2603 VL}; 2604 SDValue NewLoad = DAG.getMemIntrinsicNode( 2605 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2606 DAG.getMachineFunction().getMachineMemOperand( 2607 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2608 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2609 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2610 } 2611 2612 // Otherwise use a scalar load and splat. This will give the best 2613 // opportunity to fold a splat into the operation. ISel can turn it into 2614 // the x0 strided load if we aren't able to fold away the select. 2615 if (SVT.isFloatingPoint()) 2616 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2617 Ld->getPointerInfo().getWithOffset(Offset), 2618 Ld->getOriginalAlign(), 2619 Ld->getMemOperand()->getFlags()); 2620 else 2621 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2622 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2623 Ld->getOriginalAlign(), 2624 Ld->getMemOperand()->getFlags()); 2625 DAG.makeEquivalentMemoryOrdering(Ld, V); 2626 2627 unsigned Opc = 2628 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2629 SDValue Splat = 2630 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2631 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2632 } 2633 2634 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2635 assert(Lane < (int)NumElts && "Unexpected lane!"); 2636 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, 2637 V1, DAG.getConstant(Lane, DL, XLenVT), 2638 TrueMask, DAG.getUNDEF(ContainerVT), VL); 2639 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2640 } 2641 } 2642 2643 ArrayRef<int> Mask = SVN->getMask(); 2644 2645 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2646 // be undef which can be handled with a single SLIDEDOWN/UP. 2647 int LoSrc, HiSrc; 2648 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2649 if (Rotation > 0) { 2650 SDValue LoV, HiV; 2651 if (LoSrc >= 0) { 2652 LoV = LoSrc == 0 ? V1 : V2; 2653 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2654 } 2655 if (HiSrc >= 0) { 2656 HiV = HiSrc == 0 ? V1 : V2; 2657 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2658 } 2659 2660 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2661 // to slide LoV up by (NumElts - Rotation). 2662 unsigned InvRotate = NumElts - Rotation; 2663 2664 SDValue Res = DAG.getUNDEF(ContainerVT); 2665 if (HiV) { 2666 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2667 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2668 // causes multiple vsetvlis in some test cases such as lowering 2669 // reduce.mul 2670 SDValue DownVL = VL; 2671 if (LoV) 2672 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2673 Res = 2674 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2675 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2676 } 2677 if (LoV) 2678 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2679 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2680 2681 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2682 } 2683 2684 // Detect an interleave shuffle and lower to 2685 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2686 bool SwapSources; 2687 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2688 // Swap sources if needed. 2689 if (SwapSources) 2690 std::swap(V1, V2); 2691 2692 // Extract the lower half of the vectors. 2693 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2694 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2695 DAG.getConstant(0, DL, XLenVT)); 2696 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2697 DAG.getConstant(0, DL, XLenVT)); 2698 2699 // Double the element width and halve the number of elements in an int type. 2700 unsigned EltBits = VT.getScalarSizeInBits(); 2701 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2702 MVT WideIntVT = 2703 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2704 // Convert this to a scalable vector. We need to base this on the 2705 // destination size to ensure there's always a type with a smaller LMUL. 2706 MVT WideIntContainerVT = 2707 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2708 2709 // Convert sources to scalable vectors with the same element count as the 2710 // larger type. 2711 MVT HalfContainerVT = MVT::getVectorVT( 2712 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2713 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2714 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2715 2716 // Cast sources to integer. 2717 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2718 MVT IntHalfVT = 2719 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2720 V1 = DAG.getBitcast(IntHalfVT, V1); 2721 V2 = DAG.getBitcast(IntHalfVT, V2); 2722 2723 // Freeze V2 since we use it twice and we need to be sure that the add and 2724 // multiply see the same value. 2725 V2 = DAG.getFreeze(V2); 2726 2727 // Recreate TrueMask using the widened type's element count. 2728 TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG); 2729 2730 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2731 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2732 V2, TrueMask, VL); 2733 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2734 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2735 DAG.getUNDEF(IntHalfVT), 2736 DAG.getAllOnesConstant(DL, XLenVT)); 2737 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2738 V2, Multiplier, TrueMask, VL); 2739 // Add the new copies to our previous addition giving us 2^eltbits copies of 2740 // V2. This is equivalent to shifting V2 left by eltbits. This should 2741 // combine with the vwmulu.vv above to form vwmaccu.vv. 2742 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2743 TrueMask, VL); 2744 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2745 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2746 // vector VT. 2747 ContainerVT = 2748 MVT::getVectorVT(VT.getVectorElementType(), 2749 WideIntContainerVT.getVectorElementCount() * 2); 2750 Add = DAG.getBitcast(ContainerVT, Add); 2751 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2752 } 2753 2754 // Detect shuffles which can be re-expressed as vector selects; these are 2755 // shuffles in which each element in the destination is taken from an element 2756 // at the corresponding index in either source vectors. 2757 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2758 int MaskIndex = MaskIdx.value(); 2759 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2760 }); 2761 2762 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2763 2764 SmallVector<SDValue> MaskVals; 2765 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2766 // merged with a second vrgather. 2767 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2768 2769 // By default we preserve the original operand order, and use a mask to 2770 // select LHS as true and RHS as false. However, since RVV vector selects may 2771 // feature splats but only on the LHS, we may choose to invert our mask and 2772 // instead select between RHS and LHS. 2773 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2774 bool InvertMask = IsSelect == SwapOps; 2775 2776 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2777 // half. 2778 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2779 2780 // Now construct the mask that will be used by the vselect or blended 2781 // vrgather operation. For vrgathers, construct the appropriate indices into 2782 // each vector. 2783 for (int MaskIndex : Mask) { 2784 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2785 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2786 if (!IsSelect) { 2787 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2788 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2789 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2790 : DAG.getUNDEF(XLenVT)); 2791 GatherIndicesRHS.push_back( 2792 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2793 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2794 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2795 ++LHSIndexCounts[MaskIndex]; 2796 if (!IsLHSOrUndefIndex) 2797 ++RHSIndexCounts[MaskIndex - NumElts]; 2798 } 2799 } 2800 2801 if (SwapOps) { 2802 std::swap(V1, V2); 2803 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2804 } 2805 2806 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2807 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2808 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2809 2810 if (IsSelect) 2811 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2812 2813 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2814 // On such a large vector we're unable to use i8 as the index type. 2815 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2816 // may involve vector splitting if we're already at LMUL=8, or our 2817 // user-supplied maximum fixed-length LMUL. 2818 return SDValue(); 2819 } 2820 2821 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2822 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2823 MVT IndexVT = VT.changeTypeToInteger(); 2824 // Since we can't introduce illegal index types at this stage, use i16 and 2825 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2826 // than XLenVT. 2827 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2828 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2829 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2830 } 2831 2832 MVT IndexContainerVT = 2833 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2834 2835 SDValue Gather; 2836 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2837 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2838 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2839 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2840 Subtarget); 2841 } else { 2842 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2843 // If only one index is used, we can use a "splat" vrgather. 2844 // TODO: We can splat the most-common index and fix-up any stragglers, if 2845 // that's beneficial. 2846 if (LHSIndexCounts.size() == 1) { 2847 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2848 Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2849 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, 2850 DAG.getUNDEF(ContainerVT), VL); 2851 } else { 2852 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2853 LHSIndices = 2854 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2855 2856 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2857 TrueMask, DAG.getUNDEF(ContainerVT), VL); 2858 } 2859 } 2860 2861 // If a second vector operand is used by this shuffle, blend it in with an 2862 // additional vrgather. 2863 if (!V2.isUndef()) { 2864 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2865 2866 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2867 SelectMask = 2868 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2869 2870 // If only one index is used, we can use a "splat" vrgather. 2871 // TODO: We can splat the most-common index and fix-up any stragglers, if 2872 // that's beneficial. 2873 if (RHSIndexCounts.size() == 1) { 2874 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2875 Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2876 DAG.getConstant(SplatIndex, DL, XLenVT), SelectMask, 2877 Gather, VL); 2878 } else { 2879 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2880 RHSIndices = 2881 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2882 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, 2883 SelectMask, Gather, VL); 2884 } 2885 } 2886 2887 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2888 } 2889 2890 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2891 // Support splats for any type. These should type legalize well. 2892 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2893 return true; 2894 2895 // Only support legal VTs for other shuffles for now. 2896 if (!isTypeLegal(VT)) 2897 return false; 2898 2899 MVT SVT = VT.getSimpleVT(); 2900 2901 bool SwapSources; 2902 int LoSrc, HiSrc; 2903 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2904 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2905 } 2906 2907 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2908 // the exponent. 2909 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2910 MVT VT = Op.getSimpleValueType(); 2911 unsigned EltSize = VT.getScalarSizeInBits(); 2912 SDValue Src = Op.getOperand(0); 2913 SDLoc DL(Op); 2914 2915 // We need a FP type that can represent the value. 2916 // TODO: Use f16 for i8 when possible? 2917 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2918 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2919 2920 // Legal types should have been checked in the RISCVTargetLowering 2921 // constructor. 2922 // TODO: Splitting may make sense in some cases. 2923 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2924 "Expected legal float type!"); 2925 2926 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2927 // The trailing zero count is equal to log2 of this single bit value. 2928 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2929 SDValue Neg = 2930 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2931 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2932 } 2933 2934 // We have a legal FP type, convert to it. 2935 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2936 // Bitcast to integer and shift the exponent to the LSB. 2937 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2938 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2939 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2940 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2941 DAG.getConstant(ShiftAmt, DL, IntVT)); 2942 // Truncate back to original type to allow vnsrl. 2943 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2944 // The exponent contains log2 of the value in biased form. 2945 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2946 2947 // For trailing zeros, we just need to subtract the bias. 2948 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2949 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2950 DAG.getConstant(ExponentBias, DL, VT)); 2951 2952 // For leading zeros, we need to remove the bias and convert from log2 to 2953 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2954 unsigned Adjust = ExponentBias + (EltSize - 1); 2955 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2956 } 2957 2958 // While RVV has alignment restrictions, we should always be able to load as a 2959 // legal equivalently-sized byte-typed vector instead. This method is 2960 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2961 // the load is already correctly-aligned, it returns SDValue(). 2962 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2963 SelectionDAG &DAG) const { 2964 auto *Load = cast<LoadSDNode>(Op); 2965 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2966 2967 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2968 Load->getMemoryVT(), 2969 *Load->getMemOperand())) 2970 return SDValue(); 2971 2972 SDLoc DL(Op); 2973 MVT VT = Op.getSimpleValueType(); 2974 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2975 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2976 "Unexpected unaligned RVV load type"); 2977 MVT NewVT = 2978 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2979 assert(NewVT.isValid() && 2980 "Expecting equally-sized RVV vector types to be legal"); 2981 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2982 Load->getPointerInfo(), Load->getOriginalAlign(), 2983 Load->getMemOperand()->getFlags()); 2984 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2985 } 2986 2987 // While RVV has alignment restrictions, we should always be able to store as a 2988 // legal equivalently-sized byte-typed vector instead. This method is 2989 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2990 // returns SDValue() if the store is already correctly aligned. 2991 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2992 SelectionDAG &DAG) const { 2993 auto *Store = cast<StoreSDNode>(Op); 2994 assert(Store && Store->getValue().getValueType().isVector() && 2995 "Expected vector store"); 2996 2997 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2998 Store->getMemoryVT(), 2999 *Store->getMemOperand())) 3000 return SDValue(); 3001 3002 SDLoc DL(Op); 3003 SDValue StoredVal = Store->getValue(); 3004 MVT VT = StoredVal.getSimpleValueType(); 3005 unsigned EltSizeBits = VT.getScalarSizeInBits(); 3006 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 3007 "Unexpected unaligned RVV store type"); 3008 MVT NewVT = 3009 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 3010 assert(NewVT.isValid() && 3011 "Expecting equally-sized RVV vector types to be legal"); 3012 StoredVal = DAG.getBitcast(NewVT, StoredVal); 3013 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 3014 Store->getPointerInfo(), Store->getOriginalAlign(), 3015 Store->getMemOperand()->getFlags()); 3016 } 3017 3018 static SDValue lowerConstant(SDValue Op, SelectionDAG &DAG, 3019 const RISCVSubtarget &Subtarget) { 3020 assert(Op.getValueType() == MVT::i64 && "Unexpected VT"); 3021 3022 int64_t Imm = cast<ConstantSDNode>(Op)->getSExtValue(); 3023 3024 // All simm32 constants should be handled by isel. 3025 // NOTE: The getMaxBuildIntsCost call below should return a value >= 2 making 3026 // this check redundant, but small immediates are common so this check 3027 // should have better compile time. 3028 if (isInt<32>(Imm)) 3029 return Op; 3030 3031 // We only need to cost the immediate, if constant pool lowering is enabled. 3032 if (!Subtarget.useConstantPoolForLargeInts()) 3033 return Op; 3034 3035 RISCVMatInt::InstSeq Seq = 3036 RISCVMatInt::generateInstSeq(Imm, Subtarget.getFeatureBits()); 3037 if (Seq.size() <= Subtarget.getMaxBuildIntsCost()) 3038 return Op; 3039 3040 // Expand to a constant pool using the default expansion code. 3041 return SDValue(); 3042 } 3043 3044 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 3045 SelectionDAG &DAG) const { 3046 switch (Op.getOpcode()) { 3047 default: 3048 report_fatal_error("unimplemented operand"); 3049 case ISD::GlobalAddress: 3050 return lowerGlobalAddress(Op, DAG); 3051 case ISD::BlockAddress: 3052 return lowerBlockAddress(Op, DAG); 3053 case ISD::ConstantPool: 3054 return lowerConstantPool(Op, DAG); 3055 case ISD::JumpTable: 3056 return lowerJumpTable(Op, DAG); 3057 case ISD::GlobalTLSAddress: 3058 return lowerGlobalTLSAddress(Op, DAG); 3059 case ISD::Constant: 3060 return lowerConstant(Op, DAG, Subtarget); 3061 case ISD::SELECT: 3062 return lowerSELECT(Op, DAG); 3063 case ISD::BRCOND: 3064 return lowerBRCOND(Op, DAG); 3065 case ISD::VASTART: 3066 return lowerVASTART(Op, DAG); 3067 case ISD::FRAMEADDR: 3068 return lowerFRAMEADDR(Op, DAG); 3069 case ISD::RETURNADDR: 3070 return lowerRETURNADDR(Op, DAG); 3071 case ISD::SHL_PARTS: 3072 return lowerShiftLeftParts(Op, DAG); 3073 case ISD::SRA_PARTS: 3074 return lowerShiftRightParts(Op, DAG, true); 3075 case ISD::SRL_PARTS: 3076 return lowerShiftRightParts(Op, DAG, false); 3077 case ISD::BITCAST: { 3078 SDLoc DL(Op); 3079 EVT VT = Op.getValueType(); 3080 SDValue Op0 = Op.getOperand(0); 3081 EVT Op0VT = Op0.getValueType(); 3082 MVT XLenVT = Subtarget.getXLenVT(); 3083 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 3084 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 3085 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 3086 return FPConv; 3087 } 3088 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 3089 Subtarget.hasStdExtF()) { 3090 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3091 SDValue FPConv = 3092 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3093 return FPConv; 3094 } 3095 3096 // Consider other scalar<->scalar casts as legal if the types are legal. 3097 // Otherwise expand them. 3098 if (!VT.isVector() && !Op0VT.isVector()) { 3099 if (isTypeLegal(VT) && isTypeLegal(Op0VT)) 3100 return Op; 3101 return SDValue(); 3102 } 3103 3104 assert(!VT.isScalableVector() && !Op0VT.isScalableVector() && 3105 "Unexpected types"); 3106 3107 if (VT.isFixedLengthVector()) { 3108 // We can handle fixed length vector bitcasts with a simple replacement 3109 // in isel. 3110 if (Op0VT.isFixedLengthVector()) 3111 return Op; 3112 // When bitcasting from scalar to fixed-length vector, insert the scalar 3113 // into a one-element vector of the result type, and perform a vector 3114 // bitcast. 3115 if (!Op0VT.isVector()) { 3116 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 3117 if (!isTypeLegal(BVT)) 3118 return SDValue(); 3119 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 3120 DAG.getUNDEF(BVT), Op0, 3121 DAG.getConstant(0, DL, XLenVT))); 3122 } 3123 return SDValue(); 3124 } 3125 // Custom-legalize bitcasts from fixed-length vector types to scalar types 3126 // thus: bitcast the vector to a one-element vector type whose element type 3127 // is the same as the result type, and extract the first element. 3128 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 3129 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 3130 if (!isTypeLegal(BVT)) 3131 return SDValue(); 3132 SDValue BVec = DAG.getBitcast(BVT, Op0); 3133 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 3134 DAG.getConstant(0, DL, XLenVT)); 3135 } 3136 return SDValue(); 3137 } 3138 case ISD::INTRINSIC_WO_CHAIN: 3139 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3140 case ISD::INTRINSIC_W_CHAIN: 3141 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3142 case ISD::INTRINSIC_VOID: 3143 return LowerINTRINSIC_VOID(Op, DAG); 3144 case ISD::BSWAP: 3145 case ISD::BITREVERSE: { 3146 MVT VT = Op.getSimpleValueType(); 3147 SDLoc DL(Op); 3148 if (Subtarget.hasStdExtZbp()) { 3149 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3150 // Start with the maximum immediate value which is the bitwidth - 1. 3151 unsigned Imm = VT.getSizeInBits() - 1; 3152 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3153 if (Op.getOpcode() == ISD::BSWAP) 3154 Imm &= ~0x7U; 3155 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3156 DAG.getConstant(Imm, DL, VT)); 3157 } 3158 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3159 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3160 // Expand bitreverse to a bswap(rev8) followed by brev8. 3161 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3162 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3163 // as brev8 by an isel pattern. 3164 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3165 DAG.getConstant(7, DL, VT)); 3166 } 3167 case ISD::FSHL: 3168 case ISD::FSHR: { 3169 MVT VT = Op.getSimpleValueType(); 3170 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3171 SDLoc DL(Op); 3172 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3173 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3174 // accidentally setting the extra bit. 3175 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3176 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3177 DAG.getConstant(ShAmtWidth, DL, VT)); 3178 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3179 // instruction use different orders. fshl will return its first operand for 3180 // shift of zero, fshr will return its second operand. fsl and fsr both 3181 // return rs1 so the ISD nodes need to have different operand orders. 3182 // Shift amount is in rs2. 3183 SDValue Op0 = Op.getOperand(0); 3184 SDValue Op1 = Op.getOperand(1); 3185 unsigned Opc = RISCVISD::FSL; 3186 if (Op.getOpcode() == ISD::FSHR) { 3187 std::swap(Op0, Op1); 3188 Opc = RISCVISD::FSR; 3189 } 3190 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3191 } 3192 case ISD::TRUNCATE: 3193 // Only custom-lower vector truncates 3194 if (!Op.getSimpleValueType().isVector()) 3195 return Op; 3196 return lowerVectorTruncLike(Op, DAG); 3197 case ISD::ANY_EXTEND: 3198 case ISD::ZERO_EXTEND: 3199 if (Op.getOperand(0).getValueType().isVector() && 3200 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3201 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3202 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3203 case ISD::SIGN_EXTEND: 3204 if (Op.getOperand(0).getValueType().isVector() && 3205 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3206 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3207 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3208 case ISD::SPLAT_VECTOR_PARTS: 3209 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3210 case ISD::INSERT_VECTOR_ELT: 3211 return lowerINSERT_VECTOR_ELT(Op, DAG); 3212 case ISD::EXTRACT_VECTOR_ELT: 3213 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3214 case ISD::VSCALE: { 3215 MVT VT = Op.getSimpleValueType(); 3216 SDLoc DL(Op); 3217 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3218 // We define our scalable vector types for lmul=1 to use a 64 bit known 3219 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3220 // vscale as VLENB / 8. 3221 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3222 if (Subtarget.getRealMinVLen() < RISCV::RVVBitsPerBlock) 3223 report_fatal_error("Support for VLEN==32 is incomplete."); 3224 // We assume VLENB is a multiple of 8. We manually choose the best shift 3225 // here because SimplifyDemandedBits isn't always able to simplify it. 3226 uint64_t Val = Op.getConstantOperandVal(0); 3227 if (isPowerOf2_64(Val)) { 3228 uint64_t Log2 = Log2_64(Val); 3229 if (Log2 < 3) 3230 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3231 DAG.getConstant(3 - Log2, DL, VT)); 3232 if (Log2 > 3) 3233 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3234 DAG.getConstant(Log2 - 3, DL, VT)); 3235 return VLENB; 3236 } 3237 // If the multiplier is a multiple of 8, scale it down to avoid needing 3238 // to shift the VLENB value. 3239 if ((Val % 8) == 0) 3240 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3241 DAG.getConstant(Val / 8, DL, VT)); 3242 3243 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3244 DAG.getConstant(3, DL, VT)); 3245 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3246 } 3247 case ISD::FPOWI: { 3248 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3249 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3250 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3251 Op.getOperand(1).getValueType() == MVT::i32) { 3252 SDLoc DL(Op); 3253 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3254 SDValue Powi = 3255 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3256 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3257 DAG.getIntPtrConstant(0, DL)); 3258 } 3259 return SDValue(); 3260 } 3261 case ISD::FP_EXTEND: 3262 case ISD::FP_ROUND: 3263 if (!Op.getValueType().isVector()) 3264 return Op; 3265 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3266 case ISD::FP_TO_SINT: 3267 case ISD::FP_TO_UINT: 3268 case ISD::SINT_TO_FP: 3269 case ISD::UINT_TO_FP: { 3270 // RVV can only do fp<->int conversions to types half/double the size as 3271 // the source. We custom-lower any conversions that do two hops into 3272 // sequences. 3273 MVT VT = Op.getSimpleValueType(); 3274 if (!VT.isVector()) 3275 return Op; 3276 SDLoc DL(Op); 3277 SDValue Src = Op.getOperand(0); 3278 MVT EltVT = VT.getVectorElementType(); 3279 MVT SrcVT = Src.getSimpleValueType(); 3280 MVT SrcEltVT = SrcVT.getVectorElementType(); 3281 unsigned EltSize = EltVT.getSizeInBits(); 3282 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3283 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3284 "Unexpected vector element types"); 3285 3286 bool IsInt2FP = SrcEltVT.isInteger(); 3287 // Widening conversions 3288 if (EltSize > (2 * SrcEltSize)) { 3289 if (IsInt2FP) { 3290 // Do a regular integer sign/zero extension then convert to float. 3291 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), 3292 VT.getVectorElementCount()); 3293 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3294 ? ISD::ZERO_EXTEND 3295 : ISD::SIGN_EXTEND; 3296 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3297 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3298 } 3299 // FP2Int 3300 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3301 // Do one doubling fp_extend then complete the operation by converting 3302 // to int. 3303 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3304 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3305 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3306 } 3307 3308 // Narrowing conversions 3309 if (SrcEltSize > (2 * EltSize)) { 3310 if (IsInt2FP) { 3311 // One narrowing int_to_fp, then an fp_round. 3312 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3313 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3314 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3315 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3316 } 3317 // FP2Int 3318 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3319 // representable by the integer, the result is poison. 3320 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 3321 VT.getVectorElementCount()); 3322 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3323 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3324 } 3325 3326 // Scalable vectors can exit here. Patterns will handle equally-sized 3327 // conversions halving/doubling ones. 3328 if (!VT.isFixedLengthVector()) 3329 return Op; 3330 3331 // For fixed-length vectors we lower to a custom "VL" node. 3332 unsigned RVVOpc = 0; 3333 switch (Op.getOpcode()) { 3334 default: 3335 llvm_unreachable("Impossible opcode"); 3336 case ISD::FP_TO_SINT: 3337 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3338 break; 3339 case ISD::FP_TO_UINT: 3340 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3341 break; 3342 case ISD::SINT_TO_FP: 3343 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3344 break; 3345 case ISD::UINT_TO_FP: 3346 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3347 break; 3348 } 3349 3350 MVT ContainerVT, SrcContainerVT; 3351 // Derive the reference container type from the larger vector type. 3352 if (SrcEltSize > EltSize) { 3353 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3354 ContainerVT = 3355 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3356 } else { 3357 ContainerVT = getContainerForFixedLengthVector(VT); 3358 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3359 } 3360 3361 SDValue Mask, VL; 3362 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3363 3364 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3365 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3366 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3367 } 3368 case ISD::FP_TO_SINT_SAT: 3369 case ISD::FP_TO_UINT_SAT: 3370 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3371 case ISD::FTRUNC: 3372 case ISD::FCEIL: 3373 case ISD::FFLOOR: 3374 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3375 case ISD::FROUND: 3376 return lowerFROUND(Op, DAG); 3377 case ISD::VECREDUCE_ADD: 3378 case ISD::VECREDUCE_UMAX: 3379 case ISD::VECREDUCE_SMAX: 3380 case ISD::VECREDUCE_UMIN: 3381 case ISD::VECREDUCE_SMIN: 3382 return lowerVECREDUCE(Op, DAG); 3383 case ISD::VECREDUCE_AND: 3384 case ISD::VECREDUCE_OR: 3385 case ISD::VECREDUCE_XOR: 3386 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3387 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3388 return lowerVECREDUCE(Op, DAG); 3389 case ISD::VECREDUCE_FADD: 3390 case ISD::VECREDUCE_SEQ_FADD: 3391 case ISD::VECREDUCE_FMIN: 3392 case ISD::VECREDUCE_FMAX: 3393 return lowerFPVECREDUCE(Op, DAG); 3394 case ISD::VP_REDUCE_ADD: 3395 case ISD::VP_REDUCE_UMAX: 3396 case ISD::VP_REDUCE_SMAX: 3397 case ISD::VP_REDUCE_UMIN: 3398 case ISD::VP_REDUCE_SMIN: 3399 case ISD::VP_REDUCE_FADD: 3400 case ISD::VP_REDUCE_SEQ_FADD: 3401 case ISD::VP_REDUCE_FMIN: 3402 case ISD::VP_REDUCE_FMAX: 3403 return lowerVPREDUCE(Op, DAG); 3404 case ISD::VP_REDUCE_AND: 3405 case ISD::VP_REDUCE_OR: 3406 case ISD::VP_REDUCE_XOR: 3407 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3408 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3409 return lowerVPREDUCE(Op, DAG); 3410 case ISD::INSERT_SUBVECTOR: 3411 return lowerINSERT_SUBVECTOR(Op, DAG); 3412 case ISD::EXTRACT_SUBVECTOR: 3413 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3414 case ISD::STEP_VECTOR: 3415 return lowerSTEP_VECTOR(Op, DAG); 3416 case ISD::VECTOR_REVERSE: 3417 return lowerVECTOR_REVERSE(Op, DAG); 3418 case ISD::VECTOR_SPLICE: 3419 return lowerVECTOR_SPLICE(Op, DAG); 3420 case ISD::BUILD_VECTOR: 3421 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3422 case ISD::SPLAT_VECTOR: 3423 if (Op.getValueType().getVectorElementType() == MVT::i1) 3424 return lowerVectorMaskSplat(Op, DAG); 3425 return SDValue(); 3426 case ISD::VECTOR_SHUFFLE: 3427 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3428 case ISD::CONCAT_VECTORS: { 3429 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3430 // better than going through the stack, as the default expansion does. 3431 SDLoc DL(Op); 3432 MVT VT = Op.getSimpleValueType(); 3433 unsigned NumOpElts = 3434 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3435 SDValue Vec = DAG.getUNDEF(VT); 3436 for (const auto &OpIdx : enumerate(Op->ops())) { 3437 SDValue SubVec = OpIdx.value(); 3438 // Don't insert undef subvectors. 3439 if (SubVec.isUndef()) 3440 continue; 3441 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3442 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3443 } 3444 return Vec; 3445 } 3446 case ISD::LOAD: 3447 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3448 return V; 3449 if (Op.getValueType().isFixedLengthVector()) 3450 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3451 return Op; 3452 case ISD::STORE: 3453 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3454 return V; 3455 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3456 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3457 return Op; 3458 case ISD::MLOAD: 3459 case ISD::VP_LOAD: 3460 return lowerMaskedLoad(Op, DAG); 3461 case ISD::MSTORE: 3462 case ISD::VP_STORE: 3463 return lowerMaskedStore(Op, DAG); 3464 case ISD::SETCC: 3465 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3466 case ISD::ADD: 3467 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3468 case ISD::SUB: 3469 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3470 case ISD::MUL: 3471 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3472 case ISD::MULHS: 3473 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3474 case ISD::MULHU: 3475 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3476 case ISD::AND: 3477 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3478 RISCVISD::AND_VL); 3479 case ISD::OR: 3480 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3481 RISCVISD::OR_VL); 3482 case ISD::XOR: 3483 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3484 RISCVISD::XOR_VL); 3485 case ISD::SDIV: 3486 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3487 case ISD::SREM: 3488 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3489 case ISD::UDIV: 3490 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3491 case ISD::UREM: 3492 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3493 case ISD::SHL: 3494 case ISD::SRA: 3495 case ISD::SRL: 3496 if (Op.getSimpleValueType().isFixedLengthVector()) 3497 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3498 // This can be called for an i32 shift amount that needs to be promoted. 3499 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3500 "Unexpected custom legalisation"); 3501 return SDValue(); 3502 case ISD::SADDSAT: 3503 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3504 case ISD::UADDSAT: 3505 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3506 case ISD::SSUBSAT: 3507 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3508 case ISD::USUBSAT: 3509 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3510 case ISD::FADD: 3511 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3512 case ISD::FSUB: 3513 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3514 case ISD::FMUL: 3515 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3516 case ISD::FDIV: 3517 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3518 case ISD::FNEG: 3519 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3520 case ISD::FABS: 3521 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3522 case ISD::FSQRT: 3523 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3524 case ISD::FMA: 3525 return lowerToScalableOp(Op, DAG, RISCVISD::VFMADD_VL); 3526 case ISD::SMIN: 3527 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3528 case ISD::SMAX: 3529 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3530 case ISD::UMIN: 3531 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3532 case ISD::UMAX: 3533 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3534 case ISD::FMINNUM: 3535 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3536 case ISD::FMAXNUM: 3537 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3538 case ISD::ABS: 3539 return lowerABS(Op, DAG); 3540 case ISD::CTLZ_ZERO_UNDEF: 3541 case ISD::CTTZ_ZERO_UNDEF: 3542 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3543 case ISD::VSELECT: 3544 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3545 case ISD::FCOPYSIGN: 3546 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3547 case ISD::MGATHER: 3548 case ISD::VP_GATHER: 3549 return lowerMaskedGather(Op, DAG); 3550 case ISD::MSCATTER: 3551 case ISD::VP_SCATTER: 3552 return lowerMaskedScatter(Op, DAG); 3553 case ISD::FLT_ROUNDS_: 3554 return lowerGET_ROUNDING(Op, DAG); 3555 case ISD::SET_ROUNDING: 3556 return lowerSET_ROUNDING(Op, DAG); 3557 case ISD::EH_DWARF_CFA: 3558 return lowerEH_DWARF_CFA(Op, DAG); 3559 case ISD::VP_SELECT: 3560 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3561 case ISD::VP_MERGE: 3562 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3563 case ISD::VP_ADD: 3564 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3565 case ISD::VP_SUB: 3566 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3567 case ISD::VP_MUL: 3568 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3569 case ISD::VP_SDIV: 3570 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3571 case ISD::VP_UDIV: 3572 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3573 case ISD::VP_SREM: 3574 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3575 case ISD::VP_UREM: 3576 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3577 case ISD::VP_AND: 3578 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3579 case ISD::VP_OR: 3580 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3581 case ISD::VP_XOR: 3582 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3583 case ISD::VP_ASHR: 3584 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3585 case ISD::VP_LSHR: 3586 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3587 case ISD::VP_SHL: 3588 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3589 case ISD::VP_FADD: 3590 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3591 case ISD::VP_FSUB: 3592 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3593 case ISD::VP_FMUL: 3594 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3595 case ISD::VP_FDIV: 3596 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3597 case ISD::VP_FNEG: 3598 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3599 case ISD::VP_FMA: 3600 return lowerVPOp(Op, DAG, RISCVISD::VFMADD_VL); 3601 case ISD::VP_SIGN_EXTEND: 3602 case ISD::VP_ZERO_EXTEND: 3603 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3604 return lowerVPExtMaskOp(Op, DAG); 3605 return lowerVPOp(Op, DAG, 3606 Op.getOpcode() == ISD::VP_SIGN_EXTEND 3607 ? RISCVISD::VSEXT_VL 3608 : RISCVISD::VZEXT_VL); 3609 case ISD::VP_TRUNCATE: 3610 return lowerVectorTruncLike(Op, DAG); 3611 case ISD::VP_FP_EXTEND: 3612 case ISD::VP_FP_ROUND: 3613 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3614 case ISD::VP_FPTOSI: 3615 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL); 3616 case ISD::VP_FPTOUI: 3617 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL); 3618 case ISD::VP_SITOFP: 3619 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL); 3620 case ISD::VP_UITOFP: 3621 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL); 3622 case ISD::VP_SETCC: 3623 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3624 return lowerVPSetCCMaskOp(Op, DAG); 3625 return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL); 3626 } 3627 } 3628 3629 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3630 SelectionDAG &DAG, unsigned Flags) { 3631 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3632 } 3633 3634 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3635 SelectionDAG &DAG, unsigned Flags) { 3636 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3637 Flags); 3638 } 3639 3640 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3641 SelectionDAG &DAG, unsigned Flags) { 3642 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3643 N->getOffset(), Flags); 3644 } 3645 3646 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3647 SelectionDAG &DAG, unsigned Flags) { 3648 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3649 } 3650 3651 template <class NodeTy> 3652 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3653 bool IsLocal) const { 3654 SDLoc DL(N); 3655 EVT Ty = getPointerTy(DAG.getDataLayout()); 3656 3657 if (isPositionIndependent()) { 3658 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3659 if (IsLocal) 3660 // Use PC-relative addressing to access the symbol. This generates the 3661 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3662 // %pcrel_lo(auipc)). 3663 return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr); 3664 3665 // Use PC-relative addressing to access the GOT for this symbol, then load 3666 // the address from the GOT. This generates the pattern (PseudoLA sym), 3667 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3668 MachineFunction &MF = DAG.getMachineFunction(); 3669 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3670 MachinePointerInfo::getGOT(MF), 3671 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3672 MachineMemOperand::MOInvariant, 3673 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3674 SDValue Load = 3675 DAG.getMemIntrinsicNode(RISCVISD::LA, DL, DAG.getVTList(Ty, MVT::Other), 3676 {DAG.getEntryNode(), Addr}, Ty, MemOp); 3677 return Load; 3678 } 3679 3680 switch (getTargetMachine().getCodeModel()) { 3681 default: 3682 report_fatal_error("Unsupported code model for lowering"); 3683 case CodeModel::Small: { 3684 // Generate a sequence for accessing addresses within the first 2 GiB of 3685 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3686 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3687 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3688 SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi); 3689 return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNHi, AddrLo); 3690 } 3691 case CodeModel::Medium: { 3692 // Generate a sequence for accessing addresses within any 2GiB range within 3693 // the address space. This generates the pattern (PseudoLLA sym), which 3694 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3695 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3696 return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr); 3697 } 3698 } 3699 } 3700 3701 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3702 SelectionDAG &DAG) const { 3703 SDLoc DL(Op); 3704 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3705 assert(N->getOffset() == 0 && "unexpected offset in global node"); 3706 return getAddr(N, DAG, N->getGlobal()->isDSOLocal()); 3707 } 3708 3709 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3710 SelectionDAG &DAG) const { 3711 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3712 3713 return getAddr(N, DAG); 3714 } 3715 3716 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3717 SelectionDAG &DAG) const { 3718 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3719 3720 return getAddr(N, DAG); 3721 } 3722 3723 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3724 SelectionDAG &DAG) const { 3725 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3726 3727 return getAddr(N, DAG); 3728 } 3729 3730 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3731 SelectionDAG &DAG, 3732 bool UseGOT) const { 3733 SDLoc DL(N); 3734 EVT Ty = getPointerTy(DAG.getDataLayout()); 3735 const GlobalValue *GV = N->getGlobal(); 3736 MVT XLenVT = Subtarget.getXLenVT(); 3737 3738 if (UseGOT) { 3739 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3740 // load the address from the GOT and add the thread pointer. This generates 3741 // the pattern (PseudoLA_TLS_IE sym), which expands to 3742 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3743 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3744 MachineFunction &MF = DAG.getMachineFunction(); 3745 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3746 MachinePointerInfo::getGOT(MF), 3747 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3748 MachineMemOperand::MOInvariant, 3749 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3750 SDValue Load = DAG.getMemIntrinsicNode( 3751 RISCVISD::LA_TLS_IE, DL, DAG.getVTList(Ty, MVT::Other), 3752 {DAG.getEntryNode(), Addr}, Ty, MemOp); 3753 3754 // Add the thread pointer. 3755 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3756 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3757 } 3758 3759 // Generate a sequence for accessing the address relative to the thread 3760 // pointer, with the appropriate adjustment for the thread pointer offset. 3761 // This generates the pattern 3762 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3763 SDValue AddrHi = 3764 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3765 SDValue AddrAdd = 3766 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3767 SDValue AddrLo = 3768 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3769 3770 SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi); 3771 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3772 SDValue MNAdd = 3773 DAG.getNode(RISCVISD::ADD_TPREL, DL, Ty, MNHi, TPReg, AddrAdd); 3774 return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNAdd, AddrLo); 3775 } 3776 3777 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3778 SelectionDAG &DAG) const { 3779 SDLoc DL(N); 3780 EVT Ty = getPointerTy(DAG.getDataLayout()); 3781 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3782 const GlobalValue *GV = N->getGlobal(); 3783 3784 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3785 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3786 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3787 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3788 SDValue Load = DAG.getNode(RISCVISD::LA_TLS_GD, DL, Ty, Addr); 3789 3790 // Prepare argument list to generate call. 3791 ArgListTy Args; 3792 ArgListEntry Entry; 3793 Entry.Node = Load; 3794 Entry.Ty = CallTy; 3795 Args.push_back(Entry); 3796 3797 // Setup call to __tls_get_addr. 3798 TargetLowering::CallLoweringInfo CLI(DAG); 3799 CLI.setDebugLoc(DL) 3800 .setChain(DAG.getEntryNode()) 3801 .setLibCallee(CallingConv::C, CallTy, 3802 DAG.getExternalSymbol("__tls_get_addr", Ty), 3803 std::move(Args)); 3804 3805 return LowerCallTo(CLI).first; 3806 } 3807 3808 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3809 SelectionDAG &DAG) const { 3810 SDLoc DL(Op); 3811 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3812 assert(N->getOffset() == 0 && "unexpected offset in global node"); 3813 3814 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3815 3816 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3817 CallingConv::GHC) 3818 report_fatal_error("In GHC calling convention TLS is not supported"); 3819 3820 SDValue Addr; 3821 switch (Model) { 3822 case TLSModel::LocalExec: 3823 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3824 break; 3825 case TLSModel::InitialExec: 3826 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3827 break; 3828 case TLSModel::LocalDynamic: 3829 case TLSModel::GeneralDynamic: 3830 Addr = getDynamicTLSAddr(N, DAG); 3831 break; 3832 } 3833 3834 return Addr; 3835 } 3836 3837 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3838 SDValue CondV = Op.getOperand(0); 3839 SDValue TrueV = Op.getOperand(1); 3840 SDValue FalseV = Op.getOperand(2); 3841 SDLoc DL(Op); 3842 MVT VT = Op.getSimpleValueType(); 3843 MVT XLenVT = Subtarget.getXLenVT(); 3844 3845 // Lower vector SELECTs to VSELECTs by splatting the condition. 3846 if (VT.isVector()) { 3847 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3848 SDValue CondSplat = VT.isScalableVector() 3849 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3850 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3851 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3852 } 3853 3854 // If the result type is XLenVT and CondV is the output of a SETCC node 3855 // which also operated on XLenVT inputs, then merge the SETCC node into the 3856 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3857 // compare+branch instructions. i.e.: 3858 // (select (setcc lhs, rhs, cc), truev, falsev) 3859 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3860 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3861 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3862 SDValue LHS = CondV.getOperand(0); 3863 SDValue RHS = CondV.getOperand(1); 3864 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3865 ISD::CondCode CCVal = CC->get(); 3866 3867 // Special case for a select of 2 constants that have a diffence of 1. 3868 // Normally this is done by DAGCombine, but if the select is introduced by 3869 // type legalization or op legalization, we miss it. Restricting to SETLT 3870 // case for now because that is what signed saturating add/sub need. 3871 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3872 // but we would probably want to swap the true/false values if the condition 3873 // is SETGE/SETLE to avoid an XORI. 3874 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3875 CCVal == ISD::SETLT) { 3876 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3877 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3878 if (TrueVal - 1 == FalseVal) 3879 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3880 if (TrueVal + 1 == FalseVal) 3881 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3882 } 3883 3884 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3885 3886 SDValue TargetCC = DAG.getCondCode(CCVal); 3887 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3888 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3889 } 3890 3891 // Otherwise: 3892 // (select condv, truev, falsev) 3893 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3894 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3895 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3896 3897 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3898 3899 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3900 } 3901 3902 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3903 SDValue CondV = Op.getOperand(1); 3904 SDLoc DL(Op); 3905 MVT XLenVT = Subtarget.getXLenVT(); 3906 3907 if (CondV.getOpcode() == ISD::SETCC && 3908 CondV.getOperand(0).getValueType() == XLenVT) { 3909 SDValue LHS = CondV.getOperand(0); 3910 SDValue RHS = CondV.getOperand(1); 3911 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3912 3913 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3914 3915 SDValue TargetCC = DAG.getCondCode(CCVal); 3916 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3917 LHS, RHS, TargetCC, Op.getOperand(2)); 3918 } 3919 3920 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3921 CondV, DAG.getConstant(0, DL, XLenVT), 3922 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3923 } 3924 3925 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3926 MachineFunction &MF = DAG.getMachineFunction(); 3927 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3928 3929 SDLoc DL(Op); 3930 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3931 getPointerTy(MF.getDataLayout())); 3932 3933 // vastart just stores the address of the VarArgsFrameIndex slot into the 3934 // memory location argument. 3935 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3936 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3937 MachinePointerInfo(SV)); 3938 } 3939 3940 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3941 SelectionDAG &DAG) const { 3942 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3943 MachineFunction &MF = DAG.getMachineFunction(); 3944 MachineFrameInfo &MFI = MF.getFrameInfo(); 3945 MFI.setFrameAddressIsTaken(true); 3946 Register FrameReg = RI.getFrameRegister(MF); 3947 int XLenInBytes = Subtarget.getXLen() / 8; 3948 3949 EVT VT = Op.getValueType(); 3950 SDLoc DL(Op); 3951 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3952 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3953 while (Depth--) { 3954 int Offset = -(XLenInBytes * 2); 3955 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3956 DAG.getIntPtrConstant(Offset, DL)); 3957 FrameAddr = 3958 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3959 } 3960 return FrameAddr; 3961 } 3962 3963 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3964 SelectionDAG &DAG) const { 3965 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3966 MachineFunction &MF = DAG.getMachineFunction(); 3967 MachineFrameInfo &MFI = MF.getFrameInfo(); 3968 MFI.setReturnAddressIsTaken(true); 3969 MVT XLenVT = Subtarget.getXLenVT(); 3970 int XLenInBytes = Subtarget.getXLen() / 8; 3971 3972 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3973 return SDValue(); 3974 3975 EVT VT = Op.getValueType(); 3976 SDLoc DL(Op); 3977 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3978 if (Depth) { 3979 int Off = -XLenInBytes; 3980 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3981 SDValue Offset = DAG.getConstant(Off, DL, VT); 3982 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3983 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3984 MachinePointerInfo()); 3985 } 3986 3987 // Return the value of the return address register, marking it an implicit 3988 // live-in. 3989 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3990 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3991 } 3992 3993 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3994 SelectionDAG &DAG) const { 3995 SDLoc DL(Op); 3996 SDValue Lo = Op.getOperand(0); 3997 SDValue Hi = Op.getOperand(1); 3998 SDValue Shamt = Op.getOperand(2); 3999 EVT VT = Lo.getValueType(); 4000 4001 // if Shamt-XLEN < 0: // Shamt < XLEN 4002 // Lo = Lo << Shamt 4003 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 4004 // else: 4005 // Lo = 0 4006 // Hi = Lo << (Shamt-XLEN) 4007 4008 SDValue Zero = DAG.getConstant(0, DL, VT); 4009 SDValue One = DAG.getConstant(1, DL, VT); 4010 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4011 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4012 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4013 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4014 4015 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 4016 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 4017 SDValue ShiftRightLo = 4018 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 4019 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 4020 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 4021 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 4022 4023 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4024 4025 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 4026 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4027 4028 SDValue Parts[2] = {Lo, Hi}; 4029 return DAG.getMergeValues(Parts, DL); 4030 } 4031 4032 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 4033 bool IsSRA) const { 4034 SDLoc DL(Op); 4035 SDValue Lo = Op.getOperand(0); 4036 SDValue Hi = Op.getOperand(1); 4037 SDValue Shamt = Op.getOperand(2); 4038 EVT VT = Lo.getValueType(); 4039 4040 // SRA expansion: 4041 // if Shamt-XLEN < 0: // Shamt < XLEN 4042 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4043 // Hi = Hi >>s Shamt 4044 // else: 4045 // Lo = Hi >>s (Shamt-XLEN); 4046 // Hi = Hi >>s (XLEN-1) 4047 // 4048 // SRL expansion: 4049 // if Shamt-XLEN < 0: // Shamt < XLEN 4050 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4051 // Hi = Hi >>u Shamt 4052 // else: 4053 // Lo = Hi >>u (Shamt-XLEN); 4054 // Hi = 0; 4055 4056 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 4057 4058 SDValue Zero = DAG.getConstant(0, DL, VT); 4059 SDValue One = DAG.getConstant(1, DL, VT); 4060 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4061 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4062 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4063 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4064 4065 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 4066 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 4067 SDValue ShiftLeftHi = 4068 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 4069 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 4070 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 4071 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 4072 SDValue HiFalse = 4073 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 4074 4075 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4076 4077 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 4078 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4079 4080 SDValue Parts[2] = {Lo, Hi}; 4081 return DAG.getMergeValues(Parts, DL); 4082 } 4083 4084 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 4085 // legal equivalently-sized i8 type, so we can use that as a go-between. 4086 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4087 SelectionDAG &DAG) const { 4088 SDLoc DL(Op); 4089 MVT VT = Op.getSimpleValueType(); 4090 SDValue SplatVal = Op.getOperand(0); 4091 // All-zeros or all-ones splats are handled specially. 4092 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4093 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4094 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4095 } 4096 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4097 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4098 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4099 } 4100 MVT XLenVT = Subtarget.getXLenVT(); 4101 assert(SplatVal.getValueType() == XLenVT && 4102 "Unexpected type for i1 splat value"); 4103 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4104 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4105 DAG.getConstant(1, DL, XLenVT)); 4106 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4107 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4108 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4109 } 4110 4111 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4112 // illegal (currently only vXi64 RV32). 4113 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4114 // them to VMV_V_X_VL. 4115 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4116 SelectionDAG &DAG) const { 4117 SDLoc DL(Op); 4118 MVT VecVT = Op.getSimpleValueType(); 4119 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4120 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4121 4122 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4123 SDValue Lo = Op.getOperand(0); 4124 SDValue Hi = Op.getOperand(1); 4125 4126 if (VecVT.isFixedLengthVector()) { 4127 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4128 SDLoc DL(Op); 4129 SDValue Mask, VL; 4130 std::tie(Mask, VL) = 4131 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4132 4133 SDValue Res = 4134 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4135 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4136 } 4137 4138 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4139 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4140 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4141 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4142 // node in order to try and match RVV vector/scalar instructions. 4143 if ((LoC >> 31) == HiC) 4144 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4145 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4146 } 4147 4148 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4149 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4150 isa<ConstantSDNode>(Hi.getOperand(1)) && 4151 Hi.getConstantOperandVal(1) == 31) 4152 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4153 DAG.getRegister(RISCV::X0, MVT::i32)); 4154 4155 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4156 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4157 DAG.getUNDEF(VecVT), Lo, Hi, 4158 DAG.getRegister(RISCV::X0, MVT::i32)); 4159 } 4160 4161 // Custom-lower extensions from mask vectors by using a vselect either with 1 4162 // for zero/any-extension or -1 for sign-extension: 4163 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4164 // Note that any-extension is lowered identically to zero-extension. 4165 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4166 int64_t ExtTrueVal) const { 4167 SDLoc DL(Op); 4168 MVT VecVT = Op.getSimpleValueType(); 4169 SDValue Src = Op.getOperand(0); 4170 // Only custom-lower extensions from mask types 4171 assert(Src.getValueType().isVector() && 4172 Src.getValueType().getVectorElementType() == MVT::i1); 4173 4174 if (VecVT.isScalableVector()) { 4175 SDValue SplatZero = DAG.getConstant(0, DL, VecVT); 4176 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT); 4177 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4178 } 4179 4180 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4181 MVT I1ContainerVT = 4182 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4183 4184 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4185 4186 SDValue Mask, VL; 4187 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4188 4189 MVT XLenVT = Subtarget.getXLenVT(); 4190 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4191 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4192 4193 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4194 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4195 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4196 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4197 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4198 SplatTrueVal, SplatZero, VL); 4199 4200 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4201 } 4202 4203 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4204 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4205 MVT ExtVT = Op.getSimpleValueType(); 4206 // Only custom-lower extensions from fixed-length vector types. 4207 if (!ExtVT.isFixedLengthVector()) 4208 return Op; 4209 MVT VT = Op.getOperand(0).getSimpleValueType(); 4210 // Grab the canonical container type for the extended type. Infer the smaller 4211 // type from that to ensure the same number of vector elements, as we know 4212 // the LMUL will be sufficient to hold the smaller type. 4213 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4214 // Get the extended container type manually to ensure the same number of 4215 // vector elements between source and dest. 4216 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4217 ContainerExtVT.getVectorElementCount()); 4218 4219 SDValue Op1 = 4220 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4221 4222 SDLoc DL(Op); 4223 SDValue Mask, VL; 4224 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4225 4226 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4227 4228 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4229 } 4230 4231 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4232 // setcc operation: 4233 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4234 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op, 4235 SelectionDAG &DAG) const { 4236 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4237 SDLoc DL(Op); 4238 EVT MaskVT = Op.getValueType(); 4239 // Only expect to custom-lower truncations to mask types 4240 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4241 "Unexpected type for vector mask lowering"); 4242 SDValue Src = Op.getOperand(0); 4243 MVT VecVT = Src.getSimpleValueType(); 4244 SDValue Mask, VL; 4245 if (IsVPTrunc) { 4246 Mask = Op.getOperand(1); 4247 VL = Op.getOperand(2); 4248 } 4249 // If this is a fixed vector, we need to convert it to a scalable vector. 4250 MVT ContainerVT = VecVT; 4251 4252 if (VecVT.isFixedLengthVector()) { 4253 ContainerVT = getContainerForFixedLengthVector(VecVT); 4254 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4255 if (IsVPTrunc) { 4256 MVT MaskContainerVT = 4257 getContainerForFixedLengthVector(Mask.getSimpleValueType()); 4258 Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget); 4259 } 4260 } 4261 4262 if (!IsVPTrunc) { 4263 std::tie(Mask, VL) = 4264 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4265 } 4266 4267 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4268 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4269 4270 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4271 DAG.getUNDEF(ContainerVT), SplatOne, VL); 4272 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4273 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4274 4275 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4276 SDValue Trunc = 4277 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4278 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4279 DAG.getCondCode(ISD::SETNE), Mask, VL); 4280 if (MaskVT.isFixedLengthVector()) 4281 Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4282 return Trunc; 4283 } 4284 4285 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op, 4286 SelectionDAG &DAG) const { 4287 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4288 SDLoc DL(Op); 4289 4290 MVT VT = Op.getSimpleValueType(); 4291 // Only custom-lower vector truncates 4292 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4293 4294 // Truncates to mask types are handled differently 4295 if (VT.getVectorElementType() == MVT::i1) 4296 return lowerVectorMaskTruncLike(Op, DAG); 4297 4298 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 4299 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 4300 // truncate by one power of two at a time. 4301 MVT DstEltVT = VT.getVectorElementType(); 4302 4303 SDValue Src = Op.getOperand(0); 4304 MVT SrcVT = Src.getSimpleValueType(); 4305 MVT SrcEltVT = SrcVT.getVectorElementType(); 4306 4307 assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) && 4308 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 4309 "Unexpected vector truncate lowering"); 4310 4311 MVT ContainerVT = SrcVT; 4312 SDValue Mask, VL; 4313 if (IsVPTrunc) { 4314 Mask = Op.getOperand(1); 4315 VL = Op.getOperand(2); 4316 } 4317 if (SrcVT.isFixedLengthVector()) { 4318 ContainerVT = getContainerForFixedLengthVector(SrcVT); 4319 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4320 if (IsVPTrunc) { 4321 MVT MaskVT = getMaskTypeFor(ContainerVT); 4322 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4323 } 4324 } 4325 4326 SDValue Result = Src; 4327 if (!IsVPTrunc) { 4328 std::tie(Mask, VL) = 4329 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4330 } 4331 4332 LLVMContext &Context = *DAG.getContext(); 4333 const ElementCount Count = ContainerVT.getVectorElementCount(); 4334 do { 4335 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 4336 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 4337 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 4338 Mask, VL); 4339 } while (SrcEltVT != DstEltVT); 4340 4341 if (SrcVT.isFixedLengthVector()) 4342 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4343 4344 return Result; 4345 } 4346 4347 SDValue 4348 RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op, 4349 SelectionDAG &DAG) const { 4350 bool IsVP = 4351 Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND; 4352 bool IsExtend = 4353 Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND; 4354 // RVV can only do truncate fp to types half the size as the source. We 4355 // custom-lower f64->f16 rounds via RVV's round-to-odd float 4356 // conversion instruction. 4357 SDLoc DL(Op); 4358 MVT VT = Op.getSimpleValueType(); 4359 4360 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4361 4362 SDValue Src = Op.getOperand(0); 4363 MVT SrcVT = Src.getSimpleValueType(); 4364 4365 bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 || 4366 SrcVT.getVectorElementType() != MVT::f16); 4367 bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 || 4368 SrcVT.getVectorElementType() != MVT::f64); 4369 4370 bool IsDirectConv = IsDirectExtend || IsDirectTrunc; 4371 4372 // Prepare any fixed-length vector operands. 4373 MVT ContainerVT = VT; 4374 SDValue Mask, VL; 4375 if (IsVP) { 4376 Mask = Op.getOperand(1); 4377 VL = Op.getOperand(2); 4378 } 4379 if (VT.isFixedLengthVector()) { 4380 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 4381 ContainerVT = 4382 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 4383 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 4384 if (IsVP) { 4385 MVT MaskVT = getMaskTypeFor(ContainerVT); 4386 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4387 } 4388 } 4389 4390 if (!IsVP) 4391 std::tie(Mask, VL) = 4392 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4393 4394 unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL; 4395 4396 if (IsDirectConv) { 4397 Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL); 4398 if (VT.isFixedLengthVector()) 4399 Src = convertFromScalableVector(VT, Src, DAG, Subtarget); 4400 return Src; 4401 } 4402 4403 unsigned InterConvOpc = 4404 IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL; 4405 4406 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 4407 SDValue IntermediateConv = 4408 DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL); 4409 SDValue Result = 4410 DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL); 4411 if (VT.isFixedLengthVector()) 4412 return convertFromScalableVector(VT, Result, DAG, Subtarget); 4413 return Result; 4414 } 4415 4416 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4417 // first position of a vector, and that vector is slid up to the insert index. 4418 // By limiting the active vector length to index+1 and merging with the 4419 // original vector (with an undisturbed tail policy for elements >= VL), we 4420 // achieve the desired result of leaving all elements untouched except the one 4421 // at VL-1, which is replaced with the desired value. 4422 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4423 SelectionDAG &DAG) const { 4424 SDLoc DL(Op); 4425 MVT VecVT = Op.getSimpleValueType(); 4426 SDValue Vec = Op.getOperand(0); 4427 SDValue Val = Op.getOperand(1); 4428 SDValue Idx = Op.getOperand(2); 4429 4430 if (VecVT.getVectorElementType() == MVT::i1) { 4431 // FIXME: For now we just promote to an i8 vector and insert into that, 4432 // but this is probably not optimal. 4433 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4434 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4435 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4436 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4437 } 4438 4439 MVT ContainerVT = VecVT; 4440 // If the operand is a fixed-length vector, convert to a scalable one. 4441 if (VecVT.isFixedLengthVector()) { 4442 ContainerVT = getContainerForFixedLengthVector(VecVT); 4443 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4444 } 4445 4446 MVT XLenVT = Subtarget.getXLenVT(); 4447 4448 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4449 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4450 // Even i64-element vectors on RV32 can be lowered without scalar 4451 // legalization if the most-significant 32 bits of the value are not affected 4452 // by the sign-extension of the lower 32 bits. 4453 // TODO: We could also catch sign extensions of a 32-bit value. 4454 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4455 const auto *CVal = cast<ConstantSDNode>(Val); 4456 if (isInt<32>(CVal->getSExtValue())) { 4457 IsLegalInsert = true; 4458 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4459 } 4460 } 4461 4462 SDValue Mask, VL; 4463 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4464 4465 SDValue ValInVec; 4466 4467 if (IsLegalInsert) { 4468 unsigned Opc = 4469 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4470 if (isNullConstant(Idx)) { 4471 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4472 if (!VecVT.isFixedLengthVector()) 4473 return Vec; 4474 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4475 } 4476 ValInVec = 4477 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4478 } else { 4479 // On RV32, i64-element vectors must be specially handled to place the 4480 // value at element 0, by using two vslide1up instructions in sequence on 4481 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4482 // this. 4483 SDValue One = DAG.getConstant(1, DL, XLenVT); 4484 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4485 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4486 MVT I32ContainerVT = 4487 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4488 SDValue I32Mask = 4489 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4490 // Limit the active VL to two. 4491 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4492 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4493 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4494 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4495 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4496 // First slide in the hi value, then the lo in underneath it. 4497 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4498 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4499 I32Mask, InsertI64VL); 4500 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4501 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4502 I32Mask, InsertI64VL); 4503 // Bitcast back to the right container type. 4504 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4505 } 4506 4507 // Now that the value is in a vector, slide it into position. 4508 SDValue InsertVL = 4509 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4510 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4511 ValInVec, Idx, Mask, InsertVL); 4512 if (!VecVT.isFixedLengthVector()) 4513 return Slideup; 4514 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4515 } 4516 4517 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4518 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4519 // types this is done using VMV_X_S to allow us to glean information about the 4520 // sign bits of the result. 4521 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4522 SelectionDAG &DAG) const { 4523 SDLoc DL(Op); 4524 SDValue Idx = Op.getOperand(1); 4525 SDValue Vec = Op.getOperand(0); 4526 EVT EltVT = Op.getValueType(); 4527 MVT VecVT = Vec.getSimpleValueType(); 4528 MVT XLenVT = Subtarget.getXLenVT(); 4529 4530 if (VecVT.getVectorElementType() == MVT::i1) { 4531 if (VecVT.isFixedLengthVector()) { 4532 unsigned NumElts = VecVT.getVectorNumElements(); 4533 if (NumElts >= 8) { 4534 MVT WideEltVT; 4535 unsigned WidenVecLen; 4536 SDValue ExtractElementIdx; 4537 SDValue ExtractBitIdx; 4538 unsigned MaxEEW = Subtarget.getELEN(); 4539 MVT LargestEltVT = MVT::getIntegerVT( 4540 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4541 if (NumElts <= LargestEltVT.getSizeInBits()) { 4542 assert(isPowerOf2_32(NumElts) && 4543 "the number of elements should be power of 2"); 4544 WideEltVT = MVT::getIntegerVT(NumElts); 4545 WidenVecLen = 1; 4546 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4547 ExtractBitIdx = Idx; 4548 } else { 4549 WideEltVT = LargestEltVT; 4550 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4551 // extract element index = index / element width 4552 ExtractElementIdx = DAG.getNode( 4553 ISD::SRL, DL, XLenVT, Idx, 4554 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4555 // mask bit index = index % element width 4556 ExtractBitIdx = DAG.getNode( 4557 ISD::AND, DL, XLenVT, Idx, 4558 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4559 } 4560 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4561 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4562 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4563 Vec, ExtractElementIdx); 4564 // Extract the bit from GPR. 4565 SDValue ShiftRight = 4566 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4567 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4568 DAG.getConstant(1, DL, XLenVT)); 4569 } 4570 } 4571 // Otherwise, promote to an i8 vector and extract from that. 4572 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4573 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4574 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4575 } 4576 4577 // If this is a fixed vector, we need to convert it to a scalable vector. 4578 MVT ContainerVT = VecVT; 4579 if (VecVT.isFixedLengthVector()) { 4580 ContainerVT = getContainerForFixedLengthVector(VecVT); 4581 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4582 } 4583 4584 // If the index is 0, the vector is already in the right position. 4585 if (!isNullConstant(Idx)) { 4586 // Use a VL of 1 to avoid processing more elements than we need. 4587 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4588 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 4589 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4590 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4591 } 4592 4593 if (!EltVT.isInteger()) { 4594 // Floating-point extracts are handled in TableGen. 4595 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4596 DAG.getConstant(0, DL, XLenVT)); 4597 } 4598 4599 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4600 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4601 } 4602 4603 // Some RVV intrinsics may claim that they want an integer operand to be 4604 // promoted or expanded. 4605 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG, 4606 const RISCVSubtarget &Subtarget) { 4607 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4608 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4609 "Unexpected opcode"); 4610 4611 if (!Subtarget.hasVInstructions()) 4612 return SDValue(); 4613 4614 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4615 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4616 SDLoc DL(Op); 4617 4618 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4619 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4620 if (!II || !II->hasScalarOperand()) 4621 return SDValue(); 4622 4623 unsigned SplatOp = II->ScalarOperand + 1 + HasChain; 4624 assert(SplatOp < Op.getNumOperands()); 4625 4626 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4627 SDValue &ScalarOp = Operands[SplatOp]; 4628 MVT OpVT = ScalarOp.getSimpleValueType(); 4629 MVT XLenVT = Subtarget.getXLenVT(); 4630 4631 // If this isn't a scalar, or its type is XLenVT we're done. 4632 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4633 return SDValue(); 4634 4635 // Simplest case is that the operand needs to be promoted to XLenVT. 4636 if (OpVT.bitsLT(XLenVT)) { 4637 // If the operand is a constant, sign extend to increase our chances 4638 // of being able to use a .vi instruction. ANY_EXTEND would become a 4639 // a zero extend and the simm5 check in isel would fail. 4640 // FIXME: Should we ignore the upper bits in isel instead? 4641 unsigned ExtOpc = 4642 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4643 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4644 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4645 } 4646 4647 // Use the previous operand to get the vXi64 VT. The result might be a mask 4648 // VT for compares. Using the previous operand assumes that the previous 4649 // operand will never have a smaller element size than a scalar operand and 4650 // that a widening operation never uses SEW=64. 4651 // NOTE: If this fails the below assert, we can probably just find the 4652 // element count from any operand or result and use it to construct the VT. 4653 assert(II->ScalarOperand > 0 && "Unexpected splat operand!"); 4654 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4655 4656 // The more complex case is when the scalar is larger than XLenVT. 4657 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4658 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4659 4660 // If this is a sign-extended 32-bit value, we can truncate it and rely on the 4661 // instruction to sign-extend since SEW>XLEN. 4662 if (DAG.ComputeNumSignBits(ScalarOp) > 32) { 4663 ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp); 4664 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4665 } 4666 4667 switch (IntNo) { 4668 case Intrinsic::riscv_vslide1up: 4669 case Intrinsic::riscv_vslide1down: 4670 case Intrinsic::riscv_vslide1up_mask: 4671 case Intrinsic::riscv_vslide1down_mask: { 4672 // We need to special case these when the scalar is larger than XLen. 4673 unsigned NumOps = Op.getNumOperands(); 4674 bool IsMasked = NumOps == 7; 4675 4676 // Convert the vector source to the equivalent nxvXi32 vector. 4677 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4678 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4679 4680 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4681 DAG.getConstant(0, DL, XLenVT)); 4682 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4683 DAG.getConstant(1, DL, XLenVT)); 4684 4685 // Double the VL since we halved SEW. 4686 SDValue AVL = getVLOperand(Op); 4687 SDValue I32VL; 4688 4689 // Optimize for constant AVL 4690 if (isa<ConstantSDNode>(AVL)) { 4691 unsigned EltSize = VT.getScalarSizeInBits(); 4692 unsigned MinSize = VT.getSizeInBits().getKnownMinValue(); 4693 4694 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 4695 unsigned MaxVLMAX = 4696 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 4697 4698 unsigned VectorBitsMin = Subtarget.getRealMinVLen(); 4699 unsigned MinVLMAX = 4700 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize); 4701 4702 uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue(); 4703 if (AVLInt <= MinVLMAX) { 4704 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT); 4705 } else if (AVLInt >= 2 * MaxVLMAX) { 4706 // Just set vl to VLMAX in this situation 4707 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT); 4708 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4709 unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits()); 4710 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4711 SDValue SETVLMAX = DAG.getTargetConstant( 4712 Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32); 4713 I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW, 4714 LMUL); 4715 } else { 4716 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl 4717 // is related to the hardware implementation. 4718 // So let the following code handle 4719 } 4720 } 4721 if (!I32VL) { 4722 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT); 4723 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4724 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits()); 4725 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4726 SDValue SETVL = 4727 DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32); 4728 // Using vsetvli instruction to get actually used length which related to 4729 // the hardware implementation 4730 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL, 4731 SEW, LMUL); 4732 I32VL = 4733 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4734 } 4735 4736 SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG); 4737 4738 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4739 // instructions. 4740 SDValue Passthru; 4741 if (IsMasked) 4742 Passthru = DAG.getUNDEF(I32VT); 4743 else 4744 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4745 4746 if (IntNo == Intrinsic::riscv_vslide1up || 4747 IntNo == Intrinsic::riscv_vslide1up_mask) { 4748 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4749 ScalarHi, I32Mask, I32VL); 4750 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4751 ScalarLo, I32Mask, I32VL); 4752 } else { 4753 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4754 ScalarLo, I32Mask, I32VL); 4755 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4756 ScalarHi, I32Mask, I32VL); 4757 } 4758 4759 // Convert back to nxvXi64. 4760 Vec = DAG.getBitcast(VT, Vec); 4761 4762 if (!IsMasked) 4763 return Vec; 4764 // Apply mask after the operation. 4765 SDValue Mask = Operands[NumOps - 3]; 4766 SDValue MaskedOff = Operands[1]; 4767 // Assume Policy operand is the last operand. 4768 uint64_t Policy = 4769 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4770 // We don't need to select maskedoff if it's undef. 4771 if (MaskedOff.isUndef()) 4772 return Vec; 4773 // TAMU 4774 if (Policy == RISCVII::TAIL_AGNOSTIC) 4775 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4776 AVL); 4777 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4778 // It's fine because vmerge does not care mask policy. 4779 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, 4780 AVL); 4781 } 4782 } 4783 4784 // We need to convert the scalar to a splat vector. 4785 SDValue VL = getVLOperand(Op); 4786 assert(VL.getValueType() == XLenVT); 4787 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4788 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4789 } 4790 4791 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4792 SelectionDAG &DAG) const { 4793 unsigned IntNo = Op.getConstantOperandVal(0); 4794 SDLoc DL(Op); 4795 MVT XLenVT = Subtarget.getXLenVT(); 4796 4797 switch (IntNo) { 4798 default: 4799 break; // Don't custom lower most intrinsics. 4800 case Intrinsic::thread_pointer: { 4801 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4802 return DAG.getRegister(RISCV::X4, PtrVT); 4803 } 4804 case Intrinsic::riscv_orc_b: 4805 case Intrinsic::riscv_brev8: { 4806 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4807 unsigned Opc = 4808 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4809 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4810 DAG.getConstant(7, DL, XLenVT)); 4811 } 4812 case Intrinsic::riscv_grev: 4813 case Intrinsic::riscv_gorc: { 4814 unsigned Opc = 4815 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4816 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4817 } 4818 case Intrinsic::riscv_zip: 4819 case Intrinsic::riscv_unzip: { 4820 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4821 // For i32 the immediate is 15. For i64 the immediate is 31. 4822 unsigned Opc = 4823 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4824 unsigned BitWidth = Op.getValueSizeInBits(); 4825 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4826 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4827 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4828 } 4829 case Intrinsic::riscv_shfl: 4830 case Intrinsic::riscv_unshfl: { 4831 unsigned Opc = 4832 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4833 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4834 } 4835 case Intrinsic::riscv_bcompress: 4836 case Intrinsic::riscv_bdecompress: { 4837 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4838 : RISCVISD::BDECOMPRESS; 4839 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4840 } 4841 case Intrinsic::riscv_bfp: 4842 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4843 Op.getOperand(2)); 4844 case Intrinsic::riscv_fsl: 4845 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4846 Op.getOperand(2), Op.getOperand(3)); 4847 case Intrinsic::riscv_fsr: 4848 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4849 Op.getOperand(2), Op.getOperand(3)); 4850 case Intrinsic::riscv_vmv_x_s: 4851 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4852 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4853 Op.getOperand(1)); 4854 case Intrinsic::riscv_vmv_v_x: 4855 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4856 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4857 Subtarget); 4858 case Intrinsic::riscv_vfmv_v_f: 4859 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4860 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4861 case Intrinsic::riscv_vmv_s_x: { 4862 SDValue Scalar = Op.getOperand(2); 4863 4864 if (Scalar.getValueType().bitsLE(XLenVT)) { 4865 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4866 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4867 Op.getOperand(1), Scalar, Op.getOperand(3)); 4868 } 4869 4870 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4871 4872 // This is an i64 value that lives in two scalar registers. We have to 4873 // insert this in a convoluted way. First we build vXi64 splat containing 4874 // the two values that we assemble using some bit math. Next we'll use 4875 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4876 // to merge element 0 from our splat into the source vector. 4877 // FIXME: This is probably not the best way to do this, but it is 4878 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4879 // point. 4880 // sw lo, (a0) 4881 // sw hi, 4(a0) 4882 // vlse vX, (a0) 4883 // 4884 // vid.v vVid 4885 // vmseq.vx mMask, vVid, 0 4886 // vmerge.vvm vDest, vSrc, vVal, mMask 4887 MVT VT = Op.getSimpleValueType(); 4888 SDValue Vec = Op.getOperand(1); 4889 SDValue VL = getVLOperand(Op); 4890 4891 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4892 if (Op.getOperand(1).isUndef()) 4893 return SplattedVal; 4894 SDValue SplattedIdx = 4895 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4896 DAG.getConstant(0, DL, MVT::i32), VL); 4897 4898 MVT MaskVT = getMaskTypeFor(VT); 4899 SDValue Mask = getAllOnesMask(VT, VL, DL, DAG); 4900 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4901 SDValue SelectCond = 4902 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4903 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4904 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4905 Vec, VL); 4906 } 4907 } 4908 4909 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4910 } 4911 4912 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4913 SelectionDAG &DAG) const { 4914 unsigned IntNo = Op.getConstantOperandVal(1); 4915 switch (IntNo) { 4916 default: 4917 break; 4918 case Intrinsic::riscv_masked_strided_load: { 4919 SDLoc DL(Op); 4920 MVT XLenVT = Subtarget.getXLenVT(); 4921 4922 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4923 // the selection of the masked intrinsics doesn't do this for us. 4924 SDValue Mask = Op.getOperand(5); 4925 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4926 4927 MVT VT = Op->getSimpleValueType(0); 4928 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4929 4930 SDValue PassThru = Op.getOperand(2); 4931 if (!IsUnmasked) { 4932 MVT MaskVT = getMaskTypeFor(ContainerVT); 4933 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4934 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4935 } 4936 4937 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4938 4939 SDValue IntID = DAG.getTargetConstant( 4940 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4941 XLenVT); 4942 4943 auto *Load = cast<MemIntrinsicSDNode>(Op); 4944 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4945 if (IsUnmasked) 4946 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4947 else 4948 Ops.push_back(PassThru); 4949 Ops.push_back(Op.getOperand(3)); // Ptr 4950 Ops.push_back(Op.getOperand(4)); // Stride 4951 if (!IsUnmasked) 4952 Ops.push_back(Mask); 4953 Ops.push_back(VL); 4954 if (!IsUnmasked) { 4955 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4956 Ops.push_back(Policy); 4957 } 4958 4959 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4960 SDValue Result = 4961 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4962 Load->getMemoryVT(), Load->getMemOperand()); 4963 SDValue Chain = Result.getValue(1); 4964 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4965 return DAG.getMergeValues({Result, Chain}, DL); 4966 } 4967 case Intrinsic::riscv_seg2_load: 4968 case Intrinsic::riscv_seg3_load: 4969 case Intrinsic::riscv_seg4_load: 4970 case Intrinsic::riscv_seg5_load: 4971 case Intrinsic::riscv_seg6_load: 4972 case Intrinsic::riscv_seg7_load: 4973 case Intrinsic::riscv_seg8_load: { 4974 SDLoc DL(Op); 4975 static const Intrinsic::ID VlsegInts[7] = { 4976 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 4977 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 4978 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 4979 Intrinsic::riscv_vlseg8}; 4980 unsigned NF = Op->getNumValues() - 1; 4981 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 4982 MVT XLenVT = Subtarget.getXLenVT(); 4983 MVT VT = Op->getSimpleValueType(0); 4984 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4985 4986 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4987 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 4988 auto *Load = cast<MemIntrinsicSDNode>(Op); 4989 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 4990 ContainerVTs.push_back(MVT::Other); 4991 SDVTList VTs = DAG.getVTList(ContainerVTs); 4992 SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID}; 4993 Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT)); 4994 Ops.push_back(Op.getOperand(2)); 4995 Ops.push_back(VL); 4996 SDValue Result = 4997 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4998 Load->getMemoryVT(), Load->getMemOperand()); 4999 SmallVector<SDValue, 9> Results; 5000 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 5001 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 5002 DAG, Subtarget)); 5003 Results.push_back(Result.getValue(NF)); 5004 return DAG.getMergeValues(Results, DL); 5005 } 5006 } 5007 5008 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 5009 } 5010 5011 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 5012 SelectionDAG &DAG) const { 5013 unsigned IntNo = Op.getConstantOperandVal(1); 5014 switch (IntNo) { 5015 default: 5016 break; 5017 case Intrinsic::riscv_masked_strided_store: { 5018 SDLoc DL(Op); 5019 MVT XLenVT = Subtarget.getXLenVT(); 5020 5021 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5022 // the selection of the masked intrinsics doesn't do this for us. 5023 SDValue Mask = Op.getOperand(5); 5024 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5025 5026 SDValue Val = Op.getOperand(2); 5027 MVT VT = Val.getSimpleValueType(); 5028 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5029 5030 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5031 if (!IsUnmasked) { 5032 MVT MaskVT = getMaskTypeFor(ContainerVT); 5033 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5034 } 5035 5036 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5037 5038 SDValue IntID = DAG.getTargetConstant( 5039 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 5040 XLenVT); 5041 5042 auto *Store = cast<MemIntrinsicSDNode>(Op); 5043 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 5044 Ops.push_back(Val); 5045 Ops.push_back(Op.getOperand(3)); // Ptr 5046 Ops.push_back(Op.getOperand(4)); // Stride 5047 if (!IsUnmasked) 5048 Ops.push_back(Mask); 5049 Ops.push_back(VL); 5050 5051 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 5052 Ops, Store->getMemoryVT(), 5053 Store->getMemOperand()); 5054 } 5055 } 5056 5057 return SDValue(); 5058 } 5059 5060 static MVT getLMUL1VT(MVT VT) { 5061 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 5062 "Unexpected vector MVT"); 5063 return MVT::getScalableVectorVT( 5064 VT.getVectorElementType(), 5065 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 5066 } 5067 5068 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 5069 switch (ISDOpcode) { 5070 default: 5071 llvm_unreachable("Unhandled reduction"); 5072 case ISD::VECREDUCE_ADD: 5073 return RISCVISD::VECREDUCE_ADD_VL; 5074 case ISD::VECREDUCE_UMAX: 5075 return RISCVISD::VECREDUCE_UMAX_VL; 5076 case ISD::VECREDUCE_SMAX: 5077 return RISCVISD::VECREDUCE_SMAX_VL; 5078 case ISD::VECREDUCE_UMIN: 5079 return RISCVISD::VECREDUCE_UMIN_VL; 5080 case ISD::VECREDUCE_SMIN: 5081 return RISCVISD::VECREDUCE_SMIN_VL; 5082 case ISD::VECREDUCE_AND: 5083 return RISCVISD::VECREDUCE_AND_VL; 5084 case ISD::VECREDUCE_OR: 5085 return RISCVISD::VECREDUCE_OR_VL; 5086 case ISD::VECREDUCE_XOR: 5087 return RISCVISD::VECREDUCE_XOR_VL; 5088 } 5089 } 5090 5091 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 5092 SelectionDAG &DAG, 5093 bool IsVP) const { 5094 SDLoc DL(Op); 5095 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 5096 MVT VecVT = Vec.getSimpleValueType(); 5097 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 5098 Op.getOpcode() == ISD::VECREDUCE_OR || 5099 Op.getOpcode() == ISD::VECREDUCE_XOR || 5100 Op.getOpcode() == ISD::VP_REDUCE_AND || 5101 Op.getOpcode() == ISD::VP_REDUCE_OR || 5102 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5103 "Unexpected reduction lowering"); 5104 5105 MVT XLenVT = Subtarget.getXLenVT(); 5106 assert(Op.getValueType() == XLenVT && 5107 "Expected reduction output to be legalized to XLenVT"); 5108 5109 MVT ContainerVT = VecVT; 5110 if (VecVT.isFixedLengthVector()) { 5111 ContainerVT = getContainerForFixedLengthVector(VecVT); 5112 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5113 } 5114 5115 SDValue Mask, VL; 5116 if (IsVP) { 5117 Mask = Op.getOperand(2); 5118 VL = Op.getOperand(3); 5119 } else { 5120 std::tie(Mask, VL) = 5121 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5122 } 5123 5124 unsigned BaseOpc; 5125 ISD::CondCode CC; 5126 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5127 5128 switch (Op.getOpcode()) { 5129 default: 5130 llvm_unreachable("Unhandled reduction"); 5131 case ISD::VECREDUCE_AND: 5132 case ISD::VP_REDUCE_AND: { 5133 // vcpop ~x == 0 5134 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5135 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5136 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5137 CC = ISD::SETEQ; 5138 BaseOpc = ISD::AND; 5139 break; 5140 } 5141 case ISD::VECREDUCE_OR: 5142 case ISD::VP_REDUCE_OR: 5143 // vcpop x != 0 5144 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5145 CC = ISD::SETNE; 5146 BaseOpc = ISD::OR; 5147 break; 5148 case ISD::VECREDUCE_XOR: 5149 case ISD::VP_REDUCE_XOR: { 5150 // ((vcpop x) & 1) != 0 5151 SDValue One = DAG.getConstant(1, DL, XLenVT); 5152 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5153 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5154 CC = ISD::SETNE; 5155 BaseOpc = ISD::XOR; 5156 break; 5157 } 5158 } 5159 5160 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5161 5162 if (!IsVP) 5163 return SetCC; 5164 5165 // Now include the start value in the operation. 5166 // Note that we must return the start value when no elements are operated 5167 // upon. The vcpop instructions we've emitted in each case above will return 5168 // 0 for an inactive vector, and so we've already received the neutral value: 5169 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5170 // can simply include the start value. 5171 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5172 } 5173 5174 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5175 SelectionDAG &DAG) const { 5176 SDLoc DL(Op); 5177 SDValue Vec = Op.getOperand(0); 5178 EVT VecEVT = Vec.getValueType(); 5179 5180 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5181 5182 // Due to ordering in legalize types we may have a vector type that needs to 5183 // be split. Do that manually so we can get down to a legal type. 5184 while (getTypeAction(*DAG.getContext(), VecEVT) == 5185 TargetLowering::TypeSplitVector) { 5186 SDValue Lo, Hi; 5187 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5188 VecEVT = Lo.getValueType(); 5189 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5190 } 5191 5192 // TODO: The type may need to be widened rather than split. Or widened before 5193 // it can be split. 5194 if (!isTypeLegal(VecEVT)) 5195 return SDValue(); 5196 5197 MVT VecVT = VecEVT.getSimpleVT(); 5198 MVT VecEltVT = VecVT.getVectorElementType(); 5199 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5200 5201 MVT ContainerVT = VecVT; 5202 if (VecVT.isFixedLengthVector()) { 5203 ContainerVT = getContainerForFixedLengthVector(VecVT); 5204 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5205 } 5206 5207 MVT M1VT = getLMUL1VT(ContainerVT); 5208 MVT XLenVT = Subtarget.getXLenVT(); 5209 5210 SDValue Mask, VL; 5211 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5212 5213 SDValue NeutralElem = 5214 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5215 SDValue IdentitySplat = 5216 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5217 M1VT, DL, DAG, Subtarget); 5218 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5219 IdentitySplat, Mask, VL); 5220 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5221 DAG.getConstant(0, DL, XLenVT)); 5222 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5223 } 5224 5225 // Given a reduction op, this function returns the matching reduction opcode, 5226 // the vector SDValue and the scalar SDValue required to lower this to a 5227 // RISCVISD node. 5228 static std::tuple<unsigned, SDValue, SDValue> 5229 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5230 SDLoc DL(Op); 5231 auto Flags = Op->getFlags(); 5232 unsigned Opcode = Op.getOpcode(); 5233 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5234 switch (Opcode) { 5235 default: 5236 llvm_unreachable("Unhandled reduction"); 5237 case ISD::VECREDUCE_FADD: { 5238 // Use positive zero if we can. It is cheaper to materialize. 5239 SDValue Zero = 5240 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5241 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5242 } 5243 case ISD::VECREDUCE_SEQ_FADD: 5244 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5245 Op.getOperand(0)); 5246 case ISD::VECREDUCE_FMIN: 5247 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5248 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5249 case ISD::VECREDUCE_FMAX: 5250 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5251 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5252 } 5253 } 5254 5255 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5256 SelectionDAG &DAG) const { 5257 SDLoc DL(Op); 5258 MVT VecEltVT = Op.getSimpleValueType(); 5259 5260 unsigned RVVOpcode; 5261 SDValue VectorVal, ScalarVal; 5262 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5263 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5264 MVT VecVT = VectorVal.getSimpleValueType(); 5265 5266 MVT ContainerVT = VecVT; 5267 if (VecVT.isFixedLengthVector()) { 5268 ContainerVT = getContainerForFixedLengthVector(VecVT); 5269 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5270 } 5271 5272 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5273 MVT XLenVT = Subtarget.getXLenVT(); 5274 5275 SDValue Mask, VL; 5276 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5277 5278 SDValue ScalarSplat = 5279 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5280 M1VT, DL, DAG, Subtarget); 5281 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5282 VectorVal, ScalarSplat, Mask, VL); 5283 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5284 DAG.getConstant(0, DL, XLenVT)); 5285 } 5286 5287 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5288 switch (ISDOpcode) { 5289 default: 5290 llvm_unreachable("Unhandled reduction"); 5291 case ISD::VP_REDUCE_ADD: 5292 return RISCVISD::VECREDUCE_ADD_VL; 5293 case ISD::VP_REDUCE_UMAX: 5294 return RISCVISD::VECREDUCE_UMAX_VL; 5295 case ISD::VP_REDUCE_SMAX: 5296 return RISCVISD::VECREDUCE_SMAX_VL; 5297 case ISD::VP_REDUCE_UMIN: 5298 return RISCVISD::VECREDUCE_UMIN_VL; 5299 case ISD::VP_REDUCE_SMIN: 5300 return RISCVISD::VECREDUCE_SMIN_VL; 5301 case ISD::VP_REDUCE_AND: 5302 return RISCVISD::VECREDUCE_AND_VL; 5303 case ISD::VP_REDUCE_OR: 5304 return RISCVISD::VECREDUCE_OR_VL; 5305 case ISD::VP_REDUCE_XOR: 5306 return RISCVISD::VECREDUCE_XOR_VL; 5307 case ISD::VP_REDUCE_FADD: 5308 return RISCVISD::VECREDUCE_FADD_VL; 5309 case ISD::VP_REDUCE_SEQ_FADD: 5310 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5311 case ISD::VP_REDUCE_FMAX: 5312 return RISCVISD::VECREDUCE_FMAX_VL; 5313 case ISD::VP_REDUCE_FMIN: 5314 return RISCVISD::VECREDUCE_FMIN_VL; 5315 } 5316 } 5317 5318 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5319 SelectionDAG &DAG) const { 5320 SDLoc DL(Op); 5321 SDValue Vec = Op.getOperand(1); 5322 EVT VecEVT = Vec.getValueType(); 5323 5324 // TODO: The type may need to be widened rather than split. Or widened before 5325 // it can be split. 5326 if (!isTypeLegal(VecEVT)) 5327 return SDValue(); 5328 5329 MVT VecVT = VecEVT.getSimpleVT(); 5330 MVT VecEltVT = VecVT.getVectorElementType(); 5331 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5332 5333 MVT ContainerVT = VecVT; 5334 if (VecVT.isFixedLengthVector()) { 5335 ContainerVT = getContainerForFixedLengthVector(VecVT); 5336 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5337 } 5338 5339 SDValue VL = Op.getOperand(3); 5340 SDValue Mask = Op.getOperand(2); 5341 5342 MVT M1VT = getLMUL1VT(ContainerVT); 5343 MVT XLenVT = Subtarget.getXLenVT(); 5344 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5345 5346 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5347 DAG.getConstant(1, DL, XLenVT), M1VT, 5348 DL, DAG, Subtarget); 5349 SDValue Reduction = 5350 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5351 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5352 DAG.getConstant(0, DL, XLenVT)); 5353 if (!VecVT.isInteger()) 5354 return Elt0; 5355 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5356 } 5357 5358 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5359 SelectionDAG &DAG) const { 5360 SDValue Vec = Op.getOperand(0); 5361 SDValue SubVec = Op.getOperand(1); 5362 MVT VecVT = Vec.getSimpleValueType(); 5363 MVT SubVecVT = SubVec.getSimpleValueType(); 5364 5365 SDLoc DL(Op); 5366 MVT XLenVT = Subtarget.getXLenVT(); 5367 unsigned OrigIdx = Op.getConstantOperandVal(2); 5368 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5369 5370 // We don't have the ability to slide mask vectors up indexed by their i1 5371 // elements; the smallest we can do is i8. Often we are able to bitcast to 5372 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5373 // into a scalable one, we might not necessarily have enough scalable 5374 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5375 if (SubVecVT.getVectorElementType() == MVT::i1 && 5376 (OrigIdx != 0 || !Vec.isUndef())) { 5377 if (VecVT.getVectorMinNumElements() >= 8 && 5378 SubVecVT.getVectorMinNumElements() >= 8) { 5379 assert(OrigIdx % 8 == 0 && "Invalid index"); 5380 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5381 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5382 "Unexpected mask vector lowering"); 5383 OrigIdx /= 8; 5384 SubVecVT = 5385 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5386 SubVecVT.isScalableVector()); 5387 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5388 VecVT.isScalableVector()); 5389 Vec = DAG.getBitcast(VecVT, Vec); 5390 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5391 } else { 5392 // We can't slide this mask vector up indexed by its i1 elements. 5393 // This poses a problem when we wish to insert a scalable vector which 5394 // can't be re-expressed as a larger type. Just choose the slow path and 5395 // extend to a larger type, then truncate back down. 5396 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5397 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5398 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5399 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5400 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5401 Op.getOperand(2)); 5402 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5403 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5404 } 5405 } 5406 5407 // If the subvector vector is a fixed-length type, we cannot use subregister 5408 // manipulation to simplify the codegen; we don't know which register of a 5409 // LMUL group contains the specific subvector as we only know the minimum 5410 // register size. Therefore we must slide the vector group up the full 5411 // amount. 5412 if (SubVecVT.isFixedLengthVector()) { 5413 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5414 return Op; 5415 MVT ContainerVT = VecVT; 5416 if (VecVT.isFixedLengthVector()) { 5417 ContainerVT = getContainerForFixedLengthVector(VecVT); 5418 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5419 } 5420 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5421 DAG.getUNDEF(ContainerVT), SubVec, 5422 DAG.getConstant(0, DL, XLenVT)); 5423 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5424 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5425 return DAG.getBitcast(Op.getValueType(), SubVec); 5426 } 5427 SDValue Mask = 5428 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5429 // Set the vector length to only the number of elements we care about. Note 5430 // that for slideup this includes the offset. 5431 SDValue VL = 5432 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5433 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5434 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5435 SubVec, SlideupAmt, Mask, VL); 5436 if (VecVT.isFixedLengthVector()) 5437 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5438 return DAG.getBitcast(Op.getValueType(), Slideup); 5439 } 5440 5441 unsigned SubRegIdx, RemIdx; 5442 std::tie(SubRegIdx, RemIdx) = 5443 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5444 VecVT, SubVecVT, OrigIdx, TRI); 5445 5446 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5447 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5448 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5449 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5450 5451 // 1. If the Idx has been completely eliminated and this subvector's size is 5452 // a vector register or a multiple thereof, or the surrounding elements are 5453 // undef, then this is a subvector insert which naturally aligns to a vector 5454 // register. These can easily be handled using subregister manipulation. 5455 // 2. If the subvector is smaller than a vector register, then the insertion 5456 // must preserve the undisturbed elements of the register. We do this by 5457 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5458 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5459 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5460 // LMUL=1 type back into the larger vector (resolving to another subregister 5461 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5462 // to avoid allocating a large register group to hold our subvector. 5463 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5464 return Op; 5465 5466 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5467 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5468 // (in our case undisturbed). This means we can set up a subvector insertion 5469 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5470 // size of the subvector. 5471 MVT InterSubVT = VecVT; 5472 SDValue AlignedExtract = Vec; 5473 unsigned AlignedIdx = OrigIdx - RemIdx; 5474 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5475 InterSubVT = getLMUL1VT(VecVT); 5476 // Extract a subvector equal to the nearest full vector register type. This 5477 // should resolve to a EXTRACT_SUBREG instruction. 5478 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5479 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5480 } 5481 5482 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5483 // For scalable vectors this must be further multiplied by vscale. 5484 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5485 5486 SDValue Mask, VL; 5487 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5488 5489 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5490 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5491 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5492 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5493 5494 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5495 DAG.getUNDEF(InterSubVT), SubVec, 5496 DAG.getConstant(0, DL, XLenVT)); 5497 5498 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5499 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5500 5501 // If required, insert this subvector back into the correct vector register. 5502 // This should resolve to an INSERT_SUBREG instruction. 5503 if (VecVT.bitsGT(InterSubVT)) 5504 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5505 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5506 5507 // We might have bitcast from a mask type: cast back to the original type if 5508 // required. 5509 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5510 } 5511 5512 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5513 SelectionDAG &DAG) const { 5514 SDValue Vec = Op.getOperand(0); 5515 MVT SubVecVT = Op.getSimpleValueType(); 5516 MVT VecVT = Vec.getSimpleValueType(); 5517 5518 SDLoc DL(Op); 5519 MVT XLenVT = Subtarget.getXLenVT(); 5520 unsigned OrigIdx = Op.getConstantOperandVal(1); 5521 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5522 5523 // We don't have the ability to slide mask vectors down indexed by their i1 5524 // elements; the smallest we can do is i8. Often we are able to bitcast to 5525 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5526 // from a scalable one, we might not necessarily have enough scalable 5527 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5528 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5529 if (VecVT.getVectorMinNumElements() >= 8 && 5530 SubVecVT.getVectorMinNumElements() >= 8) { 5531 assert(OrigIdx % 8 == 0 && "Invalid index"); 5532 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5533 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5534 "Unexpected mask vector lowering"); 5535 OrigIdx /= 8; 5536 SubVecVT = 5537 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5538 SubVecVT.isScalableVector()); 5539 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5540 VecVT.isScalableVector()); 5541 Vec = DAG.getBitcast(VecVT, Vec); 5542 } else { 5543 // We can't slide this mask vector down, indexed by its i1 elements. 5544 // This poses a problem when we wish to extract a scalable vector which 5545 // can't be re-expressed as a larger type. Just choose the slow path and 5546 // extend to a larger type, then truncate back down. 5547 // TODO: We could probably improve this when extracting certain fixed 5548 // from fixed, where we can extract as i8 and shift the correct element 5549 // right to reach the desired subvector? 5550 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5551 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5552 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5553 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5554 Op.getOperand(1)); 5555 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5556 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5557 } 5558 } 5559 5560 // If the subvector vector is a fixed-length type, we cannot use subregister 5561 // manipulation to simplify the codegen; we don't know which register of a 5562 // LMUL group contains the specific subvector as we only know the minimum 5563 // register size. Therefore we must slide the vector group down the full 5564 // amount. 5565 if (SubVecVT.isFixedLengthVector()) { 5566 // With an index of 0 this is a cast-like subvector, which can be performed 5567 // with subregister operations. 5568 if (OrigIdx == 0) 5569 return Op; 5570 MVT ContainerVT = VecVT; 5571 if (VecVT.isFixedLengthVector()) { 5572 ContainerVT = getContainerForFixedLengthVector(VecVT); 5573 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5574 } 5575 SDValue Mask = 5576 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5577 // Set the vector length to only the number of elements we care about. This 5578 // avoids sliding down elements we're going to discard straight away. 5579 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5580 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5581 SDValue Slidedown = 5582 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5583 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5584 // Now we can use a cast-like subvector extract to get the result. 5585 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5586 DAG.getConstant(0, DL, XLenVT)); 5587 return DAG.getBitcast(Op.getValueType(), Slidedown); 5588 } 5589 5590 unsigned SubRegIdx, RemIdx; 5591 std::tie(SubRegIdx, RemIdx) = 5592 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5593 VecVT, SubVecVT, OrigIdx, TRI); 5594 5595 // If the Idx has been completely eliminated then this is a subvector extract 5596 // which naturally aligns to a vector register. These can easily be handled 5597 // using subregister manipulation. 5598 if (RemIdx == 0) 5599 return Op; 5600 5601 // Else we must shift our vector register directly to extract the subvector. 5602 // Do this using VSLIDEDOWN. 5603 5604 // If the vector type is an LMUL-group type, extract a subvector equal to the 5605 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5606 // instruction. 5607 MVT InterSubVT = VecVT; 5608 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5609 InterSubVT = getLMUL1VT(VecVT); 5610 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5611 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5612 } 5613 5614 // Slide this vector register down by the desired number of elements in order 5615 // to place the desired subvector starting at element 0. 5616 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5617 // For scalable vectors this must be further multiplied by vscale. 5618 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5619 5620 SDValue Mask, VL; 5621 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5622 SDValue Slidedown = 5623 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5624 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5625 5626 // Now the vector is in the right position, extract our final subvector. This 5627 // should resolve to a COPY. 5628 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5629 DAG.getConstant(0, DL, XLenVT)); 5630 5631 // We might have bitcast from a mask type: cast back to the original type if 5632 // required. 5633 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5634 } 5635 5636 // Lower step_vector to the vid instruction. Any non-identity step value must 5637 // be accounted for my manual expansion. 5638 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5639 SelectionDAG &DAG) const { 5640 SDLoc DL(Op); 5641 MVT VT = Op.getSimpleValueType(); 5642 MVT XLenVT = Subtarget.getXLenVT(); 5643 SDValue Mask, VL; 5644 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5645 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5646 uint64_t StepValImm = Op.getConstantOperandVal(0); 5647 if (StepValImm != 1) { 5648 if (isPowerOf2_64(StepValImm)) { 5649 SDValue StepVal = 5650 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5651 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5652 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5653 } else { 5654 SDValue StepVal = lowerScalarSplat( 5655 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5656 VL, VT, DL, DAG, Subtarget); 5657 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5658 } 5659 } 5660 return StepVec; 5661 } 5662 5663 // Implement vector_reverse using vrgather.vv with indices determined by 5664 // subtracting the id of each element from (VLMAX-1). This will convert 5665 // the indices like so: 5666 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5667 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5668 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5669 SelectionDAG &DAG) const { 5670 SDLoc DL(Op); 5671 MVT VecVT = Op.getSimpleValueType(); 5672 if (VecVT.getVectorElementType() == MVT::i1) { 5673 MVT WidenVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 5674 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenVT, Op.getOperand(0)); 5675 SDValue Op2 = DAG.getNode(ISD::VECTOR_REVERSE, DL, WidenVT, Op1); 5676 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Op2); 5677 } 5678 unsigned EltSize = VecVT.getScalarSizeInBits(); 5679 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5680 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 5681 unsigned MaxVLMAX = 5682 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 5683 5684 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5685 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5686 5687 // If this is SEW=8 and VLMAX is potentially more than 256, we need 5688 // to use vrgatherei16.vv. 5689 // TODO: It's also possible to use vrgatherei16.vv for other types to 5690 // decrease register width for the index calculation. 5691 if (MaxVLMAX > 256 && EltSize == 8) { 5692 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5693 // Reverse each half, then reassemble them in reverse order. 5694 // NOTE: It's also possible that after splitting that VLMAX no longer 5695 // requires vrgatherei16.vv. 5696 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5697 SDValue Lo, Hi; 5698 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5699 EVT LoVT, HiVT; 5700 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5701 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5702 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5703 // Reassemble the low and high pieces reversed. 5704 // FIXME: This is a CONCAT_VECTORS. 5705 SDValue Res = 5706 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5707 DAG.getIntPtrConstant(0, DL)); 5708 return DAG.getNode( 5709 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5710 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5711 } 5712 5713 // Just promote the int type to i16 which will double the LMUL. 5714 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5715 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5716 } 5717 5718 MVT XLenVT = Subtarget.getXLenVT(); 5719 SDValue Mask, VL; 5720 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5721 5722 // Calculate VLMAX-1 for the desired SEW. 5723 unsigned MinElts = VecVT.getVectorMinNumElements(); 5724 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5725 DAG.getConstant(MinElts, DL, XLenVT)); 5726 SDValue VLMinus1 = 5727 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5728 5729 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5730 bool IsRV32E64 = 5731 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5732 SDValue SplatVL; 5733 if (!IsRV32E64) 5734 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5735 else 5736 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5737 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5738 5739 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5740 SDValue Indices = 5741 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5742 5743 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, 5744 DAG.getUNDEF(VecVT), VL); 5745 } 5746 5747 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5748 SelectionDAG &DAG) const { 5749 SDLoc DL(Op); 5750 SDValue V1 = Op.getOperand(0); 5751 SDValue V2 = Op.getOperand(1); 5752 MVT XLenVT = Subtarget.getXLenVT(); 5753 MVT VecVT = Op.getSimpleValueType(); 5754 5755 unsigned MinElts = VecVT.getVectorMinNumElements(); 5756 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5757 DAG.getConstant(MinElts, DL, XLenVT)); 5758 5759 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5760 SDValue DownOffset, UpOffset; 5761 if (ImmValue >= 0) { 5762 // The operand is a TargetConstant, we need to rebuild it as a regular 5763 // constant. 5764 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5765 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5766 } else { 5767 // The operand is a TargetConstant, we need to rebuild it as a regular 5768 // constant rather than negating the original operand. 5769 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5770 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5771 } 5772 5773 SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG); 5774 5775 SDValue SlideDown = 5776 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5777 DownOffset, TrueMask, UpOffset); 5778 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5779 TrueMask, DAG.getRegister(RISCV::X0, XLenVT)); 5780 } 5781 5782 SDValue 5783 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5784 SelectionDAG &DAG) const { 5785 SDLoc DL(Op); 5786 auto *Load = cast<LoadSDNode>(Op); 5787 5788 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5789 Load->getMemoryVT(), 5790 *Load->getMemOperand()) && 5791 "Expecting a correctly-aligned load"); 5792 5793 MVT VT = Op.getSimpleValueType(); 5794 MVT XLenVT = Subtarget.getXLenVT(); 5795 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5796 5797 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5798 5799 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5800 SDValue IntID = DAG.getTargetConstant( 5801 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 5802 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 5803 if (!IsMaskOp) 5804 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5805 Ops.push_back(Load->getBasePtr()); 5806 Ops.push_back(VL); 5807 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5808 SDValue NewLoad = 5809 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5810 Load->getMemoryVT(), Load->getMemOperand()); 5811 5812 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5813 return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL); 5814 } 5815 5816 SDValue 5817 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5818 SelectionDAG &DAG) const { 5819 SDLoc DL(Op); 5820 auto *Store = cast<StoreSDNode>(Op); 5821 5822 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5823 Store->getMemoryVT(), 5824 *Store->getMemOperand()) && 5825 "Expecting a correctly-aligned store"); 5826 5827 SDValue StoreVal = Store->getValue(); 5828 MVT VT = StoreVal.getSimpleValueType(); 5829 MVT XLenVT = Subtarget.getXLenVT(); 5830 5831 // If the size less than a byte, we need to pad with zeros to make a byte. 5832 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5833 VT = MVT::v8i1; 5834 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5835 DAG.getConstant(0, DL, VT), StoreVal, 5836 DAG.getIntPtrConstant(0, DL)); 5837 } 5838 5839 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5840 5841 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5842 5843 SDValue NewValue = 5844 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5845 5846 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5847 SDValue IntID = DAG.getTargetConstant( 5848 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 5849 return DAG.getMemIntrinsicNode( 5850 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 5851 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 5852 Store->getMemoryVT(), Store->getMemOperand()); 5853 } 5854 5855 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5856 SelectionDAG &DAG) const { 5857 SDLoc DL(Op); 5858 MVT VT = Op.getSimpleValueType(); 5859 5860 const auto *MemSD = cast<MemSDNode>(Op); 5861 EVT MemVT = MemSD->getMemoryVT(); 5862 MachineMemOperand *MMO = MemSD->getMemOperand(); 5863 SDValue Chain = MemSD->getChain(); 5864 SDValue BasePtr = MemSD->getBasePtr(); 5865 5866 SDValue Mask, PassThru, VL; 5867 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5868 Mask = VPLoad->getMask(); 5869 PassThru = DAG.getUNDEF(VT); 5870 VL = VPLoad->getVectorLength(); 5871 } else { 5872 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5873 Mask = MLoad->getMask(); 5874 PassThru = MLoad->getPassThru(); 5875 } 5876 5877 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5878 5879 MVT XLenVT = Subtarget.getXLenVT(); 5880 5881 MVT ContainerVT = VT; 5882 if (VT.isFixedLengthVector()) { 5883 ContainerVT = getContainerForFixedLengthVector(VT); 5884 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5885 if (!IsUnmasked) { 5886 MVT MaskVT = getMaskTypeFor(ContainerVT); 5887 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5888 } 5889 } 5890 5891 if (!VL) 5892 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5893 5894 unsigned IntID = 5895 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5896 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5897 if (IsUnmasked) 5898 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5899 else 5900 Ops.push_back(PassThru); 5901 Ops.push_back(BasePtr); 5902 if (!IsUnmasked) 5903 Ops.push_back(Mask); 5904 Ops.push_back(VL); 5905 if (!IsUnmasked) 5906 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5907 5908 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5909 5910 SDValue Result = 5911 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5912 Chain = Result.getValue(1); 5913 5914 if (VT.isFixedLengthVector()) 5915 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5916 5917 return DAG.getMergeValues({Result, Chain}, DL); 5918 } 5919 5920 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5921 SelectionDAG &DAG) const { 5922 SDLoc DL(Op); 5923 5924 const auto *MemSD = cast<MemSDNode>(Op); 5925 EVT MemVT = MemSD->getMemoryVT(); 5926 MachineMemOperand *MMO = MemSD->getMemOperand(); 5927 SDValue Chain = MemSD->getChain(); 5928 SDValue BasePtr = MemSD->getBasePtr(); 5929 SDValue Val, Mask, VL; 5930 5931 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5932 Val = VPStore->getValue(); 5933 Mask = VPStore->getMask(); 5934 VL = VPStore->getVectorLength(); 5935 } else { 5936 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5937 Val = MStore->getValue(); 5938 Mask = MStore->getMask(); 5939 } 5940 5941 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5942 5943 MVT VT = Val.getSimpleValueType(); 5944 MVT XLenVT = Subtarget.getXLenVT(); 5945 5946 MVT ContainerVT = VT; 5947 if (VT.isFixedLengthVector()) { 5948 ContainerVT = getContainerForFixedLengthVector(VT); 5949 5950 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5951 if (!IsUnmasked) { 5952 MVT MaskVT = getMaskTypeFor(ContainerVT); 5953 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5954 } 5955 } 5956 5957 if (!VL) 5958 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5959 5960 unsigned IntID = 5961 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5962 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5963 Ops.push_back(Val); 5964 Ops.push_back(BasePtr); 5965 if (!IsUnmasked) 5966 Ops.push_back(Mask); 5967 Ops.push_back(VL); 5968 5969 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5970 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5971 } 5972 5973 SDValue 5974 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5975 SelectionDAG &DAG) const { 5976 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5977 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5978 5979 MVT VT = Op.getSimpleValueType(); 5980 5981 SDValue Op1 = 5982 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5983 SDValue Op2 = 5984 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5985 5986 SDLoc DL(Op); 5987 SDValue VL = 5988 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5989 5990 MVT MaskVT = getMaskTypeFor(ContainerVT); 5991 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 5992 5993 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5994 Op.getOperand(2), Mask, VL); 5995 5996 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5997 } 5998 5999 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 6000 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 6001 MVT VT = Op.getSimpleValueType(); 6002 6003 if (VT.getVectorElementType() == MVT::i1) 6004 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 6005 6006 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 6007 } 6008 6009 SDValue 6010 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 6011 SelectionDAG &DAG) const { 6012 unsigned Opc; 6013 switch (Op.getOpcode()) { 6014 default: llvm_unreachable("Unexpected opcode!"); 6015 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 6016 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 6017 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 6018 } 6019 6020 return lowerToScalableOp(Op, DAG, Opc); 6021 } 6022 6023 // Lower vector ABS to smax(X, sub(0, X)). 6024 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 6025 SDLoc DL(Op); 6026 MVT VT = Op.getSimpleValueType(); 6027 SDValue X = Op.getOperand(0); 6028 6029 assert(VT.isFixedLengthVector() && "Unexpected type"); 6030 6031 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6032 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 6033 6034 SDValue Mask, VL; 6035 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6036 6037 SDValue SplatZero = DAG.getNode( 6038 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 6039 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 6040 SDValue NegX = 6041 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 6042 SDValue Max = 6043 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 6044 6045 return convertFromScalableVector(VT, Max, DAG, Subtarget); 6046 } 6047 6048 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 6049 SDValue Op, SelectionDAG &DAG) const { 6050 SDLoc DL(Op); 6051 MVT VT = Op.getSimpleValueType(); 6052 SDValue Mag = Op.getOperand(0); 6053 SDValue Sign = Op.getOperand(1); 6054 assert(Mag.getValueType() == Sign.getValueType() && 6055 "Can only handle COPYSIGN with matching types."); 6056 6057 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6058 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 6059 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 6060 6061 SDValue Mask, VL; 6062 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6063 6064 SDValue CopySign = 6065 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 6066 6067 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 6068 } 6069 6070 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 6071 SDValue Op, SelectionDAG &DAG) const { 6072 MVT VT = Op.getSimpleValueType(); 6073 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6074 6075 MVT I1ContainerVT = 6076 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6077 6078 SDValue CC = 6079 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 6080 SDValue Op1 = 6081 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 6082 SDValue Op2 = 6083 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 6084 6085 SDLoc DL(Op); 6086 SDValue Mask, VL; 6087 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6088 6089 SDValue Select = 6090 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 6091 6092 return convertFromScalableVector(VT, Select, DAG, Subtarget); 6093 } 6094 6095 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 6096 unsigned NewOpc, 6097 bool HasMask) const { 6098 MVT VT = Op.getSimpleValueType(); 6099 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6100 6101 // Create list of operands by converting existing ones to scalable types. 6102 SmallVector<SDValue, 6> Ops; 6103 for (const SDValue &V : Op->op_values()) { 6104 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6105 6106 // Pass through non-vector operands. 6107 if (!V.getValueType().isVector()) { 6108 Ops.push_back(V); 6109 continue; 6110 } 6111 6112 // "cast" fixed length vector to a scalable vector. 6113 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6114 "Only fixed length vectors are supported!"); 6115 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6116 } 6117 6118 SDLoc DL(Op); 6119 SDValue Mask, VL; 6120 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6121 if (HasMask) 6122 Ops.push_back(Mask); 6123 Ops.push_back(VL); 6124 6125 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6126 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6127 } 6128 6129 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6130 // * Operands of each node are assumed to be in the same order. 6131 // * The EVL operand is promoted from i32 to i64 on RV64. 6132 // * Fixed-length vectors are converted to their scalable-vector container 6133 // types. 6134 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6135 unsigned RISCVISDOpc) const { 6136 SDLoc DL(Op); 6137 MVT VT = Op.getSimpleValueType(); 6138 SmallVector<SDValue, 4> Ops; 6139 6140 for (const auto &OpIdx : enumerate(Op->ops())) { 6141 SDValue V = OpIdx.value(); 6142 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6143 // Pass through operands which aren't fixed-length vectors. 6144 if (!V.getValueType().isFixedLengthVector()) { 6145 Ops.push_back(V); 6146 continue; 6147 } 6148 // "cast" fixed length vector to a scalable vector. 6149 MVT OpVT = V.getSimpleValueType(); 6150 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6151 assert(useRVVForFixedLengthVectorVT(OpVT) && 6152 "Only fixed length vectors are supported!"); 6153 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6154 } 6155 6156 if (!VT.isFixedLengthVector()) 6157 return DAG.getNode(RISCVISDOpc, DL, VT, Ops, Op->getFlags()); 6158 6159 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6160 6161 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops, Op->getFlags()); 6162 6163 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6164 } 6165 6166 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op, 6167 SelectionDAG &DAG) const { 6168 SDLoc DL(Op); 6169 MVT VT = Op.getSimpleValueType(); 6170 6171 SDValue Src = Op.getOperand(0); 6172 // NOTE: Mask is dropped. 6173 SDValue VL = Op.getOperand(2); 6174 6175 MVT ContainerVT = VT; 6176 if (VT.isFixedLengthVector()) { 6177 ContainerVT = getContainerForFixedLengthVector(VT); 6178 MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6179 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6180 } 6181 6182 MVT XLenVT = Subtarget.getXLenVT(); 6183 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6184 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6185 DAG.getUNDEF(ContainerVT), Zero, VL); 6186 6187 SDValue SplatValue = DAG.getConstant( 6188 Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT); 6189 SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6190 DAG.getUNDEF(ContainerVT), SplatValue, VL); 6191 6192 SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src, 6193 Splat, ZeroSplat, VL); 6194 if (!VT.isFixedLengthVector()) 6195 return Result; 6196 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6197 } 6198 6199 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op, 6200 SelectionDAG &DAG) const { 6201 SDLoc DL(Op); 6202 MVT VT = Op.getSimpleValueType(); 6203 6204 SDValue Op1 = Op.getOperand(0); 6205 SDValue Op2 = Op.getOperand(1); 6206 ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 6207 // NOTE: Mask is dropped. 6208 SDValue VL = Op.getOperand(4); 6209 6210 MVT ContainerVT = VT; 6211 if (VT.isFixedLengthVector()) { 6212 ContainerVT = getContainerForFixedLengthVector(VT); 6213 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6214 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6215 } 6216 6217 SDValue Result; 6218 SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 6219 6220 switch (Condition) { 6221 default: 6222 break; 6223 // X != Y --> (X^Y) 6224 case ISD::SETNE: 6225 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6226 break; 6227 // X == Y --> ~(X^Y) 6228 case ISD::SETEQ: { 6229 SDValue Temp = 6230 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6231 Result = 6232 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL); 6233 break; 6234 } 6235 // X >s Y --> X == 0 & Y == 1 --> ~X & Y 6236 // X <u Y --> X == 0 & Y == 1 --> ~X & Y 6237 case ISD::SETGT: 6238 case ISD::SETULT: { 6239 SDValue Temp = 6240 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6241 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL); 6242 break; 6243 } 6244 // X <s Y --> X == 1 & Y == 0 --> ~Y & X 6245 // X >u Y --> X == 1 & Y == 0 --> ~Y & X 6246 case ISD::SETLT: 6247 case ISD::SETUGT: { 6248 SDValue Temp = 6249 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6250 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL); 6251 break; 6252 } 6253 // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 6254 // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 6255 case ISD::SETGE: 6256 case ISD::SETULE: { 6257 SDValue Temp = 6258 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6259 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL); 6260 break; 6261 } 6262 // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 6263 // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 6264 case ISD::SETLE: 6265 case ISD::SETUGE: { 6266 SDValue Temp = 6267 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6268 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL); 6269 break; 6270 } 6271 } 6272 6273 if (!VT.isFixedLengthVector()) 6274 return Result; 6275 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6276 } 6277 6278 // Lower Floating-Point/Integer Type-Convert VP SDNodes 6279 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG, 6280 unsigned RISCVISDOpc) const { 6281 SDLoc DL(Op); 6282 6283 SDValue Src = Op.getOperand(0); 6284 SDValue Mask = Op.getOperand(1); 6285 SDValue VL = Op.getOperand(2); 6286 6287 MVT DstVT = Op.getSimpleValueType(); 6288 MVT SrcVT = Src.getSimpleValueType(); 6289 if (DstVT.isFixedLengthVector()) { 6290 DstVT = getContainerForFixedLengthVector(DstVT); 6291 SrcVT = getContainerForFixedLengthVector(SrcVT); 6292 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6293 MVT MaskVT = getMaskTypeFor(DstVT); 6294 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6295 } 6296 6297 unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL || 6298 RISCVISDOpc == RISCVISD::FP_TO_SINT_VL) 6299 ? RISCVISD::VSEXT_VL 6300 : RISCVISD::VZEXT_VL; 6301 6302 unsigned DstEltSize = DstVT.getScalarSizeInBits(); 6303 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 6304 6305 SDValue Result; 6306 if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion. 6307 if (SrcVT.isInteger()) { 6308 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6309 6310 // Do we need to do any pre-widening before converting? 6311 if (SrcEltSize == 1) { 6312 MVT IntVT = DstVT.changeVectorElementTypeToInteger(); 6313 MVT XLenVT = Subtarget.getXLenVT(); 6314 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6315 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6316 DAG.getUNDEF(IntVT), Zero, VL); 6317 SDValue One = DAG.getConstant( 6318 RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT); 6319 SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6320 DAG.getUNDEF(IntVT), One, VL); 6321 Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat, 6322 ZeroSplat, VL); 6323 } else if (DstEltSize > (2 * SrcEltSize)) { 6324 // Widen before converting. 6325 MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2), 6326 DstVT.getVectorElementCount()); 6327 Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL); 6328 } 6329 6330 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6331 } else { 6332 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6333 "Wrong input/output vector types"); 6334 6335 // Convert f16 to f32 then convert f32 to i64. 6336 if (DstEltSize > (2 * SrcEltSize)) { 6337 assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6338 MVT InterimFVT = 6339 MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6340 Src = 6341 DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL); 6342 } 6343 6344 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6345 } 6346 } else { // Narrowing + Conversion 6347 if (SrcVT.isInteger()) { 6348 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6349 // First do a narrowing convert to an FP type half the size, then round 6350 // the FP type to a small FP type if needed. 6351 6352 MVT InterimFVT = DstVT; 6353 if (SrcEltSize > (2 * DstEltSize)) { 6354 assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!"); 6355 assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6356 InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6357 } 6358 6359 Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL); 6360 6361 if (InterimFVT != DstVT) { 6362 Src = Result; 6363 Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL); 6364 } 6365 } else { 6366 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6367 "Wrong input/output vector types"); 6368 // First do a narrowing conversion to an integer half the size, then 6369 // truncate if needed. 6370 6371 if (DstEltSize == 1) { 6372 // First convert to the same size integer, then convert to mask using 6373 // setcc. 6374 assert(SrcEltSize >= 16 && "Unexpected FP type!"); 6375 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize), 6376 DstVT.getVectorElementCount()); 6377 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6378 6379 // Compare the integer result to 0. The integer should be 0 or 1/-1, 6380 // otherwise the conversion was undefined. 6381 MVT XLenVT = Subtarget.getXLenVT(); 6382 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 6383 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT, 6384 DAG.getUNDEF(InterimIVT), SplatZero); 6385 Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero, 6386 DAG.getCondCode(ISD::SETNE), Mask, VL); 6387 } else { 6388 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6389 DstVT.getVectorElementCount()); 6390 6391 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6392 6393 while (InterimIVT != DstVT) { 6394 SrcEltSize /= 2; 6395 Src = Result; 6396 InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6397 DstVT.getVectorElementCount()); 6398 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT, 6399 Src, Mask, VL); 6400 } 6401 } 6402 } 6403 } 6404 6405 MVT VT = Op.getSimpleValueType(); 6406 if (!VT.isFixedLengthVector()) 6407 return Result; 6408 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6409 } 6410 6411 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6412 unsigned MaskOpc, 6413 unsigned VecOpc) const { 6414 MVT VT = Op.getSimpleValueType(); 6415 if (VT.getVectorElementType() != MVT::i1) 6416 return lowerVPOp(Op, DAG, VecOpc); 6417 6418 // It is safe to drop mask parameter as masked-off elements are undef. 6419 SDValue Op1 = Op->getOperand(0); 6420 SDValue Op2 = Op->getOperand(1); 6421 SDValue VL = Op->getOperand(3); 6422 6423 MVT ContainerVT = VT; 6424 const bool IsFixed = VT.isFixedLengthVector(); 6425 if (IsFixed) { 6426 ContainerVT = getContainerForFixedLengthVector(VT); 6427 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6428 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6429 } 6430 6431 SDLoc DL(Op); 6432 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6433 if (!IsFixed) 6434 return Val; 6435 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6436 } 6437 6438 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6439 // matched to a RVV indexed load. The RVV indexed load instructions only 6440 // support the "unsigned unscaled" addressing mode; indices are implicitly 6441 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6442 // signed or scaled indexing is extended to the XLEN value type and scaled 6443 // accordingly. 6444 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6445 SelectionDAG &DAG) const { 6446 SDLoc DL(Op); 6447 MVT VT = Op.getSimpleValueType(); 6448 6449 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6450 EVT MemVT = MemSD->getMemoryVT(); 6451 MachineMemOperand *MMO = MemSD->getMemOperand(); 6452 SDValue Chain = MemSD->getChain(); 6453 SDValue BasePtr = MemSD->getBasePtr(); 6454 6455 ISD::LoadExtType LoadExtType; 6456 SDValue Index, Mask, PassThru, VL; 6457 6458 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6459 Index = VPGN->getIndex(); 6460 Mask = VPGN->getMask(); 6461 PassThru = DAG.getUNDEF(VT); 6462 VL = VPGN->getVectorLength(); 6463 // VP doesn't support extending loads. 6464 LoadExtType = ISD::NON_EXTLOAD; 6465 } else { 6466 // Else it must be a MGATHER. 6467 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6468 Index = MGN->getIndex(); 6469 Mask = MGN->getMask(); 6470 PassThru = MGN->getPassThru(); 6471 LoadExtType = MGN->getExtensionType(); 6472 } 6473 6474 MVT IndexVT = Index.getSimpleValueType(); 6475 MVT XLenVT = Subtarget.getXLenVT(); 6476 6477 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6478 "Unexpected VTs!"); 6479 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6480 // Targets have to explicitly opt-in for extending vector loads. 6481 assert(LoadExtType == ISD::NON_EXTLOAD && 6482 "Unexpected extending MGATHER/VP_GATHER"); 6483 (void)LoadExtType; 6484 6485 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6486 // the selection of the masked intrinsics doesn't do this for us. 6487 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6488 6489 MVT ContainerVT = VT; 6490 if (VT.isFixedLengthVector()) { 6491 ContainerVT = getContainerForFixedLengthVector(VT); 6492 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6493 ContainerVT.getVectorElementCount()); 6494 6495 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6496 6497 if (!IsUnmasked) { 6498 MVT MaskVT = getMaskTypeFor(ContainerVT); 6499 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6500 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6501 } 6502 } 6503 6504 if (!VL) 6505 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6506 6507 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6508 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6509 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6510 VL); 6511 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6512 TrueMask, VL); 6513 } 6514 6515 unsigned IntID = 6516 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6517 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6518 if (IsUnmasked) 6519 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6520 else 6521 Ops.push_back(PassThru); 6522 Ops.push_back(BasePtr); 6523 Ops.push_back(Index); 6524 if (!IsUnmasked) 6525 Ops.push_back(Mask); 6526 Ops.push_back(VL); 6527 if (!IsUnmasked) 6528 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6529 6530 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6531 SDValue Result = 6532 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6533 Chain = Result.getValue(1); 6534 6535 if (VT.isFixedLengthVector()) 6536 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6537 6538 return DAG.getMergeValues({Result, Chain}, DL); 6539 } 6540 6541 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6542 // matched to a RVV indexed store. The RVV indexed store instructions only 6543 // support the "unsigned unscaled" addressing mode; indices are implicitly 6544 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6545 // signed or scaled indexing is extended to the XLEN value type and scaled 6546 // accordingly. 6547 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6548 SelectionDAG &DAG) const { 6549 SDLoc DL(Op); 6550 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6551 EVT MemVT = MemSD->getMemoryVT(); 6552 MachineMemOperand *MMO = MemSD->getMemOperand(); 6553 SDValue Chain = MemSD->getChain(); 6554 SDValue BasePtr = MemSD->getBasePtr(); 6555 6556 bool IsTruncatingStore = false; 6557 SDValue Index, Mask, Val, VL; 6558 6559 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6560 Index = VPSN->getIndex(); 6561 Mask = VPSN->getMask(); 6562 Val = VPSN->getValue(); 6563 VL = VPSN->getVectorLength(); 6564 // VP doesn't support truncating stores. 6565 IsTruncatingStore = false; 6566 } else { 6567 // Else it must be a MSCATTER. 6568 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6569 Index = MSN->getIndex(); 6570 Mask = MSN->getMask(); 6571 Val = MSN->getValue(); 6572 IsTruncatingStore = MSN->isTruncatingStore(); 6573 } 6574 6575 MVT VT = Val.getSimpleValueType(); 6576 MVT IndexVT = Index.getSimpleValueType(); 6577 MVT XLenVT = Subtarget.getXLenVT(); 6578 6579 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6580 "Unexpected VTs!"); 6581 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6582 // Targets have to explicitly opt-in for extending vector loads and 6583 // truncating vector stores. 6584 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6585 (void)IsTruncatingStore; 6586 6587 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6588 // the selection of the masked intrinsics doesn't do this for us. 6589 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6590 6591 MVT ContainerVT = VT; 6592 if (VT.isFixedLengthVector()) { 6593 ContainerVT = getContainerForFixedLengthVector(VT); 6594 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6595 ContainerVT.getVectorElementCount()); 6596 6597 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6598 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6599 6600 if (!IsUnmasked) { 6601 MVT MaskVT = getMaskTypeFor(ContainerVT); 6602 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6603 } 6604 } 6605 6606 if (!VL) 6607 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6608 6609 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6610 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6611 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6612 VL); 6613 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6614 TrueMask, VL); 6615 } 6616 6617 unsigned IntID = 6618 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6619 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6620 Ops.push_back(Val); 6621 Ops.push_back(BasePtr); 6622 Ops.push_back(Index); 6623 if (!IsUnmasked) 6624 Ops.push_back(Mask); 6625 Ops.push_back(VL); 6626 6627 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6628 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6629 } 6630 6631 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6632 SelectionDAG &DAG) const { 6633 const MVT XLenVT = Subtarget.getXLenVT(); 6634 SDLoc DL(Op); 6635 SDValue Chain = Op->getOperand(0); 6636 SDValue SysRegNo = DAG.getTargetConstant( 6637 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6638 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6639 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6640 6641 // Encoding used for rounding mode in RISCV differs from that used in 6642 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6643 // table, which consists of a sequence of 4-bit fields, each representing 6644 // corresponding FLT_ROUNDS mode. 6645 static const int Table = 6646 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6647 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6648 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6649 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6650 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6651 6652 SDValue Shift = 6653 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6654 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6655 DAG.getConstant(Table, DL, XLenVT), Shift); 6656 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6657 DAG.getConstant(7, DL, XLenVT)); 6658 6659 return DAG.getMergeValues({Masked, Chain}, DL); 6660 } 6661 6662 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6663 SelectionDAG &DAG) const { 6664 const MVT XLenVT = Subtarget.getXLenVT(); 6665 SDLoc DL(Op); 6666 SDValue Chain = Op->getOperand(0); 6667 SDValue RMValue = Op->getOperand(1); 6668 SDValue SysRegNo = DAG.getTargetConstant( 6669 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6670 6671 // Encoding used for rounding mode in RISCV differs from that used in 6672 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6673 // a table, which consists of a sequence of 4-bit fields, each representing 6674 // corresponding RISCV mode. 6675 static const unsigned Table = 6676 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6677 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6678 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6679 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6680 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6681 6682 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6683 DAG.getConstant(2, DL, XLenVT)); 6684 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6685 DAG.getConstant(Table, DL, XLenVT), Shift); 6686 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6687 DAG.getConstant(0x7, DL, XLenVT)); 6688 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6689 RMValue); 6690 } 6691 6692 SDValue RISCVTargetLowering::lowerEH_DWARF_CFA(SDValue Op, 6693 SelectionDAG &DAG) const { 6694 MachineFunction &MF = DAG.getMachineFunction(); 6695 6696 bool isRISCV64 = Subtarget.is64Bit(); 6697 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6698 6699 int FI = MF.getFrameInfo().CreateFixedObject(isRISCV64 ? 8 : 4, 0, false); 6700 return DAG.getFrameIndex(FI, PtrVT); 6701 } 6702 6703 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6704 switch (IntNo) { 6705 default: 6706 llvm_unreachable("Unexpected Intrinsic"); 6707 case Intrinsic::riscv_bcompress: 6708 return RISCVISD::BCOMPRESSW; 6709 case Intrinsic::riscv_bdecompress: 6710 return RISCVISD::BDECOMPRESSW; 6711 case Intrinsic::riscv_bfp: 6712 return RISCVISD::BFPW; 6713 case Intrinsic::riscv_fsl: 6714 return RISCVISD::FSLW; 6715 case Intrinsic::riscv_fsr: 6716 return RISCVISD::FSRW; 6717 } 6718 } 6719 6720 // Converts the given intrinsic to a i64 operation with any extension. 6721 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6722 unsigned IntNo) { 6723 SDLoc DL(N); 6724 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6725 // Deal with the Instruction Operands 6726 SmallVector<SDValue, 3> NewOps; 6727 for (SDValue Op : drop_begin(N->ops())) 6728 // Promote the operand to i64 type 6729 NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op)); 6730 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps); 6731 // ReplaceNodeResults requires we maintain the same type for the return value. 6732 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6733 } 6734 6735 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6736 // form of the given Opcode. 6737 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6738 switch (Opcode) { 6739 default: 6740 llvm_unreachable("Unexpected opcode"); 6741 case ISD::SHL: 6742 return RISCVISD::SLLW; 6743 case ISD::SRA: 6744 return RISCVISD::SRAW; 6745 case ISD::SRL: 6746 return RISCVISD::SRLW; 6747 case ISD::SDIV: 6748 return RISCVISD::DIVW; 6749 case ISD::UDIV: 6750 return RISCVISD::DIVUW; 6751 case ISD::UREM: 6752 return RISCVISD::REMUW; 6753 case ISD::ROTL: 6754 return RISCVISD::ROLW; 6755 case ISD::ROTR: 6756 return RISCVISD::RORW; 6757 } 6758 } 6759 6760 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6761 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6762 // otherwise be promoted to i64, making it difficult to select the 6763 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6764 // type i8/i16/i32 is lost. 6765 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6766 unsigned ExtOpc = ISD::ANY_EXTEND) { 6767 SDLoc DL(N); 6768 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6769 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6770 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6771 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6772 // ReplaceNodeResults requires we maintain the same type for the return value. 6773 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6774 } 6775 6776 // Converts the given 32-bit operation to a i64 operation with signed extension 6777 // semantic to reduce the signed extension instructions. 6778 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6779 SDLoc DL(N); 6780 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6781 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6782 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6783 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6784 DAG.getValueType(MVT::i32)); 6785 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6786 } 6787 6788 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6789 SmallVectorImpl<SDValue> &Results, 6790 SelectionDAG &DAG) const { 6791 SDLoc DL(N); 6792 switch (N->getOpcode()) { 6793 default: 6794 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6795 case ISD::STRICT_FP_TO_SINT: 6796 case ISD::STRICT_FP_TO_UINT: 6797 case ISD::FP_TO_SINT: 6798 case ISD::FP_TO_UINT: { 6799 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6800 "Unexpected custom legalisation"); 6801 bool IsStrict = N->isStrictFPOpcode(); 6802 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6803 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6804 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6805 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6806 TargetLowering::TypeSoftenFloat) { 6807 if (!isTypeLegal(Op0.getValueType())) 6808 return; 6809 if (IsStrict) { 6810 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6811 : RISCVISD::STRICT_FCVT_WU_RV64; 6812 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6813 SDValue Res = DAG.getNode( 6814 Opc, DL, VTs, N->getOperand(0), Op0, 6815 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6816 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6817 Results.push_back(Res.getValue(1)); 6818 return; 6819 } 6820 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6821 SDValue Res = 6822 DAG.getNode(Opc, DL, MVT::i64, Op0, 6823 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6824 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6825 return; 6826 } 6827 // If the FP type needs to be softened, emit a library call using the 'si' 6828 // version. If we left it to default legalization we'd end up with 'di'. If 6829 // the FP type doesn't need to be softened just let generic type 6830 // legalization promote the result type. 6831 RTLIB::Libcall LC; 6832 if (IsSigned) 6833 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6834 else 6835 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6836 MakeLibCallOptions CallOptions; 6837 EVT OpVT = Op0.getValueType(); 6838 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6839 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6840 SDValue Result; 6841 std::tie(Result, Chain) = 6842 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6843 Results.push_back(Result); 6844 if (IsStrict) 6845 Results.push_back(Chain); 6846 break; 6847 } 6848 case ISD::READCYCLECOUNTER: { 6849 assert(!Subtarget.is64Bit() && 6850 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6851 6852 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6853 SDValue RCW = 6854 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6855 6856 Results.push_back( 6857 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6858 Results.push_back(RCW.getValue(2)); 6859 break; 6860 } 6861 case ISD::MUL: { 6862 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6863 unsigned XLen = Subtarget.getXLen(); 6864 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6865 if (Size > XLen) { 6866 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6867 SDValue LHS = N->getOperand(0); 6868 SDValue RHS = N->getOperand(1); 6869 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6870 6871 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6872 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6873 // We need exactly one side to be unsigned. 6874 if (LHSIsU == RHSIsU) 6875 return; 6876 6877 auto MakeMULPair = [&](SDValue S, SDValue U) { 6878 MVT XLenVT = Subtarget.getXLenVT(); 6879 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6880 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6881 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6882 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6883 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6884 }; 6885 6886 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6887 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6888 6889 // The other operand should be signed, but still prefer MULH when 6890 // possible. 6891 if (RHSIsU && LHSIsS && !RHSIsS) 6892 Results.push_back(MakeMULPair(LHS, RHS)); 6893 else if (LHSIsU && RHSIsS && !LHSIsS) 6894 Results.push_back(MakeMULPair(RHS, LHS)); 6895 6896 return; 6897 } 6898 LLVM_FALLTHROUGH; 6899 } 6900 case ISD::ADD: 6901 case ISD::SUB: 6902 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6903 "Unexpected custom legalisation"); 6904 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6905 break; 6906 case ISD::SHL: 6907 case ISD::SRA: 6908 case ISD::SRL: 6909 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6910 "Unexpected custom legalisation"); 6911 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6912 // If we can use a BSET instruction, allow default promotion to apply. 6913 if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() && 6914 isOneConstant(N->getOperand(0))) 6915 break; 6916 Results.push_back(customLegalizeToWOp(N, DAG)); 6917 break; 6918 } 6919 6920 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6921 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6922 // shift amount. 6923 if (N->getOpcode() == ISD::SHL) { 6924 SDLoc DL(N); 6925 SDValue NewOp0 = 6926 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6927 SDValue NewOp1 = 6928 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6929 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6930 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6931 DAG.getValueType(MVT::i32)); 6932 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6933 } 6934 6935 break; 6936 case ISD::ROTL: 6937 case ISD::ROTR: 6938 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6939 "Unexpected custom legalisation"); 6940 Results.push_back(customLegalizeToWOp(N, DAG)); 6941 break; 6942 case ISD::CTTZ: 6943 case ISD::CTTZ_ZERO_UNDEF: 6944 case ISD::CTLZ: 6945 case ISD::CTLZ_ZERO_UNDEF: { 6946 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6947 "Unexpected custom legalisation"); 6948 6949 SDValue NewOp0 = 6950 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6951 bool IsCTZ = 6952 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6953 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6954 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6955 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6956 return; 6957 } 6958 case ISD::SDIV: 6959 case ISD::UDIV: 6960 case ISD::UREM: { 6961 MVT VT = N->getSimpleValueType(0); 6962 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6963 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6964 "Unexpected custom legalisation"); 6965 // Don't promote division/remainder by constant since we should expand those 6966 // to multiply by magic constant. 6967 // FIXME: What if the expansion is disabled for minsize. 6968 if (N->getOperand(1).getOpcode() == ISD::Constant) 6969 return; 6970 6971 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6972 // the upper 32 bits. For other types we need to sign or zero extend 6973 // based on the opcode. 6974 unsigned ExtOpc = ISD::ANY_EXTEND; 6975 if (VT != MVT::i32) 6976 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6977 : ISD::ZERO_EXTEND; 6978 6979 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6980 break; 6981 } 6982 case ISD::UADDO: 6983 case ISD::USUBO: { 6984 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6985 "Unexpected custom legalisation"); 6986 bool IsAdd = N->getOpcode() == ISD::UADDO; 6987 // Create an ADDW or SUBW. 6988 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6989 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6990 SDValue Res = 6991 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6992 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6993 DAG.getValueType(MVT::i32)); 6994 6995 SDValue Overflow; 6996 if (IsAdd && isOneConstant(RHS)) { 6997 // Special case uaddo X, 1 overflowed if the addition result is 0. 6998 // The general case (X + C) < C is not necessarily beneficial. Although we 6999 // reduce the live range of X, we may introduce the materialization of 7000 // constant C, especially when the setcc result is used by branch. We have 7001 // no compare with constant and branch instructions. 7002 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, 7003 DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ); 7004 } else { 7005 // Sign extend the LHS and perform an unsigned compare with the ADDW 7006 // result. Since the inputs are sign extended from i32, this is equivalent 7007 // to comparing the lower 32 bits. 7008 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 7009 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 7010 IsAdd ? ISD::SETULT : ISD::SETUGT); 7011 } 7012 7013 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7014 Results.push_back(Overflow); 7015 return; 7016 } 7017 case ISD::UADDSAT: 7018 case ISD::USUBSAT: { 7019 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7020 "Unexpected custom legalisation"); 7021 if (Subtarget.hasStdExtZbb()) { 7022 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 7023 // sign extend allows overflow of the lower 32 bits to be detected on 7024 // the promoted size. 7025 SDValue LHS = 7026 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 7027 SDValue RHS = 7028 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 7029 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 7030 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7031 return; 7032 } 7033 7034 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 7035 // promotion for UADDO/USUBO. 7036 Results.push_back(expandAddSubSat(N, DAG)); 7037 return; 7038 } 7039 case ISD::ABS: { 7040 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7041 "Unexpected custom legalisation"); 7042 7043 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 7044 7045 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7046 7047 // Freeze the source so we can increase it's use count. 7048 Src = DAG.getFreeze(Src); 7049 7050 // Copy sign bit to all bits using the sraiw pattern. 7051 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 7052 DAG.getValueType(MVT::i32)); 7053 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 7054 DAG.getConstant(31, DL, MVT::i64)); 7055 7056 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 7057 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 7058 7059 // NOTE: The result is only required to be anyextended, but sext is 7060 // consistent with type legalization of sub. 7061 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 7062 DAG.getValueType(MVT::i32)); 7063 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 7064 return; 7065 } 7066 case ISD::BITCAST: { 7067 EVT VT = N->getValueType(0); 7068 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 7069 SDValue Op0 = N->getOperand(0); 7070 EVT Op0VT = Op0.getValueType(); 7071 MVT XLenVT = Subtarget.getXLenVT(); 7072 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 7073 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 7074 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 7075 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 7076 Subtarget.hasStdExtF()) { 7077 SDValue FPConv = 7078 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 7079 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 7080 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 7081 isTypeLegal(Op0VT)) { 7082 // Custom-legalize bitcasts from fixed-length vector types to illegal 7083 // scalar types in order to improve codegen. Bitcast the vector to a 7084 // one-element vector type whose element type is the same as the result 7085 // type, and extract the first element. 7086 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 7087 if (isTypeLegal(BVT)) { 7088 SDValue BVec = DAG.getBitcast(BVT, Op0); 7089 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 7090 DAG.getConstant(0, DL, XLenVT))); 7091 } 7092 } 7093 break; 7094 } 7095 case RISCVISD::GREV: 7096 case RISCVISD::GORC: 7097 case RISCVISD::SHFL: { 7098 MVT VT = N->getSimpleValueType(0); 7099 MVT XLenVT = Subtarget.getXLenVT(); 7100 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) && 7101 "Unexpected custom legalisation"); 7102 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 7103 assert((Subtarget.hasStdExtZbp() || 7104 (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV && 7105 N->getConstantOperandVal(1) == 7)) && 7106 "Unexpected extension"); 7107 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7108 SDValue NewOp1 = 7109 DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1)); 7110 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1); 7111 // ReplaceNodeResults requires we maintain the same type for the return 7112 // value. 7113 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes)); 7114 break; 7115 } 7116 case ISD::BSWAP: 7117 case ISD::BITREVERSE: { 7118 MVT VT = N->getSimpleValueType(0); 7119 MVT XLenVT = Subtarget.getXLenVT(); 7120 assert((VT == MVT::i8 || VT == MVT::i16 || 7121 (VT == MVT::i32 && Subtarget.is64Bit())) && 7122 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 7123 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7124 unsigned Imm = VT.getSizeInBits() - 1; 7125 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 7126 if (N->getOpcode() == ISD::BSWAP) 7127 Imm &= ~0x7U; 7128 SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0, 7129 DAG.getConstant(Imm, DL, XLenVT)); 7130 // ReplaceNodeResults requires we maintain the same type for the return 7131 // value. 7132 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 7133 break; 7134 } 7135 case ISD::FSHL: 7136 case ISD::FSHR: { 7137 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7138 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 7139 SDValue NewOp0 = 7140 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7141 SDValue NewOp1 = 7142 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7143 SDValue NewShAmt = 7144 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7145 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 7146 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 7147 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 7148 DAG.getConstant(0x1f, DL, MVT::i64)); 7149 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 7150 // instruction use different orders. fshl will return its first operand for 7151 // shift of zero, fshr will return its second operand. fsl and fsr both 7152 // return rs1 so the ISD nodes need to have different operand orders. 7153 // Shift amount is in rs2. 7154 unsigned Opc = RISCVISD::FSLW; 7155 if (N->getOpcode() == ISD::FSHR) { 7156 std::swap(NewOp0, NewOp1); 7157 Opc = RISCVISD::FSRW; 7158 } 7159 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 7160 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 7161 break; 7162 } 7163 case ISD::EXTRACT_VECTOR_ELT: { 7164 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 7165 // type is illegal (currently only vXi64 RV32). 7166 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 7167 // transferred to the destination register. We issue two of these from the 7168 // upper- and lower- halves of the SEW-bit vector element, slid down to the 7169 // first element. 7170 SDValue Vec = N->getOperand(0); 7171 SDValue Idx = N->getOperand(1); 7172 7173 // The vector type hasn't been legalized yet so we can't issue target 7174 // specific nodes if it needs legalization. 7175 // FIXME: We would manually legalize if it's important. 7176 if (!isTypeLegal(Vec.getValueType())) 7177 return; 7178 7179 MVT VecVT = Vec.getSimpleValueType(); 7180 7181 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 7182 VecVT.getVectorElementType() == MVT::i64 && 7183 "Unexpected EXTRACT_VECTOR_ELT legalization"); 7184 7185 // If this is a fixed vector, we need to convert it to a scalable vector. 7186 MVT ContainerVT = VecVT; 7187 if (VecVT.isFixedLengthVector()) { 7188 ContainerVT = getContainerForFixedLengthVector(VecVT); 7189 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 7190 } 7191 7192 MVT XLenVT = Subtarget.getXLenVT(); 7193 7194 // Use a VL of 1 to avoid processing more elements than we need. 7195 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7196 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 7197 7198 // Unless the index is known to be 0, we must slide the vector down to get 7199 // the desired element into index 0. 7200 if (!isNullConstant(Idx)) { 7201 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 7202 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 7203 } 7204 7205 // Extract the lower XLEN bits of the correct vector element. 7206 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7207 7208 // To extract the upper XLEN bits of the vector element, shift the first 7209 // element right by 32 bits and re-extract the lower XLEN bits. 7210 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 7211 DAG.getUNDEF(ContainerVT), 7212 DAG.getConstant(32, DL, XLenVT), VL); 7213 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 7214 ThirtyTwoV, Mask, VL); 7215 7216 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7217 7218 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7219 break; 7220 } 7221 case ISD::INTRINSIC_WO_CHAIN: { 7222 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7223 switch (IntNo) { 7224 default: 7225 llvm_unreachable( 7226 "Don't know how to custom type legalize this intrinsic!"); 7227 case Intrinsic::riscv_grev: 7228 case Intrinsic::riscv_gorc: { 7229 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7230 "Unexpected custom legalisation"); 7231 SDValue NewOp1 = 7232 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7233 SDValue NewOp2 = 7234 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7235 unsigned Opc = 7236 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 7237 // If the control is a constant, promote the node by clearing any extra 7238 // bits bits in the control. isel will form greviw/gorciw if the result is 7239 // sign extended. 7240 if (isa<ConstantSDNode>(NewOp2)) { 7241 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7242 DAG.getConstant(0x1f, DL, MVT::i64)); 7243 Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 7244 } 7245 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7246 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7247 break; 7248 } 7249 case Intrinsic::riscv_bcompress: 7250 case Intrinsic::riscv_bdecompress: 7251 case Intrinsic::riscv_bfp: 7252 case Intrinsic::riscv_fsl: 7253 case Intrinsic::riscv_fsr: { 7254 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7255 "Unexpected custom legalisation"); 7256 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 7257 break; 7258 } 7259 case Intrinsic::riscv_orc_b: { 7260 // Lower to the GORCI encoding for orc.b with the operand extended. 7261 SDValue NewOp = 7262 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7263 SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp, 7264 DAG.getConstant(7, DL, MVT::i64)); 7265 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7266 return; 7267 } 7268 case Intrinsic::riscv_shfl: 7269 case Intrinsic::riscv_unshfl: { 7270 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7271 "Unexpected custom legalisation"); 7272 SDValue NewOp1 = 7273 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7274 SDValue NewOp2 = 7275 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7276 unsigned Opc = 7277 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 7278 // There is no (UN)SHFLIW. If the control word is a constant, we can use 7279 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 7280 // will be shuffled the same way as the lower 32 bit half, but the two 7281 // halves won't cross. 7282 if (isa<ConstantSDNode>(NewOp2)) { 7283 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7284 DAG.getConstant(0xf, DL, MVT::i64)); 7285 Opc = 7286 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 7287 } 7288 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7289 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7290 break; 7291 } 7292 case Intrinsic::riscv_vmv_x_s: { 7293 EVT VT = N->getValueType(0); 7294 MVT XLenVT = Subtarget.getXLenVT(); 7295 if (VT.bitsLT(XLenVT)) { 7296 // Simple case just extract using vmv.x.s and truncate. 7297 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 7298 Subtarget.getXLenVT(), N->getOperand(1)); 7299 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 7300 return; 7301 } 7302 7303 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 7304 "Unexpected custom legalization"); 7305 7306 // We need to do the move in two steps. 7307 SDValue Vec = N->getOperand(1); 7308 MVT VecVT = Vec.getSimpleValueType(); 7309 7310 // First extract the lower XLEN bits of the element. 7311 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7312 7313 // To extract the upper XLEN bits of the vector element, shift the first 7314 // element right by 32 bits and re-extract the lower XLEN bits. 7315 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7316 SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG); 7317 7318 SDValue ThirtyTwoV = 7319 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 7320 DAG.getConstant(32, DL, XLenVT), VL); 7321 SDValue LShr32 = 7322 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 7323 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7324 7325 Results.push_back( 7326 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7327 break; 7328 } 7329 } 7330 break; 7331 } 7332 case ISD::VECREDUCE_ADD: 7333 case ISD::VECREDUCE_AND: 7334 case ISD::VECREDUCE_OR: 7335 case ISD::VECREDUCE_XOR: 7336 case ISD::VECREDUCE_SMAX: 7337 case ISD::VECREDUCE_UMAX: 7338 case ISD::VECREDUCE_SMIN: 7339 case ISD::VECREDUCE_UMIN: 7340 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 7341 Results.push_back(V); 7342 break; 7343 case ISD::VP_REDUCE_ADD: 7344 case ISD::VP_REDUCE_AND: 7345 case ISD::VP_REDUCE_OR: 7346 case ISD::VP_REDUCE_XOR: 7347 case ISD::VP_REDUCE_SMAX: 7348 case ISD::VP_REDUCE_UMAX: 7349 case ISD::VP_REDUCE_SMIN: 7350 case ISD::VP_REDUCE_UMIN: 7351 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 7352 Results.push_back(V); 7353 break; 7354 case ISD::FLT_ROUNDS_: { 7355 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7356 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7357 Results.push_back(Res.getValue(0)); 7358 Results.push_back(Res.getValue(1)); 7359 break; 7360 } 7361 } 7362 } 7363 7364 // A structure to hold one of the bit-manipulation patterns below. Together, a 7365 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7366 // (or (and (shl x, 1), 0xAAAAAAAA), 7367 // (and (srl x, 1), 0x55555555)) 7368 struct RISCVBitmanipPat { 7369 SDValue Op; 7370 unsigned ShAmt; 7371 bool IsSHL; 7372 7373 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7374 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7375 } 7376 }; 7377 7378 // Matches patterns of the form 7379 // (and (shl x, C2), (C1 << C2)) 7380 // (and (srl x, C2), C1) 7381 // (shl (and x, C1), C2) 7382 // (srl (and x, (C1 << C2)), C2) 7383 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7384 // The expected masks for each shift amount are specified in BitmanipMasks where 7385 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7386 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7387 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7388 // XLen is 64. 7389 static Optional<RISCVBitmanipPat> 7390 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7391 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7392 "Unexpected number of masks"); 7393 Optional<uint64_t> Mask; 7394 // Optionally consume a mask around the shift operation. 7395 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7396 Mask = Op.getConstantOperandVal(1); 7397 Op = Op.getOperand(0); 7398 } 7399 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7400 return None; 7401 bool IsSHL = Op.getOpcode() == ISD::SHL; 7402 7403 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7404 return None; 7405 uint64_t ShAmt = Op.getConstantOperandVal(1); 7406 7407 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7408 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7409 return None; 7410 // If we don't have enough masks for 64 bit, then we must be trying to 7411 // match SHFL so we're only allowed to shift 1/4 of the width. 7412 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7413 return None; 7414 7415 SDValue Src = Op.getOperand(0); 7416 7417 // The expected mask is shifted left when the AND is found around SHL 7418 // patterns. 7419 // ((x >> 1) & 0x55555555) 7420 // ((x << 1) & 0xAAAAAAAA) 7421 bool SHLExpMask = IsSHL; 7422 7423 if (!Mask) { 7424 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7425 // the mask is all ones: consume that now. 7426 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7427 Mask = Src.getConstantOperandVal(1); 7428 Src = Src.getOperand(0); 7429 // The expected mask is now in fact shifted left for SRL, so reverse the 7430 // decision. 7431 // ((x & 0xAAAAAAAA) >> 1) 7432 // ((x & 0x55555555) << 1) 7433 SHLExpMask = !SHLExpMask; 7434 } else { 7435 // Use a default shifted mask of all-ones if there's no AND, truncated 7436 // down to the expected width. This simplifies the logic later on. 7437 Mask = maskTrailingOnes<uint64_t>(Width); 7438 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7439 } 7440 } 7441 7442 unsigned MaskIdx = Log2_32(ShAmt); 7443 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7444 7445 if (SHLExpMask) 7446 ExpMask <<= ShAmt; 7447 7448 if (Mask != ExpMask) 7449 return None; 7450 7451 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7452 } 7453 7454 // Matches any of the following bit-manipulation patterns: 7455 // (and (shl x, 1), (0x55555555 << 1)) 7456 // (and (srl x, 1), 0x55555555) 7457 // (shl (and x, 0x55555555), 1) 7458 // (srl (and x, (0x55555555 << 1)), 1) 7459 // where the shift amount and mask may vary thus: 7460 // [1] = 0x55555555 / 0xAAAAAAAA 7461 // [2] = 0x33333333 / 0xCCCCCCCC 7462 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7463 // [8] = 0x00FF00FF / 0xFF00FF00 7464 // [16] = 0x0000FFFF / 0xFFFFFFFF 7465 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7466 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7467 // These are the unshifted masks which we use to match bit-manipulation 7468 // patterns. They may be shifted left in certain circumstances. 7469 static const uint64_t BitmanipMasks[] = { 7470 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7471 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7472 7473 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7474 } 7475 7476 // Try to fold (<bop> x, (reduction.<bop> vec, start)) 7477 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) { 7478 auto BinOpToRVVReduce = [](unsigned Opc) { 7479 switch (Opc) { 7480 default: 7481 llvm_unreachable("Unhandled binary to transfrom reduction"); 7482 case ISD::ADD: 7483 return RISCVISD::VECREDUCE_ADD_VL; 7484 case ISD::UMAX: 7485 return RISCVISD::VECREDUCE_UMAX_VL; 7486 case ISD::SMAX: 7487 return RISCVISD::VECREDUCE_SMAX_VL; 7488 case ISD::UMIN: 7489 return RISCVISD::VECREDUCE_UMIN_VL; 7490 case ISD::SMIN: 7491 return RISCVISD::VECREDUCE_SMIN_VL; 7492 case ISD::AND: 7493 return RISCVISD::VECREDUCE_AND_VL; 7494 case ISD::OR: 7495 return RISCVISD::VECREDUCE_OR_VL; 7496 case ISD::XOR: 7497 return RISCVISD::VECREDUCE_XOR_VL; 7498 case ISD::FADD: 7499 return RISCVISD::VECREDUCE_FADD_VL; 7500 case ISD::FMAXNUM: 7501 return RISCVISD::VECREDUCE_FMAX_VL; 7502 case ISD::FMINNUM: 7503 return RISCVISD::VECREDUCE_FMIN_VL; 7504 } 7505 }; 7506 7507 auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) { 7508 return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7509 isNullConstant(V.getOperand(1)) && 7510 V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc); 7511 }; 7512 7513 unsigned Opc = N->getOpcode(); 7514 unsigned ReduceIdx; 7515 if (IsReduction(N->getOperand(0), Opc)) 7516 ReduceIdx = 0; 7517 else if (IsReduction(N->getOperand(1), Opc)) 7518 ReduceIdx = 1; 7519 else 7520 return SDValue(); 7521 7522 // Skip if FADD disallows reassociation but the combiner needs. 7523 if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation()) 7524 return SDValue(); 7525 7526 SDValue Extract = N->getOperand(ReduceIdx); 7527 SDValue Reduce = Extract.getOperand(0); 7528 if (!Reduce.hasOneUse()) 7529 return SDValue(); 7530 7531 SDValue ScalarV = Reduce.getOperand(2); 7532 7533 // Make sure that ScalarV is a splat with VL=1. 7534 if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL && 7535 ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL && 7536 ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL) 7537 return SDValue(); 7538 7539 if (!isOneConstant(ScalarV.getOperand(2))) 7540 return SDValue(); 7541 7542 // TODO: Deal with value other than neutral element. 7543 auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) { 7544 if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() && 7545 isNullFPConstant(V)) 7546 return true; 7547 return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(), 7548 N->getFlags()) == V; 7549 }; 7550 7551 // Check the scalar of ScalarV is neutral element 7552 if (!IsRVVNeutralElement(N, ScalarV.getOperand(1))) 7553 return SDValue(); 7554 7555 if (!ScalarV.hasOneUse()) 7556 return SDValue(); 7557 7558 EVT SplatVT = ScalarV.getValueType(); 7559 SDValue NewStart = N->getOperand(1 - ReduceIdx); 7560 unsigned SplatOpc = RISCVISD::VFMV_S_F_VL; 7561 if (SplatVT.isInteger()) { 7562 auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode()); 7563 if (!C || C->isZero() || !isInt<5>(C->getSExtValue())) 7564 SplatOpc = RISCVISD::VMV_S_X_VL; 7565 else 7566 SplatOpc = RISCVISD::VMV_V_X_VL; 7567 } 7568 7569 SDValue NewScalarV = 7570 DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart, 7571 ScalarV.getOperand(2)); 7572 SDValue NewReduce = 7573 DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(), 7574 Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV, 7575 Reduce.getOperand(3), Reduce.getOperand(4)); 7576 return DAG.getNode(Extract.getOpcode(), SDLoc(Extract), 7577 Extract.getValueType(), NewReduce, Extract.getOperand(1)); 7578 } 7579 7580 // Match the following pattern as a GREVI(W) operation 7581 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7582 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7583 const RISCVSubtarget &Subtarget) { 7584 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7585 EVT VT = Op.getValueType(); 7586 7587 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7588 auto LHS = matchGREVIPat(Op.getOperand(0)); 7589 auto RHS = matchGREVIPat(Op.getOperand(1)); 7590 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7591 SDLoc DL(Op); 7592 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7593 DAG.getConstant(LHS->ShAmt, DL, VT)); 7594 } 7595 } 7596 return SDValue(); 7597 } 7598 7599 // Matches any the following pattern as a GORCI(W) operation 7600 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7601 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7602 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7603 // Note that with the variant of 3., 7604 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7605 // the inner pattern will first be matched as GREVI and then the outer 7606 // pattern will be matched to GORC via the first rule above. 7607 // 4. (or (rotl/rotr x, bitwidth/2), x) 7608 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7609 const RISCVSubtarget &Subtarget) { 7610 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7611 EVT VT = Op.getValueType(); 7612 7613 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7614 SDLoc DL(Op); 7615 SDValue Op0 = Op.getOperand(0); 7616 SDValue Op1 = Op.getOperand(1); 7617 7618 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7619 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7620 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7621 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7622 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7623 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7624 if ((Reverse.getOpcode() == ISD::ROTL || 7625 Reverse.getOpcode() == ISD::ROTR) && 7626 Reverse.getOperand(0) == X && 7627 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7628 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7629 if (RotAmt == (VT.getSizeInBits() / 2)) 7630 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7631 DAG.getConstant(RotAmt, DL, VT)); 7632 } 7633 return SDValue(); 7634 }; 7635 7636 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7637 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7638 return V; 7639 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7640 return V; 7641 7642 // OR is commutable so canonicalize its OR operand to the left 7643 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7644 std::swap(Op0, Op1); 7645 if (Op0.getOpcode() != ISD::OR) 7646 return SDValue(); 7647 SDValue OrOp0 = Op0.getOperand(0); 7648 SDValue OrOp1 = Op0.getOperand(1); 7649 auto LHS = matchGREVIPat(OrOp0); 7650 // OR is commutable so swap the operands and try again: x might have been 7651 // on the left 7652 if (!LHS) { 7653 std::swap(OrOp0, OrOp1); 7654 LHS = matchGREVIPat(OrOp0); 7655 } 7656 auto RHS = matchGREVIPat(Op1); 7657 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7658 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7659 DAG.getConstant(LHS->ShAmt, DL, VT)); 7660 } 7661 } 7662 return SDValue(); 7663 } 7664 7665 // Matches any of the following bit-manipulation patterns: 7666 // (and (shl x, 1), (0x22222222 << 1)) 7667 // (and (srl x, 1), 0x22222222) 7668 // (shl (and x, 0x22222222), 1) 7669 // (srl (and x, (0x22222222 << 1)), 1) 7670 // where the shift amount and mask may vary thus: 7671 // [1] = 0x22222222 / 0x44444444 7672 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7673 // [4] = 0x00F000F0 / 0x0F000F00 7674 // [8] = 0x0000FF00 / 0x00FF0000 7675 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7676 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7677 // These are the unshifted masks which we use to match bit-manipulation 7678 // patterns. They may be shifted left in certain circumstances. 7679 static const uint64_t BitmanipMasks[] = { 7680 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7681 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7682 7683 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7684 } 7685 7686 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7687 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7688 const RISCVSubtarget &Subtarget) { 7689 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7690 EVT VT = Op.getValueType(); 7691 7692 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7693 return SDValue(); 7694 7695 SDValue Op0 = Op.getOperand(0); 7696 SDValue Op1 = Op.getOperand(1); 7697 7698 // Or is commutable so canonicalize the second OR to the LHS. 7699 if (Op0.getOpcode() != ISD::OR) 7700 std::swap(Op0, Op1); 7701 if (Op0.getOpcode() != ISD::OR) 7702 return SDValue(); 7703 7704 // We found an inner OR, so our operands are the operands of the inner OR 7705 // and the other operand of the outer OR. 7706 SDValue A = Op0.getOperand(0); 7707 SDValue B = Op0.getOperand(1); 7708 SDValue C = Op1; 7709 7710 auto Match1 = matchSHFLPat(A); 7711 auto Match2 = matchSHFLPat(B); 7712 7713 // If neither matched, we failed. 7714 if (!Match1 && !Match2) 7715 return SDValue(); 7716 7717 // We had at least one match. if one failed, try the remaining C operand. 7718 if (!Match1) { 7719 std::swap(A, C); 7720 Match1 = matchSHFLPat(A); 7721 if (!Match1) 7722 return SDValue(); 7723 } else if (!Match2) { 7724 std::swap(B, C); 7725 Match2 = matchSHFLPat(B); 7726 if (!Match2) 7727 return SDValue(); 7728 } 7729 assert(Match1 && Match2); 7730 7731 // Make sure our matches pair up. 7732 if (!Match1->formsPairWith(*Match2)) 7733 return SDValue(); 7734 7735 // All the remains is to make sure C is an AND with the same input, that masks 7736 // out the bits that are being shuffled. 7737 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7738 C.getOperand(0) != Match1->Op) 7739 return SDValue(); 7740 7741 uint64_t Mask = C.getConstantOperandVal(1); 7742 7743 static const uint64_t BitmanipMasks[] = { 7744 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7745 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7746 }; 7747 7748 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7749 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7750 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7751 7752 if (Mask != ExpMask) 7753 return SDValue(); 7754 7755 SDLoc DL(Op); 7756 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7757 DAG.getConstant(Match1->ShAmt, DL, VT)); 7758 } 7759 7760 // Optimize (add (shl x, c0), (shl y, c1)) -> 7761 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7762 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7763 const RISCVSubtarget &Subtarget) { 7764 // Perform this optimization only in the zba extension. 7765 if (!Subtarget.hasStdExtZba()) 7766 return SDValue(); 7767 7768 // Skip for vector types and larger types. 7769 EVT VT = N->getValueType(0); 7770 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7771 return SDValue(); 7772 7773 // The two operand nodes must be SHL and have no other use. 7774 SDValue N0 = N->getOperand(0); 7775 SDValue N1 = N->getOperand(1); 7776 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7777 !N0->hasOneUse() || !N1->hasOneUse()) 7778 return SDValue(); 7779 7780 // Check c0 and c1. 7781 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7782 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7783 if (!N0C || !N1C) 7784 return SDValue(); 7785 int64_t C0 = N0C->getSExtValue(); 7786 int64_t C1 = N1C->getSExtValue(); 7787 if (C0 <= 0 || C1 <= 0) 7788 return SDValue(); 7789 7790 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7791 int64_t Bits = std::min(C0, C1); 7792 int64_t Diff = std::abs(C0 - C1); 7793 if (Diff != 1 && Diff != 2 && Diff != 3) 7794 return SDValue(); 7795 7796 // Build nodes. 7797 SDLoc DL(N); 7798 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7799 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7800 SDValue NA0 = 7801 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7802 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7803 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7804 } 7805 7806 // Combine 7807 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7808 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7809 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7810 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7811 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7812 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7813 // The grev patterns represents BSWAP. 7814 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7815 // off the grev. 7816 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7817 const RISCVSubtarget &Subtarget) { 7818 bool IsWInstruction = 7819 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7820 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7821 IsWInstruction) && 7822 "Unexpected opcode!"); 7823 SDValue Src = N->getOperand(0); 7824 EVT VT = N->getValueType(0); 7825 SDLoc DL(N); 7826 7827 if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV) 7828 return SDValue(); 7829 7830 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7831 !isa<ConstantSDNode>(Src.getOperand(1))) 7832 return SDValue(); 7833 7834 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7835 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7836 7837 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7838 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7839 unsigned ShAmt1 = N->getConstantOperandVal(1); 7840 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7841 if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7842 return SDValue(); 7843 7844 Src = Src.getOperand(0); 7845 7846 // Toggle bit the MSB of the shift. 7847 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7848 if (CombinedShAmt == 0) 7849 return Src; 7850 7851 SDValue Res = DAG.getNode( 7852 RISCVISD::GREV, DL, VT, Src, 7853 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7854 if (!IsWInstruction) 7855 return Res; 7856 7857 // Sign extend the result to match the behavior of the rotate. This will be 7858 // selected to GREVIW in isel. 7859 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res, 7860 DAG.getValueType(MVT::i32)); 7861 } 7862 7863 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7864 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7865 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7866 // not undo itself, but they are redundant. 7867 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7868 bool IsGORC = N->getOpcode() == RISCVISD::GORC; 7869 assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode"); 7870 SDValue Src = N->getOperand(0); 7871 7872 if (Src.getOpcode() != N->getOpcode()) 7873 return SDValue(); 7874 7875 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7876 !isa<ConstantSDNode>(Src.getOperand(1))) 7877 return SDValue(); 7878 7879 unsigned ShAmt1 = N->getConstantOperandVal(1); 7880 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7881 Src = Src.getOperand(0); 7882 7883 unsigned CombinedShAmt; 7884 if (IsGORC) 7885 CombinedShAmt = ShAmt1 | ShAmt2; 7886 else 7887 CombinedShAmt = ShAmt1 ^ ShAmt2; 7888 7889 if (CombinedShAmt == 0) 7890 return Src; 7891 7892 SDLoc DL(N); 7893 return DAG.getNode( 7894 N->getOpcode(), DL, N->getValueType(0), Src, 7895 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7896 } 7897 7898 // Combine a constant select operand into its use: 7899 // 7900 // (and (select cond, -1, c), x) 7901 // -> (select cond, x, (and x, c)) [AllOnes=1] 7902 // (or (select cond, 0, c), x) 7903 // -> (select cond, x, (or x, c)) [AllOnes=0] 7904 // (xor (select cond, 0, c), x) 7905 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7906 // (add (select cond, 0, c), x) 7907 // -> (select cond, x, (add x, c)) [AllOnes=0] 7908 // (sub x, (select cond, 0, c)) 7909 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7910 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7911 SelectionDAG &DAG, bool AllOnes) { 7912 EVT VT = N->getValueType(0); 7913 7914 // Skip vectors. 7915 if (VT.isVector()) 7916 return SDValue(); 7917 7918 if ((Slct.getOpcode() != ISD::SELECT && 7919 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7920 !Slct.hasOneUse()) 7921 return SDValue(); 7922 7923 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7924 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7925 }; 7926 7927 bool SwapSelectOps; 7928 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7929 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7930 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7931 SDValue NonConstantVal; 7932 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7933 SwapSelectOps = false; 7934 NonConstantVal = FalseVal; 7935 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7936 SwapSelectOps = true; 7937 NonConstantVal = TrueVal; 7938 } else 7939 return SDValue(); 7940 7941 // Slct is now know to be the desired identity constant when CC is true. 7942 TrueVal = OtherOp; 7943 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7944 // Unless SwapSelectOps says the condition should be false. 7945 if (SwapSelectOps) 7946 std::swap(TrueVal, FalseVal); 7947 7948 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7949 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7950 {Slct.getOperand(0), Slct.getOperand(1), 7951 Slct.getOperand(2), TrueVal, FalseVal}); 7952 7953 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7954 {Slct.getOperand(0), TrueVal, FalseVal}); 7955 } 7956 7957 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7958 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7959 bool AllOnes) { 7960 SDValue N0 = N->getOperand(0); 7961 SDValue N1 = N->getOperand(1); 7962 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7963 return Result; 7964 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7965 return Result; 7966 return SDValue(); 7967 } 7968 7969 // Transform (add (mul x, c0), c1) -> 7970 // (add (mul (add x, c1/c0), c0), c1%c0). 7971 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7972 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7973 // to an infinite loop in DAGCombine if transformed. 7974 // Or transform (add (mul x, c0), c1) -> 7975 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7976 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7977 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7978 // lead to an infinite loop in DAGCombine if transformed. 7979 // Or transform (add (mul x, c0), c1) -> 7980 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7981 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7982 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7983 // lead to an infinite loop in DAGCombine if transformed. 7984 // Or transform (add (mul x, c0), c1) -> 7985 // (mul (add x, c1/c0), c0). 7986 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7987 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7988 const RISCVSubtarget &Subtarget) { 7989 // Skip for vector types and larger types. 7990 EVT VT = N->getValueType(0); 7991 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7992 return SDValue(); 7993 // The first operand node must be a MUL and has no other use. 7994 SDValue N0 = N->getOperand(0); 7995 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7996 return SDValue(); 7997 // Check if c0 and c1 match above conditions. 7998 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7999 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8000 if (!N0C || !N1C) 8001 return SDValue(); 8002 // If N0C has multiple uses it's possible one of the cases in 8003 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 8004 // in an infinite loop. 8005 if (!N0C->hasOneUse()) 8006 return SDValue(); 8007 int64_t C0 = N0C->getSExtValue(); 8008 int64_t C1 = N1C->getSExtValue(); 8009 int64_t CA, CB; 8010 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 8011 return SDValue(); 8012 // Search for proper CA (non-zero) and CB that both are simm12. 8013 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 8014 !isInt<12>(C0 * (C1 / C0))) { 8015 CA = C1 / C0; 8016 CB = C1 % C0; 8017 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 8018 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 8019 CA = C1 / C0 + 1; 8020 CB = C1 % C0 - C0; 8021 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 8022 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 8023 CA = C1 / C0 - 1; 8024 CB = C1 % C0 + C0; 8025 } else 8026 return SDValue(); 8027 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 8028 SDLoc DL(N); 8029 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 8030 DAG.getConstant(CA, DL, VT)); 8031 SDValue New1 = 8032 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 8033 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 8034 } 8035 8036 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 8037 const RISCVSubtarget &Subtarget) { 8038 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 8039 return V; 8040 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 8041 return V; 8042 if (SDValue V = combineBinOpToReduce(N, DAG)) 8043 return V; 8044 // fold (add (select lhs, rhs, cc, 0, y), x) -> 8045 // (select lhs, rhs, cc, x, (add x, y)) 8046 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8047 } 8048 8049 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 8050 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 8051 // (select lhs, rhs, cc, x, (sub x, y)) 8052 SDValue N0 = N->getOperand(0); 8053 SDValue N1 = N->getOperand(1); 8054 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 8055 } 8056 8057 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG, 8058 const RISCVSubtarget &Subtarget) { 8059 SDValue N0 = N->getOperand(0); 8060 // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero 8061 // extending X. This is safe since we only need the LSB after the shift and 8062 // shift amounts larger than 31 would produce poison. If we wait until 8063 // type legalization, we'll create RISCVISD::SRLW and we can't recover it 8064 // to use a BEXT instruction. 8065 if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() && 8066 N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) && 8067 N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) && 8068 N0.hasOneUse()) { 8069 SDLoc DL(N); 8070 SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0)); 8071 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1)); 8072 SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1); 8073 SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl, 8074 DAG.getConstant(1, DL, MVT::i64)); 8075 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And); 8076 } 8077 8078 if (SDValue V = combineBinOpToReduce(N, DAG)) 8079 return V; 8080 8081 // fold (and (select lhs, rhs, cc, -1, y), x) -> 8082 // (select lhs, rhs, cc, x, (and x, y)) 8083 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 8084 } 8085 8086 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 8087 const RISCVSubtarget &Subtarget) { 8088 if (Subtarget.hasStdExtZbp()) { 8089 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 8090 return GREV; 8091 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 8092 return GORC; 8093 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 8094 return SHFL; 8095 } 8096 8097 if (SDValue V = combineBinOpToReduce(N, DAG)) 8098 return V; 8099 // fold (or (select cond, 0, y), x) -> 8100 // (select cond, x, (or x, y)) 8101 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8102 } 8103 8104 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 8105 SDValue N0 = N->getOperand(0); 8106 SDValue N1 = N->getOperand(1); 8107 8108 // fold (xor (sllw 1, x), -1) -> (rolw ~1, x) 8109 // NOTE: Assumes ROL being legal means ROLW is legal. 8110 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8111 if (N0.getOpcode() == RISCVISD::SLLW && 8112 isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) && 8113 TLI.isOperationLegal(ISD::ROTL, MVT::i64)) { 8114 SDLoc DL(N); 8115 return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64, 8116 DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1)); 8117 } 8118 8119 if (SDValue V = combineBinOpToReduce(N, DAG)) 8120 return V; 8121 // fold (xor (select cond, 0, y), x) -> 8122 // (select cond, x, (xor x, y)) 8123 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8124 } 8125 8126 // Replace (seteq (i64 (and X, 0xffffffff)), C1) with 8127 // (seteq (i64 (sext_inreg (X, i32)), C1')) where C1' is C1 sign extended from 8128 // bit 31. Same for setne. C1' may be cheaper to materialize and the sext_inreg 8129 // can become a sext.w instead of a shift pair. 8130 static SDValue performSETCCCombine(SDNode *N, SelectionDAG &DAG, 8131 const RISCVSubtarget &Subtarget) { 8132 SDValue N0 = N->getOperand(0); 8133 SDValue N1 = N->getOperand(1); 8134 EVT VT = N->getValueType(0); 8135 EVT OpVT = N0.getValueType(); 8136 8137 if (OpVT != MVT::i64 || !Subtarget.is64Bit()) 8138 return SDValue(); 8139 8140 // RHS needs to be a constant. 8141 auto *N1C = dyn_cast<ConstantSDNode>(N1); 8142 if (!N1C) 8143 return SDValue(); 8144 8145 // LHS needs to be (and X, 0xffffffff). 8146 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse() || 8147 !isa<ConstantSDNode>(N0.getOperand(1)) || 8148 N0.getConstantOperandVal(1) != UINT64_C(0xffffffff)) 8149 return SDValue(); 8150 8151 // Looking for an equality compare. 8152 ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8153 if (!isIntEqualitySetCC(Cond)) 8154 return SDValue(); 8155 8156 const APInt &C1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 8157 8158 SDLoc dl(N); 8159 // If the constant is larger than 2^32 - 1 it is impossible for both sides 8160 // to be equal. 8161 if (C1.getActiveBits() > 32) 8162 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT); 8163 8164 SDValue SExtOp = DAG.getNode(ISD::SIGN_EXTEND_INREG, N, OpVT, 8165 N0.getOperand(0), DAG.getValueType(MVT::i32)); 8166 return DAG.getSetCC(dl, VT, SExtOp, DAG.getConstant(C1.trunc(32).sext(64), 8167 dl, OpVT), Cond); 8168 } 8169 8170 static SDValue 8171 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 8172 const RISCVSubtarget &Subtarget) { 8173 SDValue Src = N->getOperand(0); 8174 EVT VT = N->getValueType(0); 8175 8176 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 8177 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8178 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 8179 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 8180 Src.getOperand(0)); 8181 8182 // Fold (i64 (sext_inreg (abs X), i32)) -> 8183 // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits. 8184 // The (sext_inreg (neg X), i32) will be selected to negw by isel. This 8185 // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user 8186 // of the (i32 (abs X)) is a sext or setcc or something else that causes type 8187 // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have 8188 // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg 8189 // may get combined into an earlier operation so we need to use 8190 // ComputeNumSignBits. 8191 // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for 8192 // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so 8193 // we can't assume that X has 33 sign bits. We must check. 8194 if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() && 8195 Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 && 8196 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 && 8197 DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) { 8198 SDLoc DL(N); 8199 SDValue Freeze = DAG.getFreeze(Src.getOperand(0)); 8200 SDValue Neg = 8201 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze); 8202 Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg, 8203 DAG.getValueType(MVT::i32)); 8204 return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg); 8205 } 8206 8207 return SDValue(); 8208 } 8209 8210 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 8211 // vwadd(u).vv/vx or vwsub(u).vv/vx. 8212 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 8213 bool Commute = false) { 8214 assert((N->getOpcode() == RISCVISD::ADD_VL || 8215 N->getOpcode() == RISCVISD::SUB_VL) && 8216 "Unexpected opcode"); 8217 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 8218 SDValue Op0 = N->getOperand(0); 8219 SDValue Op1 = N->getOperand(1); 8220 if (Commute) 8221 std::swap(Op0, Op1); 8222 8223 MVT VT = N->getSimpleValueType(0); 8224 8225 // Determine the narrow size for a widening add/sub. 8226 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8227 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8228 VT.getVectorElementCount()); 8229 8230 SDValue Mask = N->getOperand(2); 8231 SDValue VL = N->getOperand(3); 8232 8233 SDLoc DL(N); 8234 8235 // If the RHS is a sext or zext, we can form a widening op. 8236 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 8237 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 8238 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 8239 unsigned ExtOpc = Op1.getOpcode(); 8240 Op1 = Op1.getOperand(0); 8241 // Re-introduce narrower extends if needed. 8242 if (Op1.getValueType() != NarrowVT) 8243 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8244 8245 unsigned WOpc; 8246 if (ExtOpc == RISCVISD::VSEXT_VL) 8247 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 8248 else 8249 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 8250 8251 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 8252 } 8253 8254 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 8255 // sext/zext? 8256 8257 return SDValue(); 8258 } 8259 8260 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 8261 // vwsub(u).vv/vx. 8262 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 8263 SDValue Op0 = N->getOperand(0); 8264 SDValue Op1 = N->getOperand(1); 8265 SDValue Mask = N->getOperand(2); 8266 SDValue VL = N->getOperand(3); 8267 8268 MVT VT = N->getSimpleValueType(0); 8269 MVT NarrowVT = Op1.getSimpleValueType(); 8270 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 8271 8272 unsigned VOpc; 8273 switch (N->getOpcode()) { 8274 default: llvm_unreachable("Unexpected opcode"); 8275 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 8276 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 8277 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 8278 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 8279 } 8280 8281 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 8282 N->getOpcode() == RISCVISD::VWSUB_W_VL; 8283 8284 SDLoc DL(N); 8285 8286 // If the LHS is a sext or zext, we can narrow this op to the same size as 8287 // the RHS. 8288 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 8289 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 8290 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 8291 unsigned ExtOpc = Op0.getOpcode(); 8292 Op0 = Op0.getOperand(0); 8293 // Re-introduce narrower extends if needed. 8294 if (Op0.getValueType() != NarrowVT) 8295 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8296 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 8297 } 8298 8299 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 8300 N->getOpcode() == RISCVISD::VWADDU_W_VL; 8301 8302 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 8303 // to commute and use a vwadd(u).vx instead. 8304 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 8305 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 8306 Op0 = Op0.getOperand(1); 8307 8308 // See if have enough sign bits or zero bits in the scalar to use a 8309 // widening add/sub by splatting to smaller element size. 8310 unsigned EltBits = VT.getScalarSizeInBits(); 8311 unsigned ScalarBits = Op0.getValueSizeInBits(); 8312 // Make sure we're getting all element bits from the scalar register. 8313 // FIXME: Support implicit sign extension of vmv.v.x? 8314 if (ScalarBits < EltBits) 8315 return SDValue(); 8316 8317 if (IsSigned) { 8318 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 8319 return SDValue(); 8320 } else { 8321 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8322 if (!DAG.MaskedValueIsZero(Op0, Mask)) 8323 return SDValue(); 8324 } 8325 8326 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8327 DAG.getUNDEF(NarrowVT), Op0, VL); 8328 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 8329 } 8330 8331 return SDValue(); 8332 } 8333 8334 // Try to form VWMUL, VWMULU or VWMULSU. 8335 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 8336 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 8337 bool Commute) { 8338 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 8339 SDValue Op0 = N->getOperand(0); 8340 SDValue Op1 = N->getOperand(1); 8341 if (Commute) 8342 std::swap(Op0, Op1); 8343 8344 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 8345 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 8346 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 8347 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 8348 return SDValue(); 8349 8350 SDValue Mask = N->getOperand(2); 8351 SDValue VL = N->getOperand(3); 8352 8353 // Make sure the mask and VL match. 8354 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 8355 return SDValue(); 8356 8357 MVT VT = N->getSimpleValueType(0); 8358 8359 // Determine the narrow size for a widening multiply. 8360 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8361 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8362 VT.getVectorElementCount()); 8363 8364 SDLoc DL(N); 8365 8366 // See if the other operand is the same opcode. 8367 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 8368 if (!Op1.hasOneUse()) 8369 return SDValue(); 8370 8371 // Make sure the mask and VL match. 8372 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 8373 return SDValue(); 8374 8375 Op1 = Op1.getOperand(0); 8376 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 8377 // The operand is a splat of a scalar. 8378 8379 // The pasthru must be undef for tail agnostic 8380 if (!Op1.getOperand(0).isUndef()) 8381 return SDValue(); 8382 // The VL must be the same. 8383 if (Op1.getOperand(2) != VL) 8384 return SDValue(); 8385 8386 // Get the scalar value. 8387 Op1 = Op1.getOperand(1); 8388 8389 // See if have enough sign bits or zero bits in the scalar to use a 8390 // widening multiply by splatting to smaller element size. 8391 unsigned EltBits = VT.getScalarSizeInBits(); 8392 unsigned ScalarBits = Op1.getValueSizeInBits(); 8393 // Make sure we're getting all element bits from the scalar register. 8394 // FIXME: Support implicit sign extension of vmv.v.x? 8395 if (ScalarBits < EltBits) 8396 return SDValue(); 8397 8398 // If the LHS is a sign extend, try to use vwmul. 8399 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 8400 // Can use vwmul. 8401 } else { 8402 // Otherwise try to use vwmulu or vwmulsu. 8403 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8404 if (DAG.MaskedValueIsZero(Op1, Mask)) 8405 IsVWMULSU = IsSignExt; 8406 else 8407 return SDValue(); 8408 } 8409 8410 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8411 DAG.getUNDEF(NarrowVT), Op1, VL); 8412 } else 8413 return SDValue(); 8414 8415 Op0 = Op0.getOperand(0); 8416 8417 // Re-introduce narrower extends if needed. 8418 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 8419 if (Op0.getValueType() != NarrowVT) 8420 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8421 // vwmulsu requires second operand to be zero extended. 8422 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 8423 if (Op1.getValueType() != NarrowVT) 8424 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8425 8426 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 8427 if (!IsVWMULSU) 8428 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 8429 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 8430 } 8431 8432 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 8433 switch (Op.getOpcode()) { 8434 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 8435 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 8436 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 8437 case ISD::FCEIL: return RISCVFPRndMode::RUP; 8438 case ISD::FROUND: return RISCVFPRndMode::RMM; 8439 } 8440 8441 return RISCVFPRndMode::Invalid; 8442 } 8443 8444 // Fold 8445 // (fp_to_int (froundeven X)) -> fcvt X, rne 8446 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 8447 // (fp_to_int (ffloor X)) -> fcvt X, rdn 8448 // (fp_to_int (fceil X)) -> fcvt X, rup 8449 // (fp_to_int (fround X)) -> fcvt X, rmm 8450 static SDValue performFP_TO_INTCombine(SDNode *N, 8451 TargetLowering::DAGCombinerInfo &DCI, 8452 const RISCVSubtarget &Subtarget) { 8453 SelectionDAG &DAG = DCI.DAG; 8454 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8455 MVT XLenVT = Subtarget.getXLenVT(); 8456 8457 // Only handle XLen or i32 types. Other types narrower than XLen will 8458 // eventually be legalized to XLenVT. 8459 EVT VT = N->getValueType(0); 8460 if (VT != MVT::i32 && VT != XLenVT) 8461 return SDValue(); 8462 8463 SDValue Src = N->getOperand(0); 8464 8465 // Ensure the FP type is also legal. 8466 if (!TLI.isTypeLegal(Src.getValueType())) 8467 return SDValue(); 8468 8469 // Don't do this for f16 with Zfhmin and not Zfh. 8470 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8471 return SDValue(); 8472 8473 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8474 if (FRM == RISCVFPRndMode::Invalid) 8475 return SDValue(); 8476 8477 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8478 8479 unsigned Opc; 8480 if (VT == XLenVT) 8481 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8482 else 8483 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8484 8485 SDLoc DL(N); 8486 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 8487 DAG.getTargetConstant(FRM, DL, XLenVT)); 8488 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 8489 } 8490 8491 // Fold 8492 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 8493 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 8494 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8495 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8496 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8497 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8498 TargetLowering::DAGCombinerInfo &DCI, 8499 const RISCVSubtarget &Subtarget) { 8500 SelectionDAG &DAG = DCI.DAG; 8501 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8502 MVT XLenVT = Subtarget.getXLenVT(); 8503 8504 // Only handle XLen types. Other types narrower than XLen will eventually be 8505 // legalized to XLenVT. 8506 EVT DstVT = N->getValueType(0); 8507 if (DstVT != XLenVT) 8508 return SDValue(); 8509 8510 SDValue Src = N->getOperand(0); 8511 8512 // Ensure the FP type is also legal. 8513 if (!TLI.isTypeLegal(Src.getValueType())) 8514 return SDValue(); 8515 8516 // Don't do this for f16 with Zfhmin and not Zfh. 8517 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8518 return SDValue(); 8519 8520 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8521 8522 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8523 if (FRM == RISCVFPRndMode::Invalid) 8524 return SDValue(); 8525 8526 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8527 8528 unsigned Opc; 8529 if (SatVT == DstVT) 8530 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8531 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8532 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8533 else 8534 return SDValue(); 8535 // FIXME: Support other SatVTs by clamping before or after the conversion. 8536 8537 Src = Src.getOperand(0); 8538 8539 SDLoc DL(N); 8540 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8541 DAG.getTargetConstant(FRM, DL, XLenVT)); 8542 8543 // RISCV FP-to-int conversions saturate to the destination register size, but 8544 // don't produce 0 for nan. 8545 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8546 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8547 } 8548 8549 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is 8550 // smaller than XLenVT. 8551 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG, 8552 const RISCVSubtarget &Subtarget) { 8553 assert(Subtarget.hasStdExtZbkb() && "Unexpected extension"); 8554 8555 SDValue Src = N->getOperand(0); 8556 if (Src.getOpcode() != ISD::BSWAP) 8557 return SDValue(); 8558 8559 EVT VT = N->getValueType(0); 8560 if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() || 8561 !isPowerOf2_32(VT.getSizeInBits())) 8562 return SDValue(); 8563 8564 SDLoc DL(N); 8565 return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0), 8566 DAG.getConstant(7, DL, VT)); 8567 } 8568 8569 // Convert from one FMA opcode to another based on whether we are negating the 8570 // multiply result and/or the accumulator. 8571 // NOTE: Only supports RVV operations with VL. 8572 static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc) { 8573 assert((NegMul || NegAcc) && "Not negating anything?"); 8574 8575 // Negating the multiply result changes ADD<->SUB and toggles 'N'. 8576 if (NegMul) { 8577 // clang-format off 8578 switch (Opcode) { 8579 default: llvm_unreachable("Unexpected opcode"); 8580 case RISCVISD::VFMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break; 8581 case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFMADD_VL; break; 8582 case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFMSUB_VL; break; 8583 case RISCVISD::VFMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break; 8584 } 8585 // clang-format on 8586 } 8587 8588 // Negating the accumulator changes ADD<->SUB. 8589 if (NegAcc) { 8590 // clang-format off 8591 switch (Opcode) { 8592 default: llvm_unreachable("Unexpected opcode"); 8593 case RISCVISD::VFMADD_VL: Opcode = RISCVISD::VFMSUB_VL; break; 8594 case RISCVISD::VFMSUB_VL: Opcode = RISCVISD::VFMADD_VL; break; 8595 case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break; 8596 case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break; 8597 } 8598 // clang-format on 8599 } 8600 8601 return Opcode; 8602 } 8603 8604 static SDValue performSRACombine(SDNode *N, SelectionDAG &DAG, 8605 const RISCVSubtarget &Subtarget) { 8606 assert(N->getOpcode() == ISD::SRA && "Unexpected opcode"); 8607 8608 if (N->getValueType(0) != MVT::i64 || !Subtarget.is64Bit()) 8609 return SDValue(); 8610 8611 if (!isa<ConstantSDNode>(N->getOperand(1))) 8612 return SDValue(); 8613 uint64_t ShAmt = N->getConstantOperandVal(1); 8614 if (ShAmt > 32) 8615 return SDValue(); 8616 8617 SDValue N0 = N->getOperand(0); 8618 8619 // Combine (sra (sext_inreg (shl X, C1), i32), C2) -> 8620 // (sra (shl X, C1+32), C2+32) so it gets selected as SLLI+SRAI instead of 8621 // SLLIW+SRAIW. SLLI+SRAI have compressed forms. 8622 if (ShAmt < 32 && 8623 N0.getOpcode() == ISD::SIGN_EXTEND_INREG && N0.hasOneUse() && 8624 cast<VTSDNode>(N0.getOperand(1))->getVT() == MVT::i32 && 8625 N0.getOperand(0).getOpcode() == ISD::SHL && N0.getOperand(0).hasOneUse() && 8626 isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) { 8627 uint64_t LShAmt = N0.getOperand(0).getConstantOperandVal(1); 8628 if (LShAmt < 32) { 8629 SDLoc ShlDL(N0.getOperand(0)); 8630 SDValue Shl = DAG.getNode(ISD::SHL, ShlDL, MVT::i64, 8631 N0.getOperand(0).getOperand(0), 8632 DAG.getConstant(LShAmt + 32, ShlDL, MVT::i64)); 8633 SDLoc DL(N); 8634 return DAG.getNode(ISD::SRA, DL, MVT::i64, Shl, 8635 DAG.getConstant(ShAmt + 32, DL, MVT::i64)); 8636 } 8637 } 8638 8639 // Combine (sra (shl X, 32), 32 - C) -> (shl (sext_inreg X, i32), C) 8640 // FIXME: Should this be a generic combine? There's a similar combine on X86. 8641 // 8642 // Also try these folds where an add or sub is in the middle. 8643 // (sra (add (shl X, 32), C1), 32 - C) -> (shl (sext_inreg (add X, C1), C) 8644 // (sra (sub C1, (shl X, 32)), 32 - C) -> (shl (sext_inreg (sub C1, X), C) 8645 SDValue Shl; 8646 ConstantSDNode *AddC = nullptr; 8647 8648 // We might have an ADD or SUB between the SRA and SHL. 8649 bool IsAdd = N0.getOpcode() == ISD::ADD; 8650 if ((IsAdd || N0.getOpcode() == ISD::SUB)) { 8651 if (!N0.hasOneUse()) 8652 return SDValue(); 8653 // Other operand needs to be a constant we can modify. 8654 AddC = dyn_cast<ConstantSDNode>(N0.getOperand(IsAdd ? 1 : 0)); 8655 if (!AddC) 8656 return SDValue(); 8657 8658 // AddC needs to have at least 32 trailing zeros. 8659 if (AddC->getAPIntValue().countTrailingZeros() < 32) 8660 return SDValue(); 8661 8662 Shl = N0.getOperand(IsAdd ? 0 : 1); 8663 } else { 8664 // Not an ADD or SUB. 8665 Shl = N0; 8666 } 8667 8668 // Look for a shift left by 32. 8669 if (Shl.getOpcode() != ISD::SHL || !Shl.hasOneUse() || 8670 !isa<ConstantSDNode>(Shl.getOperand(1)) || 8671 Shl.getConstantOperandVal(1) != 32) 8672 return SDValue(); 8673 8674 SDLoc DL(N); 8675 SDValue In = Shl.getOperand(0); 8676 8677 // If we looked through an ADD or SUB, we need to rebuild it with the shifted 8678 // constant. 8679 if (AddC) { 8680 SDValue ShiftedAddC = 8681 DAG.getConstant(AddC->getAPIntValue().lshr(32), DL, MVT::i64); 8682 if (IsAdd) 8683 In = DAG.getNode(ISD::ADD, DL, MVT::i64, In, ShiftedAddC); 8684 else 8685 In = DAG.getNode(ISD::SUB, DL, MVT::i64, ShiftedAddC, In); 8686 } 8687 8688 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, In, 8689 DAG.getValueType(MVT::i32)); 8690 if (ShAmt == 32) 8691 return SExt; 8692 8693 return DAG.getNode( 8694 ISD::SHL, DL, MVT::i64, SExt, 8695 DAG.getConstant(32 - ShAmt, DL, MVT::i64)); 8696 } 8697 8698 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8699 DAGCombinerInfo &DCI) const { 8700 SelectionDAG &DAG = DCI.DAG; 8701 8702 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8703 // bits are demanded. N will be added to the Worklist if it was not deleted. 8704 // Caller should return SDValue(N, 0) if this returns true. 8705 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8706 SDValue Op = N->getOperand(OpNo); 8707 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8708 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8709 return false; 8710 8711 if (N->getOpcode() != ISD::DELETED_NODE) 8712 DCI.AddToWorklist(N); 8713 return true; 8714 }; 8715 8716 switch (N->getOpcode()) { 8717 default: 8718 break; 8719 case RISCVISD::SplitF64: { 8720 SDValue Op0 = N->getOperand(0); 8721 // If the input to SplitF64 is just BuildPairF64 then the operation is 8722 // redundant. Instead, use BuildPairF64's operands directly. 8723 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8724 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8725 8726 if (Op0->isUndef()) { 8727 SDValue Lo = DAG.getUNDEF(MVT::i32); 8728 SDValue Hi = DAG.getUNDEF(MVT::i32); 8729 return DCI.CombineTo(N, Lo, Hi); 8730 } 8731 8732 SDLoc DL(N); 8733 8734 // It's cheaper to materialise two 32-bit integers than to load a double 8735 // from the constant pool and transfer it to integer registers through the 8736 // stack. 8737 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8738 APInt V = C->getValueAPF().bitcastToAPInt(); 8739 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8740 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8741 return DCI.CombineTo(N, Lo, Hi); 8742 } 8743 8744 // This is a target-specific version of a DAGCombine performed in 8745 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8746 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8747 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8748 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8749 !Op0.getNode()->hasOneUse()) 8750 break; 8751 SDValue NewSplitF64 = 8752 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8753 Op0.getOperand(0)); 8754 SDValue Lo = NewSplitF64.getValue(0); 8755 SDValue Hi = NewSplitF64.getValue(1); 8756 APInt SignBit = APInt::getSignMask(32); 8757 if (Op0.getOpcode() == ISD::FNEG) { 8758 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8759 DAG.getConstant(SignBit, DL, MVT::i32)); 8760 return DCI.CombineTo(N, Lo, NewHi); 8761 } 8762 assert(Op0.getOpcode() == ISD::FABS); 8763 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8764 DAG.getConstant(~SignBit, DL, MVT::i32)); 8765 return DCI.CombineTo(N, Lo, NewHi); 8766 } 8767 case RISCVISD::SLLW: 8768 case RISCVISD::SRAW: 8769 case RISCVISD::SRLW: { 8770 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8771 if (SimplifyDemandedLowBitsHelper(0, 32) || 8772 SimplifyDemandedLowBitsHelper(1, 5)) 8773 return SDValue(N, 0); 8774 8775 break; 8776 } 8777 case ISD::ROTR: 8778 case ISD::ROTL: 8779 case RISCVISD::RORW: 8780 case RISCVISD::ROLW: { 8781 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8782 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8783 if (SimplifyDemandedLowBitsHelper(0, 32) || 8784 SimplifyDemandedLowBitsHelper(1, 5)) 8785 return SDValue(N, 0); 8786 } 8787 8788 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8789 } 8790 case RISCVISD::CLZW: 8791 case RISCVISD::CTZW: { 8792 // Only the lower 32 bits of the first operand are read 8793 if (SimplifyDemandedLowBitsHelper(0, 32)) 8794 return SDValue(N, 0); 8795 break; 8796 } 8797 case RISCVISD::GREV: 8798 case RISCVISD::GORC: { 8799 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8800 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8801 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8802 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8803 return SDValue(N, 0); 8804 8805 return combineGREVI_GORCI(N, DAG); 8806 } 8807 case RISCVISD::GREVW: 8808 case RISCVISD::GORCW: { 8809 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8810 if (SimplifyDemandedLowBitsHelper(0, 32) || 8811 SimplifyDemandedLowBitsHelper(1, 5)) 8812 return SDValue(N, 0); 8813 8814 break; 8815 } 8816 case RISCVISD::SHFL: 8817 case RISCVISD::UNSHFL: { 8818 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8819 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8820 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8821 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8822 return SDValue(N, 0); 8823 8824 break; 8825 } 8826 case RISCVISD::SHFLW: 8827 case RISCVISD::UNSHFLW: { 8828 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8829 if (SimplifyDemandedLowBitsHelper(0, 32) || 8830 SimplifyDemandedLowBitsHelper(1, 4)) 8831 return SDValue(N, 0); 8832 8833 break; 8834 } 8835 case RISCVISD::BCOMPRESSW: 8836 case RISCVISD::BDECOMPRESSW: { 8837 // Only the lower 32 bits of LHS and RHS are read. 8838 if (SimplifyDemandedLowBitsHelper(0, 32) || 8839 SimplifyDemandedLowBitsHelper(1, 32)) 8840 return SDValue(N, 0); 8841 8842 break; 8843 } 8844 case RISCVISD::FSR: 8845 case RISCVISD::FSL: 8846 case RISCVISD::FSRW: 8847 case RISCVISD::FSLW: { 8848 bool IsWInstruction = 8849 N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW; 8850 unsigned BitWidth = 8851 IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits(); 8852 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8853 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 8854 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1)) 8855 return SDValue(N, 0); 8856 8857 break; 8858 } 8859 case RISCVISD::FMV_X_ANYEXTH: 8860 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8861 SDLoc DL(N); 8862 SDValue Op0 = N->getOperand(0); 8863 MVT VT = N->getSimpleValueType(0); 8864 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8865 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8866 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8867 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8868 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8869 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8870 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8871 assert(Op0.getOperand(0).getValueType() == VT && 8872 "Unexpected value type!"); 8873 return Op0.getOperand(0); 8874 } 8875 8876 // This is a target-specific version of a DAGCombine performed in 8877 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8878 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8879 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8880 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8881 !Op0.getNode()->hasOneUse()) 8882 break; 8883 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8884 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8885 APInt SignBit = APInt::getSignMask(FPBits).sext(VT.getSizeInBits()); 8886 if (Op0.getOpcode() == ISD::FNEG) 8887 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8888 DAG.getConstant(SignBit, DL, VT)); 8889 8890 assert(Op0.getOpcode() == ISD::FABS); 8891 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8892 DAG.getConstant(~SignBit, DL, VT)); 8893 } 8894 case ISD::ADD: 8895 return performADDCombine(N, DAG, Subtarget); 8896 case ISD::SUB: 8897 return performSUBCombine(N, DAG); 8898 case ISD::AND: 8899 return performANDCombine(N, DAG, Subtarget); 8900 case ISD::OR: 8901 return performORCombine(N, DAG, Subtarget); 8902 case ISD::XOR: 8903 return performXORCombine(N, DAG); 8904 case ISD::FADD: 8905 case ISD::UMAX: 8906 case ISD::UMIN: 8907 case ISD::SMAX: 8908 case ISD::SMIN: 8909 case ISD::FMAXNUM: 8910 case ISD::FMINNUM: 8911 return combineBinOpToReduce(N, DAG); 8912 case ISD::SETCC: 8913 return performSETCCCombine(N, DAG, Subtarget); 8914 case ISD::SIGN_EXTEND_INREG: 8915 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 8916 case ISD::ZERO_EXTEND: 8917 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8918 // type legalization. This is safe because fp_to_uint produces poison if 8919 // it overflows. 8920 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8921 SDValue Src = N->getOperand(0); 8922 if (Src.getOpcode() == ISD::FP_TO_UINT && 8923 isTypeLegal(Src.getOperand(0).getValueType())) 8924 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8925 Src.getOperand(0)); 8926 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8927 isTypeLegal(Src.getOperand(1).getValueType())) { 8928 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8929 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8930 Src.getOperand(0), Src.getOperand(1)); 8931 DCI.CombineTo(N, Res); 8932 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8933 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8934 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8935 } 8936 } 8937 return SDValue(); 8938 case RISCVISD::SELECT_CC: { 8939 // Transform 8940 SDValue LHS = N->getOperand(0); 8941 SDValue RHS = N->getOperand(1); 8942 SDValue TrueV = N->getOperand(3); 8943 SDValue FalseV = N->getOperand(4); 8944 8945 // If the True and False values are the same, we don't need a select_cc. 8946 if (TrueV == FalseV) 8947 return TrueV; 8948 8949 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8950 if (!ISD::isIntEqualitySetCC(CCVal)) 8951 break; 8952 8953 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8954 // (select_cc X, Y, lt, trueV, falseV) 8955 // Sometimes the setcc is introduced after select_cc has been formed. 8956 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8957 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8958 // If we're looking for eq 0 instead of ne 0, we need to invert the 8959 // condition. 8960 bool Invert = CCVal == ISD::SETEQ; 8961 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8962 if (Invert) 8963 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8964 8965 SDLoc DL(N); 8966 RHS = LHS.getOperand(1); 8967 LHS = LHS.getOperand(0); 8968 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8969 8970 SDValue TargetCC = DAG.getCondCode(CCVal); 8971 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8972 {LHS, RHS, TargetCC, TrueV, FalseV}); 8973 } 8974 8975 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8976 // (select_cc X, Y, eq/ne, trueV, falseV) 8977 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8978 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8979 {LHS.getOperand(0), LHS.getOperand(1), 8980 N->getOperand(2), TrueV, FalseV}); 8981 // (select_cc X, 1, setne, trueV, falseV) -> 8982 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8983 // This can occur when legalizing some floating point comparisons. 8984 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8985 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8986 SDLoc DL(N); 8987 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8988 SDValue TargetCC = DAG.getCondCode(CCVal); 8989 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8990 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8991 {LHS, RHS, TargetCC, TrueV, FalseV}); 8992 } 8993 8994 break; 8995 } 8996 case RISCVISD::BR_CC: { 8997 SDValue LHS = N->getOperand(1); 8998 SDValue RHS = N->getOperand(2); 8999 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 9000 if (!ISD::isIntEqualitySetCC(CCVal)) 9001 break; 9002 9003 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 9004 // (br_cc X, Y, lt, dest) 9005 // Sometimes the setcc is introduced after br_cc has been formed. 9006 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 9007 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 9008 // If we're looking for eq 0 instead of ne 0, we need to invert the 9009 // condition. 9010 bool Invert = CCVal == ISD::SETEQ; 9011 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 9012 if (Invert) 9013 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 9014 9015 SDLoc DL(N); 9016 RHS = LHS.getOperand(1); 9017 LHS = LHS.getOperand(0); 9018 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 9019 9020 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 9021 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 9022 N->getOperand(4)); 9023 } 9024 9025 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 9026 // (br_cc X, Y, eq/ne, trueV, falseV) 9027 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 9028 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 9029 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 9030 N->getOperand(3), N->getOperand(4)); 9031 9032 // (br_cc X, 1, setne, br_cc) -> 9033 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 9034 // This can occur when legalizing some floating point comparisons. 9035 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 9036 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 9037 SDLoc DL(N); 9038 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 9039 SDValue TargetCC = DAG.getCondCode(CCVal); 9040 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 9041 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 9042 N->getOperand(0), LHS, RHS, TargetCC, 9043 N->getOperand(4)); 9044 } 9045 break; 9046 } 9047 case ISD::BITREVERSE: 9048 return performBITREVERSECombine(N, DAG, Subtarget); 9049 case ISD::FP_TO_SINT: 9050 case ISD::FP_TO_UINT: 9051 return performFP_TO_INTCombine(N, DCI, Subtarget); 9052 case ISD::FP_TO_SINT_SAT: 9053 case ISD::FP_TO_UINT_SAT: 9054 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 9055 case ISD::FCOPYSIGN: { 9056 EVT VT = N->getValueType(0); 9057 if (!VT.isVector()) 9058 break; 9059 // There is a form of VFSGNJ which injects the negated sign of its second 9060 // operand. Try and bubble any FNEG up after the extend/round to produce 9061 // this optimized pattern. Avoid modifying cases where FP_ROUND and 9062 // TRUNC=1. 9063 SDValue In2 = N->getOperand(1); 9064 // Avoid cases where the extend/round has multiple uses, as duplicating 9065 // those is typically more expensive than removing a fneg. 9066 if (!In2.hasOneUse()) 9067 break; 9068 if (In2.getOpcode() != ISD::FP_EXTEND && 9069 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 9070 break; 9071 In2 = In2.getOperand(0); 9072 if (In2.getOpcode() != ISD::FNEG) 9073 break; 9074 SDLoc DL(N); 9075 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 9076 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 9077 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 9078 } 9079 case ISD::MGATHER: 9080 case ISD::MSCATTER: 9081 case ISD::VP_GATHER: 9082 case ISD::VP_SCATTER: { 9083 if (!DCI.isBeforeLegalize()) 9084 break; 9085 SDValue Index, ScaleOp; 9086 bool IsIndexScaled = false; 9087 bool IsIndexSigned = false; 9088 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 9089 Index = VPGSN->getIndex(); 9090 ScaleOp = VPGSN->getScale(); 9091 IsIndexScaled = VPGSN->isIndexScaled(); 9092 IsIndexSigned = VPGSN->isIndexSigned(); 9093 } else { 9094 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 9095 Index = MGSN->getIndex(); 9096 ScaleOp = MGSN->getScale(); 9097 IsIndexScaled = MGSN->isIndexScaled(); 9098 IsIndexSigned = MGSN->isIndexSigned(); 9099 } 9100 EVT IndexVT = Index.getValueType(); 9101 MVT XLenVT = Subtarget.getXLenVT(); 9102 // RISCV indexed loads only support the "unsigned unscaled" addressing 9103 // mode, so anything else must be manually legalized. 9104 bool NeedsIdxLegalization = 9105 IsIndexScaled || 9106 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 9107 if (!NeedsIdxLegalization) 9108 break; 9109 9110 SDLoc DL(N); 9111 9112 // Any index legalization should first promote to XLenVT, so we don't lose 9113 // bits when scaling. This may create an illegal index type so we let 9114 // LLVM's legalization take care of the splitting. 9115 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 9116 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 9117 IndexVT = IndexVT.changeVectorElementType(XLenVT); 9118 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 9119 DL, IndexVT, Index); 9120 } 9121 9122 if (IsIndexScaled) { 9123 // Manually scale the indices. 9124 // TODO: Sanitize the scale operand here? 9125 // TODO: For VP nodes, should we use VP_SHL here? 9126 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 9127 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 9128 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 9129 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 9130 ScaleOp = DAG.getTargetConstant(1, DL, ScaleOp.getValueType()); 9131 } 9132 9133 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_SCALED; 9134 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 9135 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 9136 {VPGN->getChain(), VPGN->getBasePtr(), Index, 9137 ScaleOp, VPGN->getMask(), 9138 VPGN->getVectorLength()}, 9139 VPGN->getMemOperand(), NewIndexTy); 9140 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 9141 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 9142 {VPSN->getChain(), VPSN->getValue(), 9143 VPSN->getBasePtr(), Index, ScaleOp, 9144 VPSN->getMask(), VPSN->getVectorLength()}, 9145 VPSN->getMemOperand(), NewIndexTy); 9146 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 9147 return DAG.getMaskedGather( 9148 N->getVTList(), MGN->getMemoryVT(), DL, 9149 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 9150 MGN->getBasePtr(), Index, ScaleOp}, 9151 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 9152 const auto *MSN = cast<MaskedScatterSDNode>(N); 9153 return DAG.getMaskedScatter( 9154 N->getVTList(), MSN->getMemoryVT(), DL, 9155 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 9156 Index, ScaleOp}, 9157 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 9158 } 9159 case RISCVISD::SRA_VL: 9160 case RISCVISD::SRL_VL: 9161 case RISCVISD::SHL_VL: { 9162 SDValue ShAmt = N->getOperand(1); 9163 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 9164 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 9165 SDLoc DL(N); 9166 SDValue VL = N->getOperand(3); 9167 EVT VT = N->getValueType(0); 9168 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 9169 ShAmt.getOperand(1), VL); 9170 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 9171 N->getOperand(2), N->getOperand(3)); 9172 } 9173 break; 9174 } 9175 case ISD::SRA: 9176 if (SDValue V = performSRACombine(N, DAG, Subtarget)) 9177 return V; 9178 LLVM_FALLTHROUGH; 9179 case ISD::SRL: 9180 case ISD::SHL: { 9181 SDValue ShAmt = N->getOperand(1); 9182 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 9183 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 9184 SDLoc DL(N); 9185 EVT VT = N->getValueType(0); 9186 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 9187 ShAmt.getOperand(1), 9188 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 9189 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 9190 } 9191 break; 9192 } 9193 case RISCVISD::ADD_VL: 9194 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 9195 return V; 9196 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 9197 case RISCVISD::SUB_VL: 9198 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 9199 case RISCVISD::VWADD_W_VL: 9200 case RISCVISD::VWADDU_W_VL: 9201 case RISCVISD::VWSUB_W_VL: 9202 case RISCVISD::VWSUBU_W_VL: 9203 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 9204 case RISCVISD::MUL_VL: 9205 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 9206 return V; 9207 // Mul is commutative. 9208 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 9209 case RISCVISD::VFMADD_VL: 9210 case RISCVISD::VFNMADD_VL: 9211 case RISCVISD::VFMSUB_VL: 9212 case RISCVISD::VFNMSUB_VL: { 9213 // Fold FNEG_VL into FMA opcodes. 9214 SDValue A = N->getOperand(0); 9215 SDValue B = N->getOperand(1); 9216 SDValue C = N->getOperand(2); 9217 SDValue Mask = N->getOperand(3); 9218 SDValue VL = N->getOperand(4); 9219 9220 auto invertIfNegative = [&Mask, &VL](SDValue &V) { 9221 if (V.getOpcode() == RISCVISD::FNEG_VL && V.getOperand(1) == Mask && 9222 V.getOperand(2) == VL) { 9223 // Return the negated input. 9224 V = V.getOperand(0); 9225 return true; 9226 } 9227 9228 return false; 9229 }; 9230 9231 bool NegA = invertIfNegative(A); 9232 bool NegB = invertIfNegative(B); 9233 bool NegC = invertIfNegative(C); 9234 9235 // If no operands are negated, we're done. 9236 if (!NegA && !NegB && !NegC) 9237 return SDValue(); 9238 9239 unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC); 9240 return DAG.getNode(NewOpcode, SDLoc(N), N->getValueType(0), A, B, C, Mask, 9241 VL); 9242 } 9243 case ISD::STORE: { 9244 auto *Store = cast<StoreSDNode>(N); 9245 SDValue Val = Store->getValue(); 9246 // Combine store of vmv.x.s to vse with VL of 1. 9247 // FIXME: Support FP. 9248 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 9249 SDValue Src = Val.getOperand(0); 9250 MVT VecVT = Src.getSimpleValueType(); 9251 EVT MemVT = Store->getMemoryVT(); 9252 // The memory VT and the element type must match. 9253 if (MemVT == VecVT.getVectorElementType()) { 9254 SDLoc DL(N); 9255 MVT MaskVT = getMaskTypeFor(VecVT); 9256 return DAG.getStoreVP( 9257 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 9258 DAG.getConstant(1, DL, MaskVT), 9259 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 9260 Store->getMemOperand(), Store->getAddressingMode(), 9261 Store->isTruncatingStore(), /*IsCompress*/ false); 9262 } 9263 } 9264 9265 break; 9266 } 9267 case ISD::SPLAT_VECTOR: { 9268 EVT VT = N->getValueType(0); 9269 // Only perform this combine on legal MVT types. 9270 if (!isTypeLegal(VT)) 9271 break; 9272 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 9273 DAG, Subtarget)) 9274 return Gather; 9275 break; 9276 } 9277 case RISCVISD::VMV_V_X_VL: { 9278 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 9279 // scalar input. 9280 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 9281 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 9282 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 9283 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 9284 return SDValue(N, 0); 9285 9286 break; 9287 } 9288 case ISD::INTRINSIC_WO_CHAIN: { 9289 unsigned IntNo = N->getConstantOperandVal(0); 9290 switch (IntNo) { 9291 // By default we do not combine any intrinsic. 9292 default: 9293 return SDValue(); 9294 case Intrinsic::riscv_vcpop: 9295 case Intrinsic::riscv_vcpop_mask: 9296 case Intrinsic::riscv_vfirst: 9297 case Intrinsic::riscv_vfirst_mask: { 9298 SDValue VL = N->getOperand(2); 9299 if (IntNo == Intrinsic::riscv_vcpop_mask || 9300 IntNo == Intrinsic::riscv_vfirst_mask) 9301 VL = N->getOperand(3); 9302 if (!isNullConstant(VL)) 9303 return SDValue(); 9304 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 9305 SDLoc DL(N); 9306 EVT VT = N->getValueType(0); 9307 if (IntNo == Intrinsic::riscv_vfirst || 9308 IntNo == Intrinsic::riscv_vfirst_mask) 9309 return DAG.getConstant(-1, DL, VT); 9310 return DAG.getConstant(0, DL, VT); 9311 } 9312 } 9313 } 9314 case ISD::BITCAST: { 9315 assert(Subtarget.useRVVForFixedLengthVectors()); 9316 SDValue N0 = N->getOperand(0); 9317 EVT VT = N->getValueType(0); 9318 EVT SrcVT = N0.getValueType(); 9319 // If this is a bitcast between a MVT::v4i1/v2i1/v1i1 and an illegal integer 9320 // type, widen both sides to avoid a trip through memory. 9321 if ((SrcVT == MVT::v1i1 || SrcVT == MVT::v2i1 || SrcVT == MVT::v4i1) && 9322 VT.isScalarInteger()) { 9323 unsigned NumConcats = 8 / SrcVT.getVectorNumElements(); 9324 SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT)); 9325 Ops[0] = N0; 9326 SDLoc DL(N); 9327 N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i1, Ops); 9328 N0 = DAG.getBitcast(MVT::i8, N0); 9329 return DAG.getNode(ISD::TRUNCATE, DL, VT, N0); 9330 } 9331 9332 return SDValue(); 9333 } 9334 } 9335 9336 return SDValue(); 9337 } 9338 9339 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 9340 const SDNode *N, CombineLevel Level) const { 9341 assert((N->getOpcode() == ISD::SHL || N->getOpcode() == ISD::SRA || 9342 N->getOpcode() == ISD::SRL) && 9343 "Expected shift op"); 9344 9345 // The following folds are only desirable if `(OP _, c1 << c2)` can be 9346 // materialised in fewer instructions than `(OP _, c1)`: 9347 // 9348 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 9349 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 9350 SDValue N0 = N->getOperand(0); 9351 EVT Ty = N0.getValueType(); 9352 if (Ty.isScalarInteger() && 9353 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 9354 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 9355 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9356 if (C1 && C2) { 9357 const APInt &C1Int = C1->getAPIntValue(); 9358 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 9359 9360 // We can materialise `c1 << c2` into an add immediate, so it's "free", 9361 // and the combine should happen, to potentially allow further combines 9362 // later. 9363 if (ShiftedC1Int.getMinSignedBits() <= 64 && 9364 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 9365 return true; 9366 9367 // We can materialise `c1` in an add immediate, so it's "free", and the 9368 // combine should be prevented. 9369 if (C1Int.getMinSignedBits() <= 64 && 9370 isLegalAddImmediate(C1Int.getSExtValue())) 9371 return false; 9372 9373 // Neither constant will fit into an immediate, so find materialisation 9374 // costs. 9375 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 9376 Subtarget.getFeatureBits(), 9377 /*CompressionCost*/true); 9378 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 9379 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 9380 /*CompressionCost*/true); 9381 9382 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 9383 // combine should be prevented. 9384 if (C1Cost < ShiftedC1Cost) 9385 return false; 9386 } 9387 } 9388 return true; 9389 } 9390 9391 bool RISCVTargetLowering::targetShrinkDemandedConstant( 9392 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 9393 TargetLoweringOpt &TLO) const { 9394 // Delay this optimization as late as possible. 9395 if (!TLO.LegalOps) 9396 return false; 9397 9398 EVT VT = Op.getValueType(); 9399 if (VT.isVector()) 9400 return false; 9401 9402 // Only handle AND for now. 9403 unsigned Opcode = Op.getOpcode(); 9404 if (Opcode != ISD::AND && Opcode != ISD::OR && Opcode != ISD::XOR) 9405 return false; 9406 9407 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 9408 if (!C) 9409 return false; 9410 9411 const APInt &Mask = C->getAPIntValue(); 9412 9413 // Clear all non-demanded bits initially. 9414 APInt ShrunkMask = Mask & DemandedBits; 9415 9416 // Try to make a smaller immediate by setting undemanded bits. 9417 9418 APInt ExpandedMask = Mask | ~DemandedBits; 9419 9420 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 9421 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 9422 }; 9423 auto UseMask = [Mask, Op, &TLO](const APInt &NewMask) -> bool { 9424 if (NewMask == Mask) 9425 return true; 9426 SDLoc DL(Op); 9427 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, Op.getValueType()); 9428 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), DL, Op.getValueType(), 9429 Op.getOperand(0), NewC); 9430 return TLO.CombineTo(Op, NewOp); 9431 }; 9432 9433 // If the shrunk mask fits in sign extended 12 bits, let the target 9434 // independent code apply it. 9435 if (ShrunkMask.isSignedIntN(12)) 9436 return false; 9437 9438 // And has a few special cases for zext. 9439 if (Opcode == ISD::AND) { 9440 // Preserve (and X, 0xffff) when zext.h is supported. 9441 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 9442 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 9443 if (IsLegalMask(NewMask)) 9444 return UseMask(NewMask); 9445 } 9446 9447 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 9448 if (VT == MVT::i64) { 9449 APInt NewMask = APInt(64, 0xffffffff); 9450 if (IsLegalMask(NewMask)) 9451 return UseMask(NewMask); 9452 } 9453 } 9454 9455 // For the remaining optimizations, we need to be able to make a negative 9456 // number through a combination of mask and undemanded bits. 9457 if (!ExpandedMask.isNegative()) 9458 return false; 9459 9460 // What is the fewest number of bits we need to represent the negative number. 9461 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 9462 9463 // Try to make a 12 bit negative immediate. If that fails try to make a 32 9464 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 9465 // If we can't create a simm12, we shouldn't change opaque constants. 9466 APInt NewMask = ShrunkMask; 9467 if (MinSignedBits <= 12) 9468 NewMask.setBitsFrom(11); 9469 else if (!C->isOpaque() && MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 9470 NewMask.setBitsFrom(31); 9471 else 9472 return false; 9473 9474 // Check that our new mask is a subset of the demanded mask. 9475 assert(IsLegalMask(NewMask)); 9476 return UseMask(NewMask); 9477 } 9478 9479 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) { 9480 static const uint64_t GREVMasks[] = { 9481 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 9482 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 9483 9484 for (unsigned Stage = 0; Stage != 6; ++Stage) { 9485 unsigned Shift = 1 << Stage; 9486 if (ShAmt & Shift) { 9487 uint64_t Mask = GREVMasks[Stage]; 9488 uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask); 9489 if (IsGORC) 9490 Res |= x; 9491 x = Res; 9492 } 9493 } 9494 9495 return x; 9496 } 9497 9498 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 9499 KnownBits &Known, 9500 const APInt &DemandedElts, 9501 const SelectionDAG &DAG, 9502 unsigned Depth) const { 9503 unsigned BitWidth = Known.getBitWidth(); 9504 unsigned Opc = Op.getOpcode(); 9505 assert((Opc >= ISD::BUILTIN_OP_END || 9506 Opc == ISD::INTRINSIC_WO_CHAIN || 9507 Opc == ISD::INTRINSIC_W_CHAIN || 9508 Opc == ISD::INTRINSIC_VOID) && 9509 "Should use MaskedValueIsZero if you don't know whether Op" 9510 " is a target node!"); 9511 9512 Known.resetAll(); 9513 switch (Opc) { 9514 default: break; 9515 case RISCVISD::SELECT_CC: { 9516 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 9517 // If we don't know any bits, early out. 9518 if (Known.isUnknown()) 9519 break; 9520 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 9521 9522 // Only known if known in both the LHS and RHS. 9523 Known = KnownBits::commonBits(Known, Known2); 9524 break; 9525 } 9526 case RISCVISD::REMUW: { 9527 KnownBits Known2; 9528 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9529 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9530 // We only care about the lower 32 bits. 9531 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 9532 // Restore the original width by sign extending. 9533 Known = Known.sext(BitWidth); 9534 break; 9535 } 9536 case RISCVISD::DIVUW: { 9537 KnownBits Known2; 9538 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9539 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9540 // We only care about the lower 32 bits. 9541 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 9542 // Restore the original width by sign extending. 9543 Known = Known.sext(BitWidth); 9544 break; 9545 } 9546 case RISCVISD::CTZW: { 9547 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9548 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 9549 unsigned LowBits = Log2_32(PossibleTZ) + 1; 9550 Known.Zero.setBitsFrom(LowBits); 9551 break; 9552 } 9553 case RISCVISD::CLZW: { 9554 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9555 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 9556 unsigned LowBits = Log2_32(PossibleLZ) + 1; 9557 Known.Zero.setBitsFrom(LowBits); 9558 break; 9559 } 9560 case RISCVISD::GREV: 9561 case RISCVISD::GORC: { 9562 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 9563 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9564 unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1); 9565 bool IsGORC = Op.getOpcode() == RISCVISD::GORC; 9566 // To compute zeros, we need to invert the value and invert it back after. 9567 Known.Zero = 9568 ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC); 9569 Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC); 9570 } 9571 break; 9572 } 9573 case RISCVISD::READ_VLENB: { 9574 // We can use the minimum and maximum VLEN values to bound VLENB. We 9575 // know VLEN must be a power of two. 9576 const unsigned MinVLenB = Subtarget.getRealMinVLen() / 8; 9577 const unsigned MaxVLenB = Subtarget.getRealMaxVLen() / 8; 9578 assert(MinVLenB > 0 && "READ_VLENB without vector extension enabled?"); 9579 Known.Zero.setLowBits(Log2_32(MinVLenB)); 9580 Known.Zero.setBitsFrom(Log2_32(MaxVLenB)+1); 9581 if (MaxVLenB == MinVLenB) 9582 Known.One.setBit(Log2_32(MinVLenB)); 9583 break; 9584 } 9585 case ISD::INTRINSIC_W_CHAIN: 9586 case ISD::INTRINSIC_WO_CHAIN: { 9587 unsigned IntNo = 9588 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 9589 switch (IntNo) { 9590 default: 9591 // We can't do anything for most intrinsics. 9592 break; 9593 case Intrinsic::riscv_vsetvli: 9594 case Intrinsic::riscv_vsetvlimax: 9595 case Intrinsic::riscv_vsetvli_opt: 9596 case Intrinsic::riscv_vsetvlimax_opt: 9597 // Assume that VL output is positive and would fit in an int32_t. 9598 // TODO: VLEN might be capped at 16 bits in a future V spec update. 9599 if (BitWidth >= 32) 9600 Known.Zero.setBitsFrom(31); 9601 break; 9602 } 9603 break; 9604 } 9605 } 9606 } 9607 9608 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 9609 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 9610 unsigned Depth) const { 9611 switch (Op.getOpcode()) { 9612 default: 9613 break; 9614 case RISCVISD::SELECT_CC: { 9615 unsigned Tmp = 9616 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 9617 if (Tmp == 1) return 1; // Early out. 9618 unsigned Tmp2 = 9619 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 9620 return std::min(Tmp, Tmp2); 9621 } 9622 case RISCVISD::SLLW: 9623 case RISCVISD::SRAW: 9624 case RISCVISD::SRLW: 9625 case RISCVISD::DIVW: 9626 case RISCVISD::DIVUW: 9627 case RISCVISD::REMUW: 9628 case RISCVISD::ROLW: 9629 case RISCVISD::RORW: 9630 case RISCVISD::GREVW: 9631 case RISCVISD::GORCW: 9632 case RISCVISD::FSLW: 9633 case RISCVISD::FSRW: 9634 case RISCVISD::SHFLW: 9635 case RISCVISD::UNSHFLW: 9636 case RISCVISD::BCOMPRESSW: 9637 case RISCVISD::BDECOMPRESSW: 9638 case RISCVISD::BFPW: 9639 case RISCVISD::FCVT_W_RV64: 9640 case RISCVISD::FCVT_WU_RV64: 9641 case RISCVISD::STRICT_FCVT_W_RV64: 9642 case RISCVISD::STRICT_FCVT_WU_RV64: 9643 // TODO: As the result is sign-extended, this is conservatively correct. A 9644 // more precise answer could be calculated for SRAW depending on known 9645 // bits in the shift amount. 9646 return 33; 9647 case RISCVISD::SHFL: 9648 case RISCVISD::UNSHFL: { 9649 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 9650 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 9651 // will stay within the upper 32 bits. If there were more than 32 sign bits 9652 // before there will be at least 33 sign bits after. 9653 if (Op.getValueType() == MVT::i64 && 9654 isa<ConstantSDNode>(Op.getOperand(1)) && 9655 (Op.getConstantOperandVal(1) & 0x10) == 0) { 9656 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 9657 if (Tmp > 32) 9658 return 33; 9659 } 9660 break; 9661 } 9662 case RISCVISD::VMV_X_S: { 9663 // The number of sign bits of the scalar result is computed by obtaining the 9664 // element type of the input vector operand, subtracting its width from the 9665 // XLEN, and then adding one (sign bit within the element type). If the 9666 // element type is wider than XLen, the least-significant XLEN bits are 9667 // taken. 9668 unsigned XLen = Subtarget.getXLen(); 9669 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 9670 if (EltBits <= XLen) 9671 return XLen - EltBits + 1; 9672 break; 9673 } 9674 } 9675 9676 return 1; 9677 } 9678 9679 const Constant * 9680 RISCVTargetLowering::getTargetConstantFromLoad(LoadSDNode *Ld) const { 9681 assert(Ld && "Unexpected null LoadSDNode"); 9682 if (!ISD::isNormalLoad(Ld)) 9683 return nullptr; 9684 9685 SDValue Ptr = Ld->getBasePtr(); 9686 9687 // Only constant pools with no offset are supported. 9688 auto GetSupportedConstantPool = [](SDValue Ptr) -> ConstantPoolSDNode * { 9689 auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr); 9690 if (!CNode || CNode->isMachineConstantPoolEntry() || 9691 CNode->getOffset() != 0) 9692 return nullptr; 9693 9694 return CNode; 9695 }; 9696 9697 // Simple case, LLA. 9698 if (Ptr.getOpcode() == RISCVISD::LLA) { 9699 auto *CNode = GetSupportedConstantPool(Ptr); 9700 if (!CNode || CNode->getTargetFlags() != 0) 9701 return nullptr; 9702 9703 return CNode->getConstVal(); 9704 } 9705 9706 // Look for a HI and ADD_LO pair. 9707 if (Ptr.getOpcode() != RISCVISD::ADD_LO || 9708 Ptr.getOperand(0).getOpcode() != RISCVISD::HI) 9709 return nullptr; 9710 9711 auto *CNodeLo = GetSupportedConstantPool(Ptr.getOperand(1)); 9712 auto *CNodeHi = GetSupportedConstantPool(Ptr.getOperand(0).getOperand(0)); 9713 9714 if (!CNodeLo || CNodeLo->getTargetFlags() != RISCVII::MO_LO || 9715 !CNodeHi || CNodeHi->getTargetFlags() != RISCVII::MO_HI) 9716 return nullptr; 9717 9718 if (CNodeLo->getConstVal() != CNodeHi->getConstVal()) 9719 return nullptr; 9720 9721 return CNodeLo->getConstVal(); 9722 } 9723 9724 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 9725 MachineBasicBlock *BB) { 9726 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 9727 9728 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 9729 // Should the count have wrapped while it was being read, we need to try 9730 // again. 9731 // ... 9732 // read: 9733 // rdcycleh x3 # load high word of cycle 9734 // rdcycle x2 # load low word of cycle 9735 // rdcycleh x4 # load high word of cycle 9736 // bne x3, x4, read # check if high word reads match, otherwise try again 9737 // ... 9738 9739 MachineFunction &MF = *BB->getParent(); 9740 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9741 MachineFunction::iterator It = ++BB->getIterator(); 9742 9743 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9744 MF.insert(It, LoopMBB); 9745 9746 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9747 MF.insert(It, DoneMBB); 9748 9749 // Transfer the remainder of BB and its successor edges to DoneMBB. 9750 DoneMBB->splice(DoneMBB->begin(), BB, 9751 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9752 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 9753 9754 BB->addSuccessor(LoopMBB); 9755 9756 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9757 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9758 Register LoReg = MI.getOperand(0).getReg(); 9759 Register HiReg = MI.getOperand(1).getReg(); 9760 DebugLoc DL = MI.getDebugLoc(); 9761 9762 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 9763 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 9764 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9765 .addReg(RISCV::X0); 9766 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 9767 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 9768 .addReg(RISCV::X0); 9769 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 9770 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9771 .addReg(RISCV::X0); 9772 9773 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 9774 .addReg(HiReg) 9775 .addReg(ReadAgainReg) 9776 .addMBB(LoopMBB); 9777 9778 LoopMBB->addSuccessor(LoopMBB); 9779 LoopMBB->addSuccessor(DoneMBB); 9780 9781 MI.eraseFromParent(); 9782 9783 return DoneMBB; 9784 } 9785 9786 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9787 MachineBasicBlock *BB) { 9788 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9789 9790 MachineFunction &MF = *BB->getParent(); 9791 DebugLoc DL = MI.getDebugLoc(); 9792 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9793 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9794 Register LoReg = MI.getOperand(0).getReg(); 9795 Register HiReg = MI.getOperand(1).getReg(); 9796 Register SrcReg = MI.getOperand(2).getReg(); 9797 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9798 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9799 9800 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9801 RI); 9802 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9803 MachineMemOperand *MMOLo = 9804 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9805 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9806 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9807 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9808 .addFrameIndex(FI) 9809 .addImm(0) 9810 .addMemOperand(MMOLo); 9811 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9812 .addFrameIndex(FI) 9813 .addImm(4) 9814 .addMemOperand(MMOHi); 9815 MI.eraseFromParent(); // The pseudo instruction is gone now. 9816 return BB; 9817 } 9818 9819 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9820 MachineBasicBlock *BB) { 9821 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9822 "Unexpected instruction"); 9823 9824 MachineFunction &MF = *BB->getParent(); 9825 DebugLoc DL = MI.getDebugLoc(); 9826 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9827 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9828 Register DstReg = MI.getOperand(0).getReg(); 9829 Register LoReg = MI.getOperand(1).getReg(); 9830 Register HiReg = MI.getOperand(2).getReg(); 9831 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9832 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9833 9834 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9835 MachineMemOperand *MMOLo = 9836 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9837 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9838 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9839 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9840 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9841 .addFrameIndex(FI) 9842 .addImm(0) 9843 .addMemOperand(MMOLo); 9844 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9845 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9846 .addFrameIndex(FI) 9847 .addImm(4) 9848 .addMemOperand(MMOHi); 9849 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9850 MI.eraseFromParent(); // The pseudo instruction is gone now. 9851 return BB; 9852 } 9853 9854 static bool isSelectPseudo(MachineInstr &MI) { 9855 switch (MI.getOpcode()) { 9856 default: 9857 return false; 9858 case RISCV::Select_GPR_Using_CC_GPR: 9859 case RISCV::Select_FPR16_Using_CC_GPR: 9860 case RISCV::Select_FPR32_Using_CC_GPR: 9861 case RISCV::Select_FPR64_Using_CC_GPR: 9862 return true; 9863 } 9864 } 9865 9866 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9867 unsigned RelOpcode, unsigned EqOpcode, 9868 const RISCVSubtarget &Subtarget) { 9869 DebugLoc DL = MI.getDebugLoc(); 9870 Register DstReg = MI.getOperand(0).getReg(); 9871 Register Src1Reg = MI.getOperand(1).getReg(); 9872 Register Src2Reg = MI.getOperand(2).getReg(); 9873 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9874 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9875 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9876 9877 // Save the current FFLAGS. 9878 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9879 9880 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9881 .addReg(Src1Reg) 9882 .addReg(Src2Reg); 9883 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9884 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9885 9886 // Restore the FFLAGS. 9887 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9888 .addReg(SavedFFlags, RegState::Kill); 9889 9890 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9891 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9892 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9893 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9894 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9895 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9896 9897 // Erase the pseudoinstruction. 9898 MI.eraseFromParent(); 9899 return BB; 9900 } 9901 9902 static MachineBasicBlock * 9903 EmitLoweredCascadedSelect(MachineInstr &First, MachineInstr &Second, 9904 MachineBasicBlock *ThisMBB, 9905 const RISCVSubtarget &Subtarget) { 9906 // Select_FPRX_ (rs1, rs2, imm, rs4, (Select_FPRX_ rs1, rs2, imm, rs4, rs5) 9907 // Without this, custom-inserter would have generated: 9908 // 9909 // A 9910 // | \ 9911 // | B 9912 // | / 9913 // C 9914 // | \ 9915 // | D 9916 // | / 9917 // E 9918 // 9919 // A: X = ...; Y = ... 9920 // B: empty 9921 // C: Z = PHI [X, A], [Y, B] 9922 // D: empty 9923 // E: PHI [X, C], [Z, D] 9924 // 9925 // If we lower both Select_FPRX_ in a single step, we can instead generate: 9926 // 9927 // A 9928 // | \ 9929 // | C 9930 // | /| 9931 // |/ | 9932 // | | 9933 // | D 9934 // | / 9935 // E 9936 // 9937 // A: X = ...; Y = ... 9938 // D: empty 9939 // E: PHI [X, A], [X, C], [Y, D] 9940 9941 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9942 const DebugLoc &DL = First.getDebugLoc(); 9943 const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock(); 9944 MachineFunction *F = ThisMBB->getParent(); 9945 MachineBasicBlock *FirstMBB = F->CreateMachineBasicBlock(LLVM_BB); 9946 MachineBasicBlock *SecondMBB = F->CreateMachineBasicBlock(LLVM_BB); 9947 MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9948 MachineFunction::iterator It = ++ThisMBB->getIterator(); 9949 F->insert(It, FirstMBB); 9950 F->insert(It, SecondMBB); 9951 F->insert(It, SinkMBB); 9952 9953 // Transfer the remainder of ThisMBB and its successor edges to SinkMBB. 9954 SinkMBB->splice(SinkMBB->begin(), ThisMBB, 9955 std::next(MachineBasicBlock::iterator(First)), 9956 ThisMBB->end()); 9957 SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB); 9958 9959 // Fallthrough block for ThisMBB. 9960 ThisMBB->addSuccessor(FirstMBB); 9961 // Fallthrough block for FirstMBB. 9962 FirstMBB->addSuccessor(SecondMBB); 9963 ThisMBB->addSuccessor(SinkMBB); 9964 FirstMBB->addSuccessor(SinkMBB); 9965 // This is fallthrough. 9966 SecondMBB->addSuccessor(SinkMBB); 9967 9968 auto FirstCC = static_cast<RISCVCC::CondCode>(First.getOperand(3).getImm()); 9969 Register FLHS = First.getOperand(1).getReg(); 9970 Register FRHS = First.getOperand(2).getReg(); 9971 // Insert appropriate branch. 9972 BuildMI(FirstMBB, DL, TII.getBrCond(FirstCC)) 9973 .addReg(FLHS) 9974 .addReg(FRHS) 9975 .addMBB(SinkMBB); 9976 9977 Register SLHS = Second.getOperand(1).getReg(); 9978 Register SRHS = Second.getOperand(2).getReg(); 9979 Register Op1Reg4 = First.getOperand(4).getReg(); 9980 Register Op1Reg5 = First.getOperand(5).getReg(); 9981 9982 auto SecondCC = static_cast<RISCVCC::CondCode>(Second.getOperand(3).getImm()); 9983 // Insert appropriate branch. 9984 BuildMI(ThisMBB, DL, TII.getBrCond(SecondCC)) 9985 .addReg(SLHS) 9986 .addReg(SRHS) 9987 .addMBB(SinkMBB); 9988 9989 Register DestReg = Second.getOperand(0).getReg(); 9990 Register Op2Reg4 = Second.getOperand(4).getReg(); 9991 BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII.get(RISCV::PHI), DestReg) 9992 .addReg(Op2Reg4) 9993 .addMBB(ThisMBB) 9994 .addReg(Op1Reg4) 9995 .addMBB(FirstMBB) 9996 .addReg(Op1Reg5) 9997 .addMBB(SecondMBB); 9998 9999 // Now remove the Select_FPRX_s. 10000 First.eraseFromParent(); 10001 Second.eraseFromParent(); 10002 return SinkMBB; 10003 } 10004 10005 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 10006 MachineBasicBlock *BB, 10007 const RISCVSubtarget &Subtarget) { 10008 // To "insert" Select_* instructions, we actually have to insert the triangle 10009 // control-flow pattern. The incoming instructions know the destination vreg 10010 // to set, the condition code register to branch on, the true/false values to 10011 // select between, and the condcode to use to select the appropriate branch. 10012 // 10013 // We produce the following control flow: 10014 // HeadMBB 10015 // | \ 10016 // | IfFalseMBB 10017 // | / 10018 // TailMBB 10019 // 10020 // When we find a sequence of selects we attempt to optimize their emission 10021 // by sharing the control flow. Currently we only handle cases where we have 10022 // multiple selects with the exact same condition (same LHS, RHS and CC). 10023 // The selects may be interleaved with other instructions if the other 10024 // instructions meet some requirements we deem safe: 10025 // - They are debug instructions. Otherwise, 10026 // - They do not have side-effects, do not access memory and their inputs do 10027 // not depend on the results of the select pseudo-instructions. 10028 // The TrueV/FalseV operands of the selects cannot depend on the result of 10029 // previous selects in the sequence. 10030 // These conditions could be further relaxed. See the X86 target for a 10031 // related approach and more information. 10032 // 10033 // Select_FPRX_ (rs1, rs2, imm, rs4, (Select_FPRX_ rs1, rs2, imm, rs4, rs5)) 10034 // is checked here and handled by a separate function - 10035 // EmitLoweredCascadedSelect. 10036 Register LHS = MI.getOperand(1).getReg(); 10037 Register RHS = MI.getOperand(2).getReg(); 10038 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 10039 10040 SmallVector<MachineInstr *, 4> SelectDebugValues; 10041 SmallSet<Register, 4> SelectDests; 10042 SelectDests.insert(MI.getOperand(0).getReg()); 10043 10044 MachineInstr *LastSelectPseudo = &MI; 10045 auto Next = next_nodbg(MI.getIterator(), BB->instr_end()); 10046 if (MI.getOpcode() != RISCV::Select_GPR_Using_CC_GPR && Next != BB->end() && 10047 Next->getOpcode() == MI.getOpcode() && 10048 Next->getOperand(5).getReg() == MI.getOperand(0).getReg() && 10049 Next->getOperand(5).isKill()) { 10050 return EmitLoweredCascadedSelect(MI, *Next, BB, Subtarget); 10051 } 10052 10053 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 10054 SequenceMBBI != E; ++SequenceMBBI) { 10055 if (SequenceMBBI->isDebugInstr()) 10056 continue; 10057 if (isSelectPseudo(*SequenceMBBI)) { 10058 if (SequenceMBBI->getOperand(1).getReg() != LHS || 10059 SequenceMBBI->getOperand(2).getReg() != RHS || 10060 SequenceMBBI->getOperand(3).getImm() != CC || 10061 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 10062 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 10063 break; 10064 LastSelectPseudo = &*SequenceMBBI; 10065 SequenceMBBI->collectDebugValues(SelectDebugValues); 10066 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 10067 } else { 10068 if (SequenceMBBI->hasUnmodeledSideEffects() || 10069 SequenceMBBI->mayLoadOrStore()) 10070 break; 10071 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 10072 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 10073 })) 10074 break; 10075 } 10076 } 10077 10078 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 10079 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10080 DebugLoc DL = MI.getDebugLoc(); 10081 MachineFunction::iterator I = ++BB->getIterator(); 10082 10083 MachineBasicBlock *HeadMBB = BB; 10084 MachineFunction *F = BB->getParent(); 10085 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 10086 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 10087 10088 F->insert(I, IfFalseMBB); 10089 F->insert(I, TailMBB); 10090 10091 // Transfer debug instructions associated with the selects to TailMBB. 10092 for (MachineInstr *DebugInstr : SelectDebugValues) { 10093 TailMBB->push_back(DebugInstr->removeFromParent()); 10094 } 10095 10096 // Move all instructions after the sequence to TailMBB. 10097 TailMBB->splice(TailMBB->end(), HeadMBB, 10098 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 10099 // Update machine-CFG edges by transferring all successors of the current 10100 // block to the new block which will contain the Phi nodes for the selects. 10101 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 10102 // Set the successors for HeadMBB. 10103 HeadMBB->addSuccessor(IfFalseMBB); 10104 HeadMBB->addSuccessor(TailMBB); 10105 10106 // Insert appropriate branch. 10107 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 10108 .addReg(LHS) 10109 .addReg(RHS) 10110 .addMBB(TailMBB); 10111 10112 // IfFalseMBB just falls through to TailMBB. 10113 IfFalseMBB->addSuccessor(TailMBB); 10114 10115 // Create PHIs for all of the select pseudo-instructions. 10116 auto SelectMBBI = MI.getIterator(); 10117 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 10118 auto InsertionPoint = TailMBB->begin(); 10119 while (SelectMBBI != SelectEnd) { 10120 auto Next = std::next(SelectMBBI); 10121 if (isSelectPseudo(*SelectMBBI)) { 10122 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 10123 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 10124 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 10125 .addReg(SelectMBBI->getOperand(4).getReg()) 10126 .addMBB(HeadMBB) 10127 .addReg(SelectMBBI->getOperand(5).getReg()) 10128 .addMBB(IfFalseMBB); 10129 SelectMBBI->eraseFromParent(); 10130 } 10131 SelectMBBI = Next; 10132 } 10133 10134 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 10135 return TailMBB; 10136 } 10137 10138 MachineBasicBlock * 10139 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10140 MachineBasicBlock *BB) const { 10141 switch (MI.getOpcode()) { 10142 default: 10143 llvm_unreachable("Unexpected instr type to insert"); 10144 case RISCV::ReadCycleWide: 10145 assert(!Subtarget.is64Bit() && 10146 "ReadCycleWrite is only to be used on riscv32"); 10147 return emitReadCycleWidePseudo(MI, BB); 10148 case RISCV::Select_GPR_Using_CC_GPR: 10149 case RISCV::Select_FPR16_Using_CC_GPR: 10150 case RISCV::Select_FPR32_Using_CC_GPR: 10151 case RISCV::Select_FPR64_Using_CC_GPR: 10152 return emitSelectPseudo(MI, BB, Subtarget); 10153 case RISCV::BuildPairF64Pseudo: 10154 return emitBuildPairF64Pseudo(MI, BB); 10155 case RISCV::SplitF64Pseudo: 10156 return emitSplitF64Pseudo(MI, BB); 10157 case RISCV::PseudoQuietFLE_H: 10158 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 10159 case RISCV::PseudoQuietFLT_H: 10160 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 10161 case RISCV::PseudoQuietFLE_S: 10162 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 10163 case RISCV::PseudoQuietFLT_S: 10164 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 10165 case RISCV::PseudoQuietFLE_D: 10166 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 10167 case RISCV::PseudoQuietFLT_D: 10168 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 10169 } 10170 } 10171 10172 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10173 SDNode *Node) const { 10174 // Add FRM dependency to any instructions with dynamic rounding mode. 10175 unsigned Opc = MI.getOpcode(); 10176 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 10177 if (Idx < 0) 10178 return; 10179 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 10180 return; 10181 // If the instruction already reads FRM, don't add another read. 10182 if (MI.readsRegister(RISCV::FRM)) 10183 return; 10184 MI.addOperand( 10185 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 10186 } 10187 10188 // Calling Convention Implementation. 10189 // The expectations for frontend ABI lowering vary from target to target. 10190 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 10191 // details, but this is a longer term goal. For now, we simply try to keep the 10192 // role of the frontend as simple and well-defined as possible. The rules can 10193 // be summarised as: 10194 // * Never split up large scalar arguments. We handle them here. 10195 // * If a hardfloat calling convention is being used, and the struct may be 10196 // passed in a pair of registers (fp+fp, int+fp), and both registers are 10197 // available, then pass as two separate arguments. If either the GPRs or FPRs 10198 // are exhausted, then pass according to the rule below. 10199 // * If a struct could never be passed in registers or directly in a stack 10200 // slot (as it is larger than 2*XLEN and the floating point rules don't 10201 // apply), then pass it using a pointer with the byval attribute. 10202 // * If a struct is less than 2*XLEN, then coerce to either a two-element 10203 // word-sized array or a 2*XLEN scalar (depending on alignment). 10204 // * The frontend can determine whether a struct is returned by reference or 10205 // not based on its size and fields. If it will be returned by reference, the 10206 // frontend must modify the prototype so a pointer with the sret annotation is 10207 // passed as the first argument. This is not necessary for large scalar 10208 // returns. 10209 // * Struct return values and varargs should be coerced to structs containing 10210 // register-size fields in the same situations they would be for fixed 10211 // arguments. 10212 10213 static const MCPhysReg ArgGPRs[] = { 10214 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 10215 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 10216 }; 10217 static const MCPhysReg ArgFPR16s[] = { 10218 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 10219 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 10220 }; 10221 static const MCPhysReg ArgFPR32s[] = { 10222 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 10223 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 10224 }; 10225 static const MCPhysReg ArgFPR64s[] = { 10226 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 10227 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 10228 }; 10229 // This is an interim calling convention and it may be changed in the future. 10230 static const MCPhysReg ArgVRs[] = { 10231 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 10232 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 10233 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 10234 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 10235 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 10236 RISCV::V20M2, RISCV::V22M2}; 10237 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 10238 RISCV::V20M4}; 10239 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 10240 10241 // Pass a 2*XLEN argument that has been split into two XLEN values through 10242 // registers or the stack as necessary. 10243 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 10244 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 10245 MVT ValVT2, MVT LocVT2, 10246 ISD::ArgFlagsTy ArgFlags2) { 10247 unsigned XLenInBytes = XLen / 8; 10248 if (Register Reg = State.AllocateReg(ArgGPRs)) { 10249 // At least one half can be passed via register. 10250 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 10251 VA1.getLocVT(), CCValAssign::Full)); 10252 } else { 10253 // Both halves must be passed on the stack, with proper alignment. 10254 Align StackAlign = 10255 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 10256 State.addLoc( 10257 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 10258 State.AllocateStack(XLenInBytes, StackAlign), 10259 VA1.getLocVT(), CCValAssign::Full)); 10260 State.addLoc(CCValAssign::getMem( 10261 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 10262 LocVT2, CCValAssign::Full)); 10263 return false; 10264 } 10265 10266 if (Register Reg = State.AllocateReg(ArgGPRs)) { 10267 // The second half can also be passed via register. 10268 State.addLoc( 10269 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 10270 } else { 10271 // The second half is passed via the stack, without additional alignment. 10272 State.addLoc(CCValAssign::getMem( 10273 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 10274 LocVT2, CCValAssign::Full)); 10275 } 10276 10277 return false; 10278 } 10279 10280 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 10281 Optional<unsigned> FirstMaskArgument, 10282 CCState &State, const RISCVTargetLowering &TLI) { 10283 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 10284 if (RC == &RISCV::VRRegClass) { 10285 // Assign the first mask argument to V0. 10286 // This is an interim calling convention and it may be changed in the 10287 // future. 10288 if (FirstMaskArgument && ValNo == *FirstMaskArgument) 10289 return State.AllocateReg(RISCV::V0); 10290 return State.AllocateReg(ArgVRs); 10291 } 10292 if (RC == &RISCV::VRM2RegClass) 10293 return State.AllocateReg(ArgVRM2s); 10294 if (RC == &RISCV::VRM4RegClass) 10295 return State.AllocateReg(ArgVRM4s); 10296 if (RC == &RISCV::VRM8RegClass) 10297 return State.AllocateReg(ArgVRM8s); 10298 llvm_unreachable("Unhandled register class for ValueType"); 10299 } 10300 10301 // Implements the RISC-V calling convention. Returns true upon failure. 10302 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 10303 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 10304 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 10305 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 10306 Optional<unsigned> FirstMaskArgument) { 10307 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 10308 assert(XLen == 32 || XLen == 64); 10309 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 10310 10311 // Any return value split in to more than two values can't be returned 10312 // directly. Vectors are returned via the available vector registers. 10313 if (!LocVT.isVector() && IsRet && ValNo > 1) 10314 return true; 10315 10316 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 10317 // variadic argument, or if no F16/F32 argument registers are available. 10318 bool UseGPRForF16_F32 = true; 10319 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 10320 // variadic argument, or if no F64 argument registers are available. 10321 bool UseGPRForF64 = true; 10322 10323 switch (ABI) { 10324 default: 10325 llvm_unreachable("Unexpected ABI"); 10326 case RISCVABI::ABI_ILP32: 10327 case RISCVABI::ABI_LP64: 10328 break; 10329 case RISCVABI::ABI_ILP32F: 10330 case RISCVABI::ABI_LP64F: 10331 UseGPRForF16_F32 = !IsFixed; 10332 break; 10333 case RISCVABI::ABI_ILP32D: 10334 case RISCVABI::ABI_LP64D: 10335 UseGPRForF16_F32 = !IsFixed; 10336 UseGPRForF64 = !IsFixed; 10337 break; 10338 } 10339 10340 // FPR16, FPR32, and FPR64 alias each other. 10341 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 10342 UseGPRForF16_F32 = true; 10343 UseGPRForF64 = true; 10344 } 10345 10346 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 10347 // similar local variables rather than directly checking against the target 10348 // ABI. 10349 10350 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 10351 LocVT = XLenVT; 10352 LocInfo = CCValAssign::BCvt; 10353 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 10354 LocVT = MVT::i64; 10355 LocInfo = CCValAssign::BCvt; 10356 } 10357 10358 // If this is a variadic argument, the RISC-V calling convention requires 10359 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 10360 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 10361 // be used regardless of whether the original argument was split during 10362 // legalisation or not. The argument will not be passed by registers if the 10363 // original type is larger than 2*XLEN, so the register alignment rule does 10364 // not apply. 10365 unsigned TwoXLenInBytes = (2 * XLen) / 8; 10366 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 10367 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 10368 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 10369 // Skip 'odd' register if necessary. 10370 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 10371 State.AllocateReg(ArgGPRs); 10372 } 10373 10374 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 10375 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 10376 State.getPendingArgFlags(); 10377 10378 assert(PendingLocs.size() == PendingArgFlags.size() && 10379 "PendingLocs and PendingArgFlags out of sync"); 10380 10381 // Handle passing f64 on RV32D with a soft float ABI or when floating point 10382 // registers are exhausted. 10383 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 10384 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 10385 "Can't lower f64 if it is split"); 10386 // Depending on available argument GPRS, f64 may be passed in a pair of 10387 // GPRs, split between a GPR and the stack, or passed completely on the 10388 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 10389 // cases. 10390 Register Reg = State.AllocateReg(ArgGPRs); 10391 LocVT = MVT::i32; 10392 if (!Reg) { 10393 unsigned StackOffset = State.AllocateStack(8, Align(8)); 10394 State.addLoc( 10395 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10396 return false; 10397 } 10398 if (!State.AllocateReg(ArgGPRs)) 10399 State.AllocateStack(4, Align(4)); 10400 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10401 return false; 10402 } 10403 10404 // Fixed-length vectors are located in the corresponding scalable-vector 10405 // container types. 10406 if (ValVT.isFixedLengthVector()) 10407 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10408 10409 // Split arguments might be passed indirectly, so keep track of the pending 10410 // values. Split vectors are passed via a mix of registers and indirectly, so 10411 // treat them as we would any other argument. 10412 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 10413 LocVT = XLenVT; 10414 LocInfo = CCValAssign::Indirect; 10415 PendingLocs.push_back( 10416 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 10417 PendingArgFlags.push_back(ArgFlags); 10418 if (!ArgFlags.isSplitEnd()) { 10419 return false; 10420 } 10421 } 10422 10423 // If the split argument only had two elements, it should be passed directly 10424 // in registers or on the stack. 10425 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 10426 PendingLocs.size() <= 2) { 10427 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 10428 // Apply the normal calling convention rules to the first half of the 10429 // split argument. 10430 CCValAssign VA = PendingLocs[0]; 10431 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 10432 PendingLocs.clear(); 10433 PendingArgFlags.clear(); 10434 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 10435 ArgFlags); 10436 } 10437 10438 // Allocate to a register if possible, or else a stack slot. 10439 Register Reg; 10440 unsigned StoreSizeBytes = XLen / 8; 10441 Align StackAlign = Align(XLen / 8); 10442 10443 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 10444 Reg = State.AllocateReg(ArgFPR16s); 10445 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 10446 Reg = State.AllocateReg(ArgFPR32s); 10447 else if (ValVT == MVT::f64 && !UseGPRForF64) 10448 Reg = State.AllocateReg(ArgFPR64s); 10449 else if (ValVT.isVector()) { 10450 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 10451 if (!Reg) { 10452 // For return values, the vector must be passed fully via registers or 10453 // via the stack. 10454 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 10455 // but we're using all of them. 10456 if (IsRet) 10457 return true; 10458 // Try using a GPR to pass the address 10459 if ((Reg = State.AllocateReg(ArgGPRs))) { 10460 LocVT = XLenVT; 10461 LocInfo = CCValAssign::Indirect; 10462 } else if (ValVT.isScalableVector()) { 10463 LocVT = XLenVT; 10464 LocInfo = CCValAssign::Indirect; 10465 } else { 10466 // Pass fixed-length vectors on the stack. 10467 LocVT = ValVT; 10468 StoreSizeBytes = ValVT.getStoreSize(); 10469 // Align vectors to their element sizes, being careful for vXi1 10470 // vectors. 10471 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10472 } 10473 } 10474 } else { 10475 Reg = State.AllocateReg(ArgGPRs); 10476 } 10477 10478 unsigned StackOffset = 10479 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 10480 10481 // If we reach this point and PendingLocs is non-empty, we must be at the 10482 // end of a split argument that must be passed indirectly. 10483 if (!PendingLocs.empty()) { 10484 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 10485 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 10486 10487 for (auto &It : PendingLocs) { 10488 if (Reg) 10489 It.convertToReg(Reg); 10490 else 10491 It.convertToMem(StackOffset); 10492 State.addLoc(It); 10493 } 10494 PendingLocs.clear(); 10495 PendingArgFlags.clear(); 10496 return false; 10497 } 10498 10499 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 10500 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 10501 "Expected an XLenVT or vector types at this stage"); 10502 10503 if (Reg) { 10504 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10505 return false; 10506 } 10507 10508 // When a floating-point value is passed on the stack, no bit-conversion is 10509 // needed. 10510 if (ValVT.isFloatingPoint()) { 10511 LocVT = ValVT; 10512 LocInfo = CCValAssign::Full; 10513 } 10514 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10515 return false; 10516 } 10517 10518 template <typename ArgTy> 10519 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 10520 for (const auto &ArgIdx : enumerate(Args)) { 10521 MVT ArgVT = ArgIdx.value().VT; 10522 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 10523 return ArgIdx.index(); 10524 } 10525 return None; 10526 } 10527 10528 void RISCVTargetLowering::analyzeInputArgs( 10529 MachineFunction &MF, CCState &CCInfo, 10530 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 10531 RISCVCCAssignFn Fn) const { 10532 unsigned NumArgs = Ins.size(); 10533 FunctionType *FType = MF.getFunction().getFunctionType(); 10534 10535 Optional<unsigned> FirstMaskArgument; 10536 if (Subtarget.hasVInstructions()) 10537 FirstMaskArgument = preAssignMask(Ins); 10538 10539 for (unsigned i = 0; i != NumArgs; ++i) { 10540 MVT ArgVT = Ins[i].VT; 10541 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 10542 10543 Type *ArgTy = nullptr; 10544 if (IsRet) 10545 ArgTy = FType->getReturnType(); 10546 else if (Ins[i].isOrigArg()) 10547 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 10548 10549 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10550 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10551 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 10552 FirstMaskArgument)) { 10553 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 10554 << EVT(ArgVT).getEVTString() << '\n'); 10555 llvm_unreachable(nullptr); 10556 } 10557 } 10558 } 10559 10560 void RISCVTargetLowering::analyzeOutputArgs( 10561 MachineFunction &MF, CCState &CCInfo, 10562 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 10563 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 10564 unsigned NumArgs = Outs.size(); 10565 10566 Optional<unsigned> FirstMaskArgument; 10567 if (Subtarget.hasVInstructions()) 10568 FirstMaskArgument = preAssignMask(Outs); 10569 10570 for (unsigned i = 0; i != NumArgs; i++) { 10571 MVT ArgVT = Outs[i].VT; 10572 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10573 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 10574 10575 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10576 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10577 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 10578 FirstMaskArgument)) { 10579 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 10580 << EVT(ArgVT).getEVTString() << "\n"); 10581 llvm_unreachable(nullptr); 10582 } 10583 } 10584 } 10585 10586 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 10587 // values. 10588 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 10589 const CCValAssign &VA, const SDLoc &DL, 10590 const RISCVSubtarget &Subtarget) { 10591 switch (VA.getLocInfo()) { 10592 default: 10593 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10594 case CCValAssign::Full: 10595 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 10596 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 10597 break; 10598 case CCValAssign::BCvt: 10599 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10600 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 10601 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10602 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 10603 else 10604 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 10605 break; 10606 } 10607 return Val; 10608 } 10609 10610 // The caller is responsible for loading the full value if the argument is 10611 // passed with CCValAssign::Indirect. 10612 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 10613 const CCValAssign &VA, const SDLoc &DL, 10614 const RISCVTargetLowering &TLI) { 10615 MachineFunction &MF = DAG.getMachineFunction(); 10616 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10617 EVT LocVT = VA.getLocVT(); 10618 SDValue Val; 10619 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 10620 Register VReg = RegInfo.createVirtualRegister(RC); 10621 RegInfo.addLiveIn(VA.getLocReg(), VReg); 10622 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 10623 10624 if (VA.getLocInfo() == CCValAssign::Indirect) 10625 return Val; 10626 10627 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 10628 } 10629 10630 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 10631 const CCValAssign &VA, const SDLoc &DL, 10632 const RISCVSubtarget &Subtarget) { 10633 EVT LocVT = VA.getLocVT(); 10634 10635 switch (VA.getLocInfo()) { 10636 default: 10637 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10638 case CCValAssign::Full: 10639 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 10640 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 10641 break; 10642 case CCValAssign::BCvt: 10643 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10644 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 10645 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10646 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 10647 else 10648 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 10649 break; 10650 } 10651 return Val; 10652 } 10653 10654 // The caller is responsible for loading the full value if the argument is 10655 // passed with CCValAssign::Indirect. 10656 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 10657 const CCValAssign &VA, const SDLoc &DL) { 10658 MachineFunction &MF = DAG.getMachineFunction(); 10659 MachineFrameInfo &MFI = MF.getFrameInfo(); 10660 EVT LocVT = VA.getLocVT(); 10661 EVT ValVT = VA.getValVT(); 10662 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 10663 if (ValVT.isScalableVector()) { 10664 // When the value is a scalable vector, we save the pointer which points to 10665 // the scalable vector value in the stack. The ValVT will be the pointer 10666 // type, instead of the scalable vector type. 10667 ValVT = LocVT; 10668 } 10669 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 10670 /*IsImmutable=*/true); 10671 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 10672 SDValue Val; 10673 10674 ISD::LoadExtType ExtType; 10675 switch (VA.getLocInfo()) { 10676 default: 10677 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10678 case CCValAssign::Full: 10679 case CCValAssign::Indirect: 10680 case CCValAssign::BCvt: 10681 ExtType = ISD::NON_EXTLOAD; 10682 break; 10683 } 10684 Val = DAG.getExtLoad( 10685 ExtType, DL, LocVT, Chain, FIN, 10686 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 10687 return Val; 10688 } 10689 10690 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 10691 const CCValAssign &VA, const SDLoc &DL) { 10692 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 10693 "Unexpected VA"); 10694 MachineFunction &MF = DAG.getMachineFunction(); 10695 MachineFrameInfo &MFI = MF.getFrameInfo(); 10696 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10697 10698 if (VA.isMemLoc()) { 10699 // f64 is passed on the stack. 10700 int FI = 10701 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 10702 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10703 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 10704 MachinePointerInfo::getFixedStack(MF, FI)); 10705 } 10706 10707 assert(VA.isRegLoc() && "Expected register VA assignment"); 10708 10709 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10710 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 10711 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 10712 SDValue Hi; 10713 if (VA.getLocReg() == RISCV::X17) { 10714 // Second half of f64 is passed on the stack. 10715 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 10716 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10717 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 10718 MachinePointerInfo::getFixedStack(MF, FI)); 10719 } else { 10720 // Second half of f64 is passed in another GPR. 10721 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10722 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 10723 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 10724 } 10725 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 10726 } 10727 10728 // FastCC has less than 1% performance improvement for some particular 10729 // benchmark. But theoretically, it may has benenfit for some cases. 10730 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 10731 unsigned ValNo, MVT ValVT, MVT LocVT, 10732 CCValAssign::LocInfo LocInfo, 10733 ISD::ArgFlagsTy ArgFlags, CCState &State, 10734 bool IsFixed, bool IsRet, Type *OrigTy, 10735 const RISCVTargetLowering &TLI, 10736 Optional<unsigned> FirstMaskArgument) { 10737 10738 // X5 and X6 might be used for save-restore libcall. 10739 static const MCPhysReg GPRList[] = { 10740 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 10741 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 10742 RISCV::X29, RISCV::X30, RISCV::X31}; 10743 10744 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10745 if (unsigned Reg = State.AllocateReg(GPRList)) { 10746 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10747 return false; 10748 } 10749 } 10750 10751 if (LocVT == MVT::f16) { 10752 static const MCPhysReg FPR16List[] = { 10753 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 10754 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 10755 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 10756 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 10757 if (unsigned Reg = State.AllocateReg(FPR16List)) { 10758 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10759 return false; 10760 } 10761 } 10762 10763 if (LocVT == MVT::f32) { 10764 static const MCPhysReg FPR32List[] = { 10765 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 10766 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 10767 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 10768 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 10769 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10770 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10771 return false; 10772 } 10773 } 10774 10775 if (LocVT == MVT::f64) { 10776 static const MCPhysReg FPR64List[] = { 10777 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 10778 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 10779 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 10780 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 10781 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10782 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10783 return false; 10784 } 10785 } 10786 10787 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 10788 unsigned Offset4 = State.AllocateStack(4, Align(4)); 10789 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 10790 return false; 10791 } 10792 10793 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 10794 unsigned Offset5 = State.AllocateStack(8, Align(8)); 10795 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 10796 return false; 10797 } 10798 10799 if (LocVT.isVector()) { 10800 if (unsigned Reg = 10801 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 10802 // Fixed-length vectors are located in the corresponding scalable-vector 10803 // container types. 10804 if (ValVT.isFixedLengthVector()) 10805 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10806 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10807 } else { 10808 // Try and pass the address via a "fast" GPR. 10809 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 10810 LocInfo = CCValAssign::Indirect; 10811 LocVT = TLI.getSubtarget().getXLenVT(); 10812 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 10813 } else if (ValVT.isFixedLengthVector()) { 10814 auto StackAlign = 10815 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10816 unsigned StackOffset = 10817 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 10818 State.addLoc( 10819 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10820 } else { 10821 // Can't pass scalable vectors on the stack. 10822 return true; 10823 } 10824 } 10825 10826 return false; 10827 } 10828 10829 return true; // CC didn't match. 10830 } 10831 10832 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 10833 CCValAssign::LocInfo LocInfo, 10834 ISD::ArgFlagsTy ArgFlags, CCState &State) { 10835 10836 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10837 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 10838 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 10839 static const MCPhysReg GPRList[] = { 10840 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 10841 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 10842 if (unsigned Reg = State.AllocateReg(GPRList)) { 10843 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10844 return false; 10845 } 10846 } 10847 10848 if (LocVT == MVT::f32) { 10849 // Pass in STG registers: F1, ..., F6 10850 // fs0 ... fs5 10851 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 10852 RISCV::F18_F, RISCV::F19_F, 10853 RISCV::F20_F, RISCV::F21_F}; 10854 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10855 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10856 return false; 10857 } 10858 } 10859 10860 if (LocVT == MVT::f64) { 10861 // Pass in STG registers: D1, ..., D6 10862 // fs6 ... fs11 10863 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 10864 RISCV::F24_D, RISCV::F25_D, 10865 RISCV::F26_D, RISCV::F27_D}; 10866 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10867 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10868 return false; 10869 } 10870 } 10871 10872 report_fatal_error("No registers left in GHC calling convention"); 10873 return true; 10874 } 10875 10876 // Transform physical registers into virtual registers. 10877 SDValue RISCVTargetLowering::LowerFormalArguments( 10878 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 10879 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 10880 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 10881 10882 MachineFunction &MF = DAG.getMachineFunction(); 10883 10884 switch (CallConv) { 10885 default: 10886 report_fatal_error("Unsupported calling convention"); 10887 case CallingConv::C: 10888 case CallingConv::Fast: 10889 break; 10890 case CallingConv::GHC: 10891 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10892 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10893 report_fatal_error( 10894 "GHC calling convention requires the F and D instruction set extensions"); 10895 } 10896 10897 const Function &Func = MF.getFunction(); 10898 if (Func.hasFnAttribute("interrupt")) { 10899 if (!Func.arg_empty()) 10900 report_fatal_error( 10901 "Functions with the interrupt attribute cannot have arguments!"); 10902 10903 StringRef Kind = 10904 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10905 10906 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10907 report_fatal_error( 10908 "Function interrupt attribute argument not supported!"); 10909 } 10910 10911 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10912 MVT XLenVT = Subtarget.getXLenVT(); 10913 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10914 // Used with vargs to acumulate store chains. 10915 std::vector<SDValue> OutChains; 10916 10917 // Assign locations to all of the incoming arguments. 10918 SmallVector<CCValAssign, 16> ArgLocs; 10919 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10920 10921 if (CallConv == CallingConv::GHC) 10922 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10923 else 10924 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10925 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10926 : CC_RISCV); 10927 10928 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10929 CCValAssign &VA = ArgLocs[i]; 10930 SDValue ArgValue; 10931 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10932 // case. 10933 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10934 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10935 else if (VA.isRegLoc()) 10936 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10937 else 10938 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10939 10940 if (VA.getLocInfo() == CCValAssign::Indirect) { 10941 // If the original argument was split and passed by reference (e.g. i128 10942 // on RV32), we need to load all parts of it here (using the same 10943 // address). Vectors may be partly split to registers and partly to the 10944 // stack, in which case the base address is partly offset and subsequent 10945 // stores are relative to that. 10946 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10947 MachinePointerInfo())); 10948 unsigned ArgIndex = Ins[i].OrigArgIndex; 10949 unsigned ArgPartOffset = Ins[i].PartOffset; 10950 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10951 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10952 CCValAssign &PartVA = ArgLocs[i + 1]; 10953 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10954 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10955 if (PartVA.getValVT().isScalableVector()) 10956 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10957 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10958 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10959 MachinePointerInfo())); 10960 ++i; 10961 } 10962 continue; 10963 } 10964 InVals.push_back(ArgValue); 10965 } 10966 10967 if (IsVarArg) { 10968 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10969 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10970 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10971 MachineFrameInfo &MFI = MF.getFrameInfo(); 10972 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10973 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10974 10975 // Offset of the first variable argument from stack pointer, and size of 10976 // the vararg save area. For now, the varargs save area is either zero or 10977 // large enough to hold a0-a7. 10978 int VaArgOffset, VarArgsSaveSize; 10979 10980 // If all registers are allocated, then all varargs must be passed on the 10981 // stack and we don't need to save any argregs. 10982 if (ArgRegs.size() == Idx) { 10983 VaArgOffset = CCInfo.getNextStackOffset(); 10984 VarArgsSaveSize = 0; 10985 } else { 10986 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10987 VaArgOffset = -VarArgsSaveSize; 10988 } 10989 10990 // Record the frame index of the first variable argument 10991 // which is a value necessary to VASTART. 10992 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10993 RVFI->setVarArgsFrameIndex(FI); 10994 10995 // If saving an odd number of registers then create an extra stack slot to 10996 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10997 // offsets to even-numbered registered remain 2*XLEN-aligned. 10998 if (Idx % 2) { 10999 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 11000 VarArgsSaveSize += XLenInBytes; 11001 } 11002 11003 // Copy the integer registers that may have been used for passing varargs 11004 // to the vararg save area. 11005 for (unsigned I = Idx; I < ArgRegs.size(); 11006 ++I, VaArgOffset += XLenInBytes) { 11007 const Register Reg = RegInfo.createVirtualRegister(RC); 11008 RegInfo.addLiveIn(ArgRegs[I], Reg); 11009 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 11010 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 11011 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 11012 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 11013 MachinePointerInfo::getFixedStack(MF, FI)); 11014 cast<StoreSDNode>(Store.getNode()) 11015 ->getMemOperand() 11016 ->setValue((Value *)nullptr); 11017 OutChains.push_back(Store); 11018 } 11019 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 11020 } 11021 11022 // All stores are grouped in one node to allow the matching between 11023 // the size of Ins and InVals. This only happens for vararg functions. 11024 if (!OutChains.empty()) { 11025 OutChains.push_back(Chain); 11026 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 11027 } 11028 11029 return Chain; 11030 } 11031 11032 /// isEligibleForTailCallOptimization - Check whether the call is eligible 11033 /// for tail call optimization. 11034 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 11035 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 11036 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 11037 const SmallVector<CCValAssign, 16> &ArgLocs) const { 11038 11039 auto &Callee = CLI.Callee; 11040 auto CalleeCC = CLI.CallConv; 11041 auto &Outs = CLI.Outs; 11042 auto &Caller = MF.getFunction(); 11043 auto CallerCC = Caller.getCallingConv(); 11044 11045 // Exception-handling functions need a special set of instructions to 11046 // indicate a return to the hardware. Tail-calling another function would 11047 // probably break this. 11048 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 11049 // should be expanded as new function attributes are introduced. 11050 if (Caller.hasFnAttribute("interrupt")) 11051 return false; 11052 11053 // Do not tail call opt if the stack is used to pass parameters. 11054 if (CCInfo.getNextStackOffset() != 0) 11055 return false; 11056 11057 // Do not tail call opt if any parameters need to be passed indirectly. 11058 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 11059 // passed indirectly. So the address of the value will be passed in a 11060 // register, or if not available, then the address is put on the stack. In 11061 // order to pass indirectly, space on the stack often needs to be allocated 11062 // in order to store the value. In this case the CCInfo.getNextStackOffset() 11063 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 11064 // are passed CCValAssign::Indirect. 11065 for (auto &VA : ArgLocs) 11066 if (VA.getLocInfo() == CCValAssign::Indirect) 11067 return false; 11068 11069 // Do not tail call opt if either caller or callee uses struct return 11070 // semantics. 11071 auto IsCallerStructRet = Caller.hasStructRetAttr(); 11072 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 11073 if (IsCallerStructRet || IsCalleeStructRet) 11074 return false; 11075 11076 // Externally-defined functions with weak linkage should not be 11077 // tail-called. The behaviour of branch instructions in this situation (as 11078 // used for tail calls) is implementation-defined, so we cannot rely on the 11079 // linker replacing the tail call with a return. 11080 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 11081 const GlobalValue *GV = G->getGlobal(); 11082 if (GV->hasExternalWeakLinkage()) 11083 return false; 11084 } 11085 11086 // The callee has to preserve all registers the caller needs to preserve. 11087 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11088 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 11089 if (CalleeCC != CallerCC) { 11090 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 11091 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 11092 return false; 11093 } 11094 11095 // Byval parameters hand the function a pointer directly into the stack area 11096 // we want to reuse during a tail call. Working around this *is* possible 11097 // but less efficient and uglier in LowerCall. 11098 for (auto &Arg : Outs) 11099 if (Arg.Flags.isByVal()) 11100 return false; 11101 11102 return true; 11103 } 11104 11105 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 11106 return DAG.getDataLayout().getPrefTypeAlign( 11107 VT.getTypeForEVT(*DAG.getContext())); 11108 } 11109 11110 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 11111 // and output parameter nodes. 11112 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 11113 SmallVectorImpl<SDValue> &InVals) const { 11114 SelectionDAG &DAG = CLI.DAG; 11115 SDLoc &DL = CLI.DL; 11116 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 11117 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 11118 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 11119 SDValue Chain = CLI.Chain; 11120 SDValue Callee = CLI.Callee; 11121 bool &IsTailCall = CLI.IsTailCall; 11122 CallingConv::ID CallConv = CLI.CallConv; 11123 bool IsVarArg = CLI.IsVarArg; 11124 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 11125 MVT XLenVT = Subtarget.getXLenVT(); 11126 11127 MachineFunction &MF = DAG.getMachineFunction(); 11128 11129 // Analyze the operands of the call, assigning locations to each operand. 11130 SmallVector<CCValAssign, 16> ArgLocs; 11131 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 11132 11133 if (CallConv == CallingConv::GHC) 11134 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 11135 else 11136 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 11137 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 11138 : CC_RISCV); 11139 11140 // Check if it's really possible to do a tail call. 11141 if (IsTailCall) 11142 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 11143 11144 if (IsTailCall) 11145 ++NumTailCalls; 11146 else if (CLI.CB && CLI.CB->isMustTailCall()) 11147 report_fatal_error("failed to perform tail call elimination on a call " 11148 "site marked musttail"); 11149 11150 // Get a count of how many bytes are to be pushed on the stack. 11151 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 11152 11153 // Create local copies for byval args 11154 SmallVector<SDValue, 8> ByValArgs; 11155 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 11156 ISD::ArgFlagsTy Flags = Outs[i].Flags; 11157 if (!Flags.isByVal()) 11158 continue; 11159 11160 SDValue Arg = OutVals[i]; 11161 unsigned Size = Flags.getByValSize(); 11162 Align Alignment = Flags.getNonZeroByValAlign(); 11163 11164 int FI = 11165 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 11166 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 11167 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 11168 11169 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 11170 /*IsVolatile=*/false, 11171 /*AlwaysInline=*/false, IsTailCall, 11172 MachinePointerInfo(), MachinePointerInfo()); 11173 ByValArgs.push_back(FIPtr); 11174 } 11175 11176 if (!IsTailCall) 11177 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 11178 11179 // Copy argument values to their designated locations. 11180 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 11181 SmallVector<SDValue, 8> MemOpChains; 11182 SDValue StackPtr; 11183 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 11184 CCValAssign &VA = ArgLocs[i]; 11185 SDValue ArgValue = OutVals[i]; 11186 ISD::ArgFlagsTy Flags = Outs[i].Flags; 11187 11188 // Handle passing f64 on RV32D with a soft float ABI as a special case. 11189 bool IsF64OnRV32DSoftABI = 11190 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 11191 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 11192 SDValue SplitF64 = DAG.getNode( 11193 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 11194 SDValue Lo = SplitF64.getValue(0); 11195 SDValue Hi = SplitF64.getValue(1); 11196 11197 Register RegLo = VA.getLocReg(); 11198 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 11199 11200 if (RegLo == RISCV::X17) { 11201 // Second half of f64 is passed on the stack. 11202 // Work out the address of the stack slot. 11203 if (!StackPtr.getNode()) 11204 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 11205 // Emit the store. 11206 MemOpChains.push_back( 11207 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 11208 } else { 11209 // Second half of f64 is passed in another GPR. 11210 assert(RegLo < RISCV::X31 && "Invalid register pair"); 11211 Register RegHigh = RegLo + 1; 11212 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 11213 } 11214 continue; 11215 } 11216 11217 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 11218 // as any other MemLoc. 11219 11220 // Promote the value if needed. 11221 // For now, only handle fully promoted and indirect arguments. 11222 if (VA.getLocInfo() == CCValAssign::Indirect) { 11223 // Store the argument in a stack slot and pass its address. 11224 Align StackAlign = 11225 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 11226 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 11227 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 11228 // If the original argument was split (e.g. i128), we need 11229 // to store the required parts of it here (and pass just one address). 11230 // Vectors may be partly split to registers and partly to the stack, in 11231 // which case the base address is partly offset and subsequent stores are 11232 // relative to that. 11233 unsigned ArgIndex = Outs[i].OrigArgIndex; 11234 unsigned ArgPartOffset = Outs[i].PartOffset; 11235 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 11236 // Calculate the total size to store. We don't have access to what we're 11237 // actually storing other than performing the loop and collecting the 11238 // info. 11239 SmallVector<std::pair<SDValue, SDValue>> Parts; 11240 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 11241 SDValue PartValue = OutVals[i + 1]; 11242 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 11243 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 11244 EVT PartVT = PartValue.getValueType(); 11245 if (PartVT.isScalableVector()) 11246 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 11247 StoredSize += PartVT.getStoreSize(); 11248 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 11249 Parts.push_back(std::make_pair(PartValue, Offset)); 11250 ++i; 11251 } 11252 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 11253 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 11254 MemOpChains.push_back( 11255 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 11256 MachinePointerInfo::getFixedStack(MF, FI))); 11257 for (const auto &Part : Parts) { 11258 SDValue PartValue = Part.first; 11259 SDValue PartOffset = Part.second; 11260 SDValue Address = 11261 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 11262 MemOpChains.push_back( 11263 DAG.getStore(Chain, DL, PartValue, Address, 11264 MachinePointerInfo::getFixedStack(MF, FI))); 11265 } 11266 ArgValue = SpillSlot; 11267 } else { 11268 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 11269 } 11270 11271 // Use local copy if it is a byval arg. 11272 if (Flags.isByVal()) 11273 ArgValue = ByValArgs[j++]; 11274 11275 if (VA.isRegLoc()) { 11276 // Queue up the argument copies and emit them at the end. 11277 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 11278 } else { 11279 assert(VA.isMemLoc() && "Argument not register or memory"); 11280 assert(!IsTailCall && "Tail call not allowed if stack is used " 11281 "for passing parameters"); 11282 11283 // Work out the address of the stack slot. 11284 if (!StackPtr.getNode()) 11285 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 11286 SDValue Address = 11287 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 11288 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 11289 11290 // Emit the store. 11291 MemOpChains.push_back( 11292 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 11293 } 11294 } 11295 11296 // Join the stores, which are independent of one another. 11297 if (!MemOpChains.empty()) 11298 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 11299 11300 SDValue Glue; 11301 11302 // Build a sequence of copy-to-reg nodes, chained and glued together. 11303 for (auto &Reg : RegsToPass) { 11304 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 11305 Glue = Chain.getValue(1); 11306 } 11307 11308 // Validate that none of the argument registers have been marked as 11309 // reserved, if so report an error. Do the same for the return address if this 11310 // is not a tailcall. 11311 validateCCReservedRegs(RegsToPass, MF); 11312 if (!IsTailCall && 11313 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 11314 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11315 MF.getFunction(), 11316 "Return address register required, but has been reserved."}); 11317 11318 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 11319 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 11320 // split it and then direct call can be matched by PseudoCALL. 11321 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 11322 const GlobalValue *GV = S->getGlobal(); 11323 11324 unsigned OpFlags = RISCVII::MO_CALL; 11325 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 11326 OpFlags = RISCVII::MO_PLT; 11327 11328 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 11329 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 11330 unsigned OpFlags = RISCVII::MO_CALL; 11331 11332 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 11333 nullptr)) 11334 OpFlags = RISCVII::MO_PLT; 11335 11336 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 11337 } 11338 11339 // The first call operand is the chain and the second is the target address. 11340 SmallVector<SDValue, 8> Ops; 11341 Ops.push_back(Chain); 11342 Ops.push_back(Callee); 11343 11344 // Add argument registers to the end of the list so that they are 11345 // known live into the call. 11346 for (auto &Reg : RegsToPass) 11347 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 11348 11349 if (!IsTailCall) { 11350 // Add a register mask operand representing the call-preserved registers. 11351 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11352 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 11353 assert(Mask && "Missing call preserved mask for calling convention"); 11354 Ops.push_back(DAG.getRegisterMask(Mask)); 11355 } 11356 11357 // Glue the call to the argument copies, if any. 11358 if (Glue.getNode()) 11359 Ops.push_back(Glue); 11360 11361 // Emit the call. 11362 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 11363 11364 if (IsTailCall) { 11365 MF.getFrameInfo().setHasTailCall(); 11366 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 11367 } 11368 11369 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 11370 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 11371 Glue = Chain.getValue(1); 11372 11373 // Mark the end of the call, which is glued to the call itself. 11374 Chain = DAG.getCALLSEQ_END(Chain, 11375 DAG.getConstant(NumBytes, DL, PtrVT, true), 11376 DAG.getConstant(0, DL, PtrVT, true), 11377 Glue, DL); 11378 Glue = Chain.getValue(1); 11379 11380 // Assign locations to each value returned by this call. 11381 SmallVector<CCValAssign, 16> RVLocs; 11382 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 11383 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 11384 11385 // Copy all of the result registers out of their specified physreg. 11386 for (auto &VA : RVLocs) { 11387 // Copy the value out 11388 SDValue RetValue = 11389 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 11390 // Glue the RetValue to the end of the call sequence 11391 Chain = RetValue.getValue(1); 11392 Glue = RetValue.getValue(2); 11393 11394 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 11395 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 11396 SDValue RetValue2 = 11397 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 11398 Chain = RetValue2.getValue(1); 11399 Glue = RetValue2.getValue(2); 11400 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 11401 RetValue2); 11402 } 11403 11404 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 11405 11406 InVals.push_back(RetValue); 11407 } 11408 11409 return Chain; 11410 } 11411 11412 bool RISCVTargetLowering::CanLowerReturn( 11413 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 11414 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 11415 SmallVector<CCValAssign, 16> RVLocs; 11416 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 11417 11418 Optional<unsigned> FirstMaskArgument; 11419 if (Subtarget.hasVInstructions()) 11420 FirstMaskArgument = preAssignMask(Outs); 11421 11422 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 11423 MVT VT = Outs[i].VT; 11424 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 11425 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 11426 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 11427 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 11428 *this, FirstMaskArgument)) 11429 return false; 11430 } 11431 return true; 11432 } 11433 11434 SDValue 11435 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 11436 bool IsVarArg, 11437 const SmallVectorImpl<ISD::OutputArg> &Outs, 11438 const SmallVectorImpl<SDValue> &OutVals, 11439 const SDLoc &DL, SelectionDAG &DAG) const { 11440 const MachineFunction &MF = DAG.getMachineFunction(); 11441 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 11442 11443 // Stores the assignment of the return value to a location. 11444 SmallVector<CCValAssign, 16> RVLocs; 11445 11446 // Info about the registers and stack slot. 11447 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 11448 *DAG.getContext()); 11449 11450 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 11451 nullptr, CC_RISCV); 11452 11453 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 11454 report_fatal_error("GHC functions return void only"); 11455 11456 SDValue Glue; 11457 SmallVector<SDValue, 4> RetOps(1, Chain); 11458 11459 // Copy the result values into the output registers. 11460 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 11461 SDValue Val = OutVals[i]; 11462 CCValAssign &VA = RVLocs[i]; 11463 assert(VA.isRegLoc() && "Can only return in registers!"); 11464 11465 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 11466 // Handle returning f64 on RV32D with a soft float ABI. 11467 assert(VA.isRegLoc() && "Expected return via registers"); 11468 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 11469 DAG.getVTList(MVT::i32, MVT::i32), Val); 11470 SDValue Lo = SplitF64.getValue(0); 11471 SDValue Hi = SplitF64.getValue(1); 11472 Register RegLo = VA.getLocReg(); 11473 assert(RegLo < RISCV::X31 && "Invalid register pair"); 11474 Register RegHi = RegLo + 1; 11475 11476 if (STI.isRegisterReservedByUser(RegLo) || 11477 STI.isRegisterReservedByUser(RegHi)) 11478 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11479 MF.getFunction(), 11480 "Return value register required, but has been reserved."}); 11481 11482 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 11483 Glue = Chain.getValue(1); 11484 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 11485 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 11486 Glue = Chain.getValue(1); 11487 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 11488 } else { 11489 // Handle a 'normal' return. 11490 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 11491 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 11492 11493 if (STI.isRegisterReservedByUser(VA.getLocReg())) 11494 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11495 MF.getFunction(), 11496 "Return value register required, but has been reserved."}); 11497 11498 // Guarantee that all emitted copies are stuck together. 11499 Glue = Chain.getValue(1); 11500 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 11501 } 11502 } 11503 11504 RetOps[0] = Chain; // Update chain. 11505 11506 // Add the glue node if we have it. 11507 if (Glue.getNode()) { 11508 RetOps.push_back(Glue); 11509 } 11510 11511 unsigned RetOpc = RISCVISD::RET_FLAG; 11512 // Interrupt service routines use different return instructions. 11513 const Function &Func = DAG.getMachineFunction().getFunction(); 11514 if (Func.hasFnAttribute("interrupt")) { 11515 if (!Func.getReturnType()->isVoidTy()) 11516 report_fatal_error( 11517 "Functions with the interrupt attribute must have void return type!"); 11518 11519 MachineFunction &MF = DAG.getMachineFunction(); 11520 StringRef Kind = 11521 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 11522 11523 if (Kind == "user") 11524 RetOpc = RISCVISD::URET_FLAG; 11525 else if (Kind == "supervisor") 11526 RetOpc = RISCVISD::SRET_FLAG; 11527 else 11528 RetOpc = RISCVISD::MRET_FLAG; 11529 } 11530 11531 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 11532 } 11533 11534 void RISCVTargetLowering::validateCCReservedRegs( 11535 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 11536 MachineFunction &MF) const { 11537 const Function &F = MF.getFunction(); 11538 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 11539 11540 if (llvm::any_of(Regs, [&STI](auto Reg) { 11541 return STI.isRegisterReservedByUser(Reg.first); 11542 })) 11543 F.getContext().diagnose(DiagnosticInfoUnsupported{ 11544 F, "Argument register required, but has been reserved."}); 11545 } 11546 11547 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 11548 return CI->isTailCall(); 11549 } 11550 11551 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 11552 #define NODE_NAME_CASE(NODE) \ 11553 case RISCVISD::NODE: \ 11554 return "RISCVISD::" #NODE; 11555 // clang-format off 11556 switch ((RISCVISD::NodeType)Opcode) { 11557 case RISCVISD::FIRST_NUMBER: 11558 break; 11559 NODE_NAME_CASE(RET_FLAG) 11560 NODE_NAME_CASE(URET_FLAG) 11561 NODE_NAME_CASE(SRET_FLAG) 11562 NODE_NAME_CASE(MRET_FLAG) 11563 NODE_NAME_CASE(CALL) 11564 NODE_NAME_CASE(SELECT_CC) 11565 NODE_NAME_CASE(BR_CC) 11566 NODE_NAME_CASE(BuildPairF64) 11567 NODE_NAME_CASE(SplitF64) 11568 NODE_NAME_CASE(TAIL) 11569 NODE_NAME_CASE(ADD_LO) 11570 NODE_NAME_CASE(HI) 11571 NODE_NAME_CASE(LLA) 11572 NODE_NAME_CASE(ADD_TPREL) 11573 NODE_NAME_CASE(LA) 11574 NODE_NAME_CASE(LA_TLS_IE) 11575 NODE_NAME_CASE(LA_TLS_GD) 11576 NODE_NAME_CASE(MULHSU) 11577 NODE_NAME_CASE(SLLW) 11578 NODE_NAME_CASE(SRAW) 11579 NODE_NAME_CASE(SRLW) 11580 NODE_NAME_CASE(DIVW) 11581 NODE_NAME_CASE(DIVUW) 11582 NODE_NAME_CASE(REMUW) 11583 NODE_NAME_CASE(ROLW) 11584 NODE_NAME_CASE(RORW) 11585 NODE_NAME_CASE(CLZW) 11586 NODE_NAME_CASE(CTZW) 11587 NODE_NAME_CASE(FSLW) 11588 NODE_NAME_CASE(FSRW) 11589 NODE_NAME_CASE(FSL) 11590 NODE_NAME_CASE(FSR) 11591 NODE_NAME_CASE(FMV_H_X) 11592 NODE_NAME_CASE(FMV_X_ANYEXTH) 11593 NODE_NAME_CASE(FMV_X_SIGNEXTH) 11594 NODE_NAME_CASE(FMV_W_X_RV64) 11595 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 11596 NODE_NAME_CASE(FCVT_X) 11597 NODE_NAME_CASE(FCVT_XU) 11598 NODE_NAME_CASE(FCVT_W_RV64) 11599 NODE_NAME_CASE(FCVT_WU_RV64) 11600 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 11601 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 11602 NODE_NAME_CASE(READ_CYCLE_WIDE) 11603 NODE_NAME_CASE(GREV) 11604 NODE_NAME_CASE(GREVW) 11605 NODE_NAME_CASE(GORC) 11606 NODE_NAME_CASE(GORCW) 11607 NODE_NAME_CASE(SHFL) 11608 NODE_NAME_CASE(SHFLW) 11609 NODE_NAME_CASE(UNSHFL) 11610 NODE_NAME_CASE(UNSHFLW) 11611 NODE_NAME_CASE(BFP) 11612 NODE_NAME_CASE(BFPW) 11613 NODE_NAME_CASE(BCOMPRESS) 11614 NODE_NAME_CASE(BCOMPRESSW) 11615 NODE_NAME_CASE(BDECOMPRESS) 11616 NODE_NAME_CASE(BDECOMPRESSW) 11617 NODE_NAME_CASE(VMV_V_X_VL) 11618 NODE_NAME_CASE(VFMV_V_F_VL) 11619 NODE_NAME_CASE(VMV_X_S) 11620 NODE_NAME_CASE(VMV_S_X_VL) 11621 NODE_NAME_CASE(VFMV_S_F_VL) 11622 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 11623 NODE_NAME_CASE(READ_VLENB) 11624 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 11625 NODE_NAME_CASE(VSLIDEUP_VL) 11626 NODE_NAME_CASE(VSLIDE1UP_VL) 11627 NODE_NAME_CASE(VSLIDEDOWN_VL) 11628 NODE_NAME_CASE(VSLIDE1DOWN_VL) 11629 NODE_NAME_CASE(VID_VL) 11630 NODE_NAME_CASE(VFNCVT_ROD_VL) 11631 NODE_NAME_CASE(VECREDUCE_ADD_VL) 11632 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 11633 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 11634 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 11635 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 11636 NODE_NAME_CASE(VECREDUCE_AND_VL) 11637 NODE_NAME_CASE(VECREDUCE_OR_VL) 11638 NODE_NAME_CASE(VECREDUCE_XOR_VL) 11639 NODE_NAME_CASE(VECREDUCE_FADD_VL) 11640 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 11641 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 11642 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 11643 NODE_NAME_CASE(ADD_VL) 11644 NODE_NAME_CASE(AND_VL) 11645 NODE_NAME_CASE(MUL_VL) 11646 NODE_NAME_CASE(OR_VL) 11647 NODE_NAME_CASE(SDIV_VL) 11648 NODE_NAME_CASE(SHL_VL) 11649 NODE_NAME_CASE(SREM_VL) 11650 NODE_NAME_CASE(SRA_VL) 11651 NODE_NAME_CASE(SRL_VL) 11652 NODE_NAME_CASE(SUB_VL) 11653 NODE_NAME_CASE(UDIV_VL) 11654 NODE_NAME_CASE(UREM_VL) 11655 NODE_NAME_CASE(XOR_VL) 11656 NODE_NAME_CASE(SADDSAT_VL) 11657 NODE_NAME_CASE(UADDSAT_VL) 11658 NODE_NAME_CASE(SSUBSAT_VL) 11659 NODE_NAME_CASE(USUBSAT_VL) 11660 NODE_NAME_CASE(FADD_VL) 11661 NODE_NAME_CASE(FSUB_VL) 11662 NODE_NAME_CASE(FMUL_VL) 11663 NODE_NAME_CASE(FDIV_VL) 11664 NODE_NAME_CASE(FNEG_VL) 11665 NODE_NAME_CASE(FABS_VL) 11666 NODE_NAME_CASE(FSQRT_VL) 11667 NODE_NAME_CASE(VFMADD_VL) 11668 NODE_NAME_CASE(VFNMADD_VL) 11669 NODE_NAME_CASE(VFMSUB_VL) 11670 NODE_NAME_CASE(VFNMSUB_VL) 11671 NODE_NAME_CASE(FCOPYSIGN_VL) 11672 NODE_NAME_CASE(SMIN_VL) 11673 NODE_NAME_CASE(SMAX_VL) 11674 NODE_NAME_CASE(UMIN_VL) 11675 NODE_NAME_CASE(UMAX_VL) 11676 NODE_NAME_CASE(FMINNUM_VL) 11677 NODE_NAME_CASE(FMAXNUM_VL) 11678 NODE_NAME_CASE(MULHS_VL) 11679 NODE_NAME_CASE(MULHU_VL) 11680 NODE_NAME_CASE(FP_TO_SINT_VL) 11681 NODE_NAME_CASE(FP_TO_UINT_VL) 11682 NODE_NAME_CASE(SINT_TO_FP_VL) 11683 NODE_NAME_CASE(UINT_TO_FP_VL) 11684 NODE_NAME_CASE(FP_EXTEND_VL) 11685 NODE_NAME_CASE(FP_ROUND_VL) 11686 NODE_NAME_CASE(VWMUL_VL) 11687 NODE_NAME_CASE(VWMULU_VL) 11688 NODE_NAME_CASE(VWMULSU_VL) 11689 NODE_NAME_CASE(VWADD_VL) 11690 NODE_NAME_CASE(VWADDU_VL) 11691 NODE_NAME_CASE(VWSUB_VL) 11692 NODE_NAME_CASE(VWSUBU_VL) 11693 NODE_NAME_CASE(VWADD_W_VL) 11694 NODE_NAME_CASE(VWADDU_W_VL) 11695 NODE_NAME_CASE(VWSUB_W_VL) 11696 NODE_NAME_CASE(VWSUBU_W_VL) 11697 NODE_NAME_CASE(SETCC_VL) 11698 NODE_NAME_CASE(VSELECT_VL) 11699 NODE_NAME_CASE(VP_MERGE_VL) 11700 NODE_NAME_CASE(VMAND_VL) 11701 NODE_NAME_CASE(VMOR_VL) 11702 NODE_NAME_CASE(VMXOR_VL) 11703 NODE_NAME_CASE(VMCLR_VL) 11704 NODE_NAME_CASE(VMSET_VL) 11705 NODE_NAME_CASE(VRGATHER_VX_VL) 11706 NODE_NAME_CASE(VRGATHER_VV_VL) 11707 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 11708 NODE_NAME_CASE(VSEXT_VL) 11709 NODE_NAME_CASE(VZEXT_VL) 11710 NODE_NAME_CASE(VCPOP_VL) 11711 NODE_NAME_CASE(READ_CSR) 11712 NODE_NAME_CASE(WRITE_CSR) 11713 NODE_NAME_CASE(SWAP_CSR) 11714 } 11715 // clang-format on 11716 return nullptr; 11717 #undef NODE_NAME_CASE 11718 } 11719 11720 /// getConstraintType - Given a constraint letter, return the type of 11721 /// constraint it is for this target. 11722 RISCVTargetLowering::ConstraintType 11723 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 11724 if (Constraint.size() == 1) { 11725 switch (Constraint[0]) { 11726 default: 11727 break; 11728 case 'f': 11729 return C_RegisterClass; 11730 case 'I': 11731 case 'J': 11732 case 'K': 11733 return C_Immediate; 11734 case 'A': 11735 return C_Memory; 11736 case 'S': // A symbolic address 11737 return C_Other; 11738 } 11739 } else { 11740 if (Constraint == "vr" || Constraint == "vm") 11741 return C_RegisterClass; 11742 } 11743 return TargetLowering::getConstraintType(Constraint); 11744 } 11745 11746 std::pair<unsigned, const TargetRegisterClass *> 11747 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11748 StringRef Constraint, 11749 MVT VT) const { 11750 // First, see if this is a constraint that directly corresponds to a 11751 // RISCV register class. 11752 if (Constraint.size() == 1) { 11753 switch (Constraint[0]) { 11754 case 'r': 11755 // TODO: Support fixed vectors up to XLen for P extension? 11756 if (VT.isVector()) 11757 break; 11758 return std::make_pair(0U, &RISCV::GPRRegClass); 11759 case 'f': 11760 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 11761 return std::make_pair(0U, &RISCV::FPR16RegClass); 11762 if (Subtarget.hasStdExtF() && VT == MVT::f32) 11763 return std::make_pair(0U, &RISCV::FPR32RegClass); 11764 if (Subtarget.hasStdExtD() && VT == MVT::f64) 11765 return std::make_pair(0U, &RISCV::FPR64RegClass); 11766 break; 11767 default: 11768 break; 11769 } 11770 } else if (Constraint == "vr") { 11771 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 11772 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11773 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 11774 return std::make_pair(0U, RC); 11775 } 11776 } else if (Constraint == "vm") { 11777 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 11778 return std::make_pair(0U, &RISCV::VMV0RegClass); 11779 } 11780 11781 // Clang will correctly decode the usage of register name aliases into their 11782 // official names. However, other frontends like `rustc` do not. This allows 11783 // users of these frontends to use the ABI names for registers in LLVM-style 11784 // register constraints. 11785 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 11786 .Case("{zero}", RISCV::X0) 11787 .Case("{ra}", RISCV::X1) 11788 .Case("{sp}", RISCV::X2) 11789 .Case("{gp}", RISCV::X3) 11790 .Case("{tp}", RISCV::X4) 11791 .Case("{t0}", RISCV::X5) 11792 .Case("{t1}", RISCV::X6) 11793 .Case("{t2}", RISCV::X7) 11794 .Cases("{s0}", "{fp}", RISCV::X8) 11795 .Case("{s1}", RISCV::X9) 11796 .Case("{a0}", RISCV::X10) 11797 .Case("{a1}", RISCV::X11) 11798 .Case("{a2}", RISCV::X12) 11799 .Case("{a3}", RISCV::X13) 11800 .Case("{a4}", RISCV::X14) 11801 .Case("{a5}", RISCV::X15) 11802 .Case("{a6}", RISCV::X16) 11803 .Case("{a7}", RISCV::X17) 11804 .Case("{s2}", RISCV::X18) 11805 .Case("{s3}", RISCV::X19) 11806 .Case("{s4}", RISCV::X20) 11807 .Case("{s5}", RISCV::X21) 11808 .Case("{s6}", RISCV::X22) 11809 .Case("{s7}", RISCV::X23) 11810 .Case("{s8}", RISCV::X24) 11811 .Case("{s9}", RISCV::X25) 11812 .Case("{s10}", RISCV::X26) 11813 .Case("{s11}", RISCV::X27) 11814 .Case("{t3}", RISCV::X28) 11815 .Case("{t4}", RISCV::X29) 11816 .Case("{t5}", RISCV::X30) 11817 .Case("{t6}", RISCV::X31) 11818 .Default(RISCV::NoRegister); 11819 if (XRegFromAlias != RISCV::NoRegister) 11820 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 11821 11822 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 11823 // TableGen record rather than the AsmName to choose registers for InlineAsm 11824 // constraints, plus we want to match those names to the widest floating point 11825 // register type available, manually select floating point registers here. 11826 // 11827 // The second case is the ABI name of the register, so that frontends can also 11828 // use the ABI names in register constraint lists. 11829 if (Subtarget.hasStdExtF()) { 11830 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 11831 .Cases("{f0}", "{ft0}", RISCV::F0_F) 11832 .Cases("{f1}", "{ft1}", RISCV::F1_F) 11833 .Cases("{f2}", "{ft2}", RISCV::F2_F) 11834 .Cases("{f3}", "{ft3}", RISCV::F3_F) 11835 .Cases("{f4}", "{ft4}", RISCV::F4_F) 11836 .Cases("{f5}", "{ft5}", RISCV::F5_F) 11837 .Cases("{f6}", "{ft6}", RISCV::F6_F) 11838 .Cases("{f7}", "{ft7}", RISCV::F7_F) 11839 .Cases("{f8}", "{fs0}", RISCV::F8_F) 11840 .Cases("{f9}", "{fs1}", RISCV::F9_F) 11841 .Cases("{f10}", "{fa0}", RISCV::F10_F) 11842 .Cases("{f11}", "{fa1}", RISCV::F11_F) 11843 .Cases("{f12}", "{fa2}", RISCV::F12_F) 11844 .Cases("{f13}", "{fa3}", RISCV::F13_F) 11845 .Cases("{f14}", "{fa4}", RISCV::F14_F) 11846 .Cases("{f15}", "{fa5}", RISCV::F15_F) 11847 .Cases("{f16}", "{fa6}", RISCV::F16_F) 11848 .Cases("{f17}", "{fa7}", RISCV::F17_F) 11849 .Cases("{f18}", "{fs2}", RISCV::F18_F) 11850 .Cases("{f19}", "{fs3}", RISCV::F19_F) 11851 .Cases("{f20}", "{fs4}", RISCV::F20_F) 11852 .Cases("{f21}", "{fs5}", RISCV::F21_F) 11853 .Cases("{f22}", "{fs6}", RISCV::F22_F) 11854 .Cases("{f23}", "{fs7}", RISCV::F23_F) 11855 .Cases("{f24}", "{fs8}", RISCV::F24_F) 11856 .Cases("{f25}", "{fs9}", RISCV::F25_F) 11857 .Cases("{f26}", "{fs10}", RISCV::F26_F) 11858 .Cases("{f27}", "{fs11}", RISCV::F27_F) 11859 .Cases("{f28}", "{ft8}", RISCV::F28_F) 11860 .Cases("{f29}", "{ft9}", RISCV::F29_F) 11861 .Cases("{f30}", "{ft10}", RISCV::F30_F) 11862 .Cases("{f31}", "{ft11}", RISCV::F31_F) 11863 .Default(RISCV::NoRegister); 11864 if (FReg != RISCV::NoRegister) { 11865 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 11866 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 11867 unsigned RegNo = FReg - RISCV::F0_F; 11868 unsigned DReg = RISCV::F0_D + RegNo; 11869 return std::make_pair(DReg, &RISCV::FPR64RegClass); 11870 } 11871 if (VT == MVT::f32 || VT == MVT::Other) 11872 return std::make_pair(FReg, &RISCV::FPR32RegClass); 11873 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 11874 unsigned RegNo = FReg - RISCV::F0_F; 11875 unsigned HReg = RISCV::F0_H + RegNo; 11876 return std::make_pair(HReg, &RISCV::FPR16RegClass); 11877 } 11878 } 11879 } 11880 11881 if (Subtarget.hasVInstructions()) { 11882 Register VReg = StringSwitch<Register>(Constraint.lower()) 11883 .Case("{v0}", RISCV::V0) 11884 .Case("{v1}", RISCV::V1) 11885 .Case("{v2}", RISCV::V2) 11886 .Case("{v3}", RISCV::V3) 11887 .Case("{v4}", RISCV::V4) 11888 .Case("{v5}", RISCV::V5) 11889 .Case("{v6}", RISCV::V6) 11890 .Case("{v7}", RISCV::V7) 11891 .Case("{v8}", RISCV::V8) 11892 .Case("{v9}", RISCV::V9) 11893 .Case("{v10}", RISCV::V10) 11894 .Case("{v11}", RISCV::V11) 11895 .Case("{v12}", RISCV::V12) 11896 .Case("{v13}", RISCV::V13) 11897 .Case("{v14}", RISCV::V14) 11898 .Case("{v15}", RISCV::V15) 11899 .Case("{v16}", RISCV::V16) 11900 .Case("{v17}", RISCV::V17) 11901 .Case("{v18}", RISCV::V18) 11902 .Case("{v19}", RISCV::V19) 11903 .Case("{v20}", RISCV::V20) 11904 .Case("{v21}", RISCV::V21) 11905 .Case("{v22}", RISCV::V22) 11906 .Case("{v23}", RISCV::V23) 11907 .Case("{v24}", RISCV::V24) 11908 .Case("{v25}", RISCV::V25) 11909 .Case("{v26}", RISCV::V26) 11910 .Case("{v27}", RISCV::V27) 11911 .Case("{v28}", RISCV::V28) 11912 .Case("{v29}", RISCV::V29) 11913 .Case("{v30}", RISCV::V30) 11914 .Case("{v31}", RISCV::V31) 11915 .Default(RISCV::NoRegister); 11916 if (VReg != RISCV::NoRegister) { 11917 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11918 return std::make_pair(VReg, &RISCV::VMRegClass); 11919 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11920 return std::make_pair(VReg, &RISCV::VRRegClass); 11921 for (const auto *RC : 11922 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11923 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11924 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11925 return std::make_pair(VReg, RC); 11926 } 11927 } 11928 } 11929 } 11930 11931 std::pair<Register, const TargetRegisterClass *> Res = 11932 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11933 11934 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11935 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11936 // Subtarget into account. 11937 if (Res.second == &RISCV::GPRF16RegClass || 11938 Res.second == &RISCV::GPRF32RegClass || 11939 Res.second == &RISCV::GPRF64RegClass) 11940 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11941 11942 return Res; 11943 } 11944 11945 unsigned 11946 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11947 // Currently only support length 1 constraints. 11948 if (ConstraintCode.size() == 1) { 11949 switch (ConstraintCode[0]) { 11950 case 'A': 11951 return InlineAsm::Constraint_A; 11952 default: 11953 break; 11954 } 11955 } 11956 11957 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11958 } 11959 11960 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11961 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11962 SelectionDAG &DAG) const { 11963 // Currently only support length 1 constraints. 11964 if (Constraint.length() == 1) { 11965 switch (Constraint[0]) { 11966 case 'I': 11967 // Validate & create a 12-bit signed immediate operand. 11968 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11969 uint64_t CVal = C->getSExtValue(); 11970 if (isInt<12>(CVal)) 11971 Ops.push_back( 11972 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11973 } 11974 return; 11975 case 'J': 11976 // Validate & create an integer zero operand. 11977 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11978 if (C->getZExtValue() == 0) 11979 Ops.push_back( 11980 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11981 return; 11982 case 'K': 11983 // Validate & create a 5-bit unsigned immediate operand. 11984 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11985 uint64_t CVal = C->getZExtValue(); 11986 if (isUInt<5>(CVal)) 11987 Ops.push_back( 11988 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11989 } 11990 return; 11991 case 'S': 11992 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11993 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11994 GA->getValueType(0))); 11995 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11996 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11997 BA->getValueType(0))); 11998 } 11999 return; 12000 default: 12001 break; 12002 } 12003 } 12004 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 12005 } 12006 12007 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 12008 Instruction *Inst, 12009 AtomicOrdering Ord) const { 12010 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 12011 return Builder.CreateFence(Ord); 12012 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 12013 return Builder.CreateFence(AtomicOrdering::Release); 12014 return nullptr; 12015 } 12016 12017 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 12018 Instruction *Inst, 12019 AtomicOrdering Ord) const { 12020 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 12021 return Builder.CreateFence(AtomicOrdering::Acquire); 12022 return nullptr; 12023 } 12024 12025 TargetLowering::AtomicExpansionKind 12026 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 12027 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 12028 // point operations can't be used in an lr/sc sequence without breaking the 12029 // forward-progress guarantee. 12030 if (AI->isFloatingPointOperation()) 12031 return AtomicExpansionKind::CmpXChg; 12032 12033 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 12034 if (Size == 8 || Size == 16) 12035 return AtomicExpansionKind::MaskedIntrinsic; 12036 return AtomicExpansionKind::None; 12037 } 12038 12039 static Intrinsic::ID 12040 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 12041 if (XLen == 32) { 12042 switch (BinOp) { 12043 default: 12044 llvm_unreachable("Unexpected AtomicRMW BinOp"); 12045 case AtomicRMWInst::Xchg: 12046 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 12047 case AtomicRMWInst::Add: 12048 return Intrinsic::riscv_masked_atomicrmw_add_i32; 12049 case AtomicRMWInst::Sub: 12050 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 12051 case AtomicRMWInst::Nand: 12052 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 12053 case AtomicRMWInst::Max: 12054 return Intrinsic::riscv_masked_atomicrmw_max_i32; 12055 case AtomicRMWInst::Min: 12056 return Intrinsic::riscv_masked_atomicrmw_min_i32; 12057 case AtomicRMWInst::UMax: 12058 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 12059 case AtomicRMWInst::UMin: 12060 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 12061 } 12062 } 12063 12064 if (XLen == 64) { 12065 switch (BinOp) { 12066 default: 12067 llvm_unreachable("Unexpected AtomicRMW BinOp"); 12068 case AtomicRMWInst::Xchg: 12069 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 12070 case AtomicRMWInst::Add: 12071 return Intrinsic::riscv_masked_atomicrmw_add_i64; 12072 case AtomicRMWInst::Sub: 12073 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 12074 case AtomicRMWInst::Nand: 12075 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 12076 case AtomicRMWInst::Max: 12077 return Intrinsic::riscv_masked_atomicrmw_max_i64; 12078 case AtomicRMWInst::Min: 12079 return Intrinsic::riscv_masked_atomicrmw_min_i64; 12080 case AtomicRMWInst::UMax: 12081 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 12082 case AtomicRMWInst::UMin: 12083 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 12084 } 12085 } 12086 12087 llvm_unreachable("Unexpected XLen\n"); 12088 } 12089 12090 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 12091 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 12092 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 12093 unsigned XLen = Subtarget.getXLen(); 12094 Value *Ordering = 12095 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 12096 Type *Tys[] = {AlignedAddr->getType()}; 12097 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 12098 AI->getModule(), 12099 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 12100 12101 if (XLen == 64) { 12102 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 12103 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 12104 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 12105 } 12106 12107 Value *Result; 12108 12109 // Must pass the shift amount needed to sign extend the loaded value prior 12110 // to performing a signed comparison for min/max. ShiftAmt is the number of 12111 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 12112 // is the number of bits to left+right shift the value in order to 12113 // sign-extend. 12114 if (AI->getOperation() == AtomicRMWInst::Min || 12115 AI->getOperation() == AtomicRMWInst::Max) { 12116 const DataLayout &DL = AI->getModule()->getDataLayout(); 12117 unsigned ValWidth = 12118 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 12119 Value *SextShamt = 12120 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 12121 Result = Builder.CreateCall(LrwOpScwLoop, 12122 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 12123 } else { 12124 Result = 12125 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 12126 } 12127 12128 if (XLen == 64) 12129 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 12130 return Result; 12131 } 12132 12133 TargetLowering::AtomicExpansionKind 12134 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 12135 AtomicCmpXchgInst *CI) const { 12136 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 12137 if (Size == 8 || Size == 16) 12138 return AtomicExpansionKind::MaskedIntrinsic; 12139 return AtomicExpansionKind::None; 12140 } 12141 12142 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 12143 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 12144 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 12145 unsigned XLen = Subtarget.getXLen(); 12146 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 12147 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 12148 if (XLen == 64) { 12149 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 12150 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 12151 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 12152 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 12153 } 12154 Type *Tys[] = {AlignedAddr->getType()}; 12155 Function *MaskedCmpXchg = 12156 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 12157 Value *Result = Builder.CreateCall( 12158 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 12159 if (XLen == 64) 12160 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 12161 return Result; 12162 } 12163 12164 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT, 12165 EVT DataVT) const { 12166 return false; 12167 } 12168 12169 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 12170 EVT VT) const { 12171 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 12172 return false; 12173 12174 switch (FPVT.getSimpleVT().SimpleTy) { 12175 case MVT::f16: 12176 return Subtarget.hasStdExtZfh(); 12177 case MVT::f32: 12178 return Subtarget.hasStdExtF(); 12179 case MVT::f64: 12180 return Subtarget.hasStdExtD(); 12181 default: 12182 return false; 12183 } 12184 } 12185 12186 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 12187 // If we are using the small code model, we can reduce size of jump table 12188 // entry to 4 bytes. 12189 if (Subtarget.is64Bit() && !isPositionIndependent() && 12190 getTargetMachine().getCodeModel() == CodeModel::Small) { 12191 return MachineJumpTableInfo::EK_Custom32; 12192 } 12193 return TargetLowering::getJumpTableEncoding(); 12194 } 12195 12196 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 12197 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 12198 unsigned uid, MCContext &Ctx) const { 12199 assert(Subtarget.is64Bit() && !isPositionIndependent() && 12200 getTargetMachine().getCodeModel() == CodeModel::Small); 12201 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 12202 } 12203 12204 bool RISCVTargetLowering::isVScaleKnownToBeAPowerOfTwo() const { 12205 // We define vscale to be VLEN/RVVBitsPerBlock. VLEN is always a power 12206 // of two >= 64, and RVVBitsPerBlock is 64. Thus, vscale must be 12207 // a power of two as well. 12208 // FIXME: This doesn't work for zve32, but that's already broken 12209 // elsewhere for the same reason. 12210 assert(Subtarget.getRealMinVLen() >= 64 && "zve32* unsupported"); 12211 assert(RISCV::RVVBitsPerBlock == 64 && "RVVBitsPerBlock changed, audit needed"); 12212 return true; 12213 } 12214 12215 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 12216 EVT VT) const { 12217 VT = VT.getScalarType(); 12218 12219 if (!VT.isSimple()) 12220 return false; 12221 12222 switch (VT.getSimpleVT().SimpleTy) { 12223 case MVT::f16: 12224 return Subtarget.hasStdExtZfh(); 12225 case MVT::f32: 12226 return Subtarget.hasStdExtF(); 12227 case MVT::f64: 12228 return Subtarget.hasStdExtD(); 12229 default: 12230 break; 12231 } 12232 12233 return false; 12234 } 12235 12236 Register RISCVTargetLowering::getExceptionPointerRegister( 12237 const Constant *PersonalityFn) const { 12238 return RISCV::X10; 12239 } 12240 12241 Register RISCVTargetLowering::getExceptionSelectorRegister( 12242 const Constant *PersonalityFn) const { 12243 return RISCV::X11; 12244 } 12245 12246 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 12247 // Return false to suppress the unnecessary extensions if the LibCall 12248 // arguments or return value is f32 type for LP64 ABI. 12249 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 12250 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 12251 return false; 12252 12253 return true; 12254 } 12255 12256 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 12257 if (Subtarget.is64Bit() && Type == MVT::i32) 12258 return true; 12259 12260 return IsSigned; 12261 } 12262 12263 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 12264 SDValue C) const { 12265 // Check integral scalar types. 12266 const bool HasExtMOrZmmul = 12267 Subtarget.hasStdExtM() || Subtarget.hasStdExtZmmul(); 12268 if (VT.isScalarInteger()) { 12269 // Omit the optimization if the sub target has the M extension and the data 12270 // size exceeds XLen. 12271 if (HasExtMOrZmmul && VT.getSizeInBits() > Subtarget.getXLen()) 12272 return false; 12273 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 12274 // Break the MUL to a SLLI and an ADD/SUB. 12275 const APInt &Imm = ConstNode->getAPIntValue(); 12276 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 12277 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 12278 return true; 12279 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 12280 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 12281 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 12282 (Imm - 8).isPowerOf2())) 12283 return true; 12284 // Omit the following optimization if the sub target has the M extension 12285 // and the data size >= XLen. 12286 if (HasExtMOrZmmul && VT.getSizeInBits() >= Subtarget.getXLen()) 12287 return false; 12288 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 12289 // a pair of LUI/ADDI. 12290 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 12291 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 12292 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 12293 (1 - ImmS).isPowerOf2()) 12294 return true; 12295 } 12296 } 12297 } 12298 12299 return false; 12300 } 12301 12302 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 12303 SDValue ConstNode) const { 12304 // Let the DAGCombiner decide for vectors. 12305 EVT VT = AddNode.getValueType(); 12306 if (VT.isVector()) 12307 return true; 12308 12309 // Let the DAGCombiner decide for larger types. 12310 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 12311 return true; 12312 12313 // It is worse if c1 is simm12 while c1*c2 is not. 12314 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 12315 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 12316 const APInt &C1 = C1Node->getAPIntValue(); 12317 const APInt &C2 = C2Node->getAPIntValue(); 12318 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 12319 return false; 12320 12321 // Default to true and let the DAGCombiner decide. 12322 return true; 12323 } 12324 12325 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 12326 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 12327 bool *Fast) const { 12328 if (!VT.isVector()) { 12329 if (Fast) 12330 *Fast = false; 12331 return Subtarget.enableUnalignedScalarMem(); 12332 } 12333 12334 // All vector implementations must support element alignment 12335 EVT ElemVT = VT.getVectorElementType(); 12336 if (Alignment >= ElemVT.getStoreSize()) { 12337 if (Fast) 12338 *Fast = true; 12339 return true; 12340 } 12341 12342 return false; 12343 } 12344 12345 bool RISCVTargetLowering::splitValueIntoRegisterParts( 12346 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 12347 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 12348 bool IsABIRegCopy = CC.has_value(); 12349 EVT ValueVT = Val.getValueType(); 12350 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 12351 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 12352 // and cast to f32. 12353 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 12354 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 12355 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 12356 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 12357 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 12358 Parts[0] = Val; 12359 return true; 12360 } 12361 12362 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 12363 LLVMContext &Context = *DAG.getContext(); 12364 EVT ValueEltVT = ValueVT.getVectorElementType(); 12365 EVT PartEltVT = PartVT.getVectorElementType(); 12366 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 12367 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 12368 if (PartVTBitSize % ValueVTBitSize == 0) { 12369 assert(PartVTBitSize >= ValueVTBitSize); 12370 // If the element types are different, bitcast to the same element type of 12371 // PartVT first. 12372 // Give an example here, we want copy a <vscale x 1 x i8> value to 12373 // <vscale x 4 x i16>. 12374 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 12375 // subvector, then we can bitcast to <vscale x 4 x i16>. 12376 if (ValueEltVT != PartEltVT) { 12377 if (PartVTBitSize > ValueVTBitSize) { 12378 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 12379 assert(Count != 0 && "The number of element should not be zero."); 12380 EVT SameEltTypeVT = 12381 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 12382 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 12383 DAG.getUNDEF(SameEltTypeVT), Val, 12384 DAG.getVectorIdxConstant(0, DL)); 12385 } 12386 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 12387 } else { 12388 Val = 12389 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 12390 Val, DAG.getVectorIdxConstant(0, DL)); 12391 } 12392 Parts[0] = Val; 12393 return true; 12394 } 12395 } 12396 return false; 12397 } 12398 12399 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 12400 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 12401 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 12402 bool IsABIRegCopy = CC.has_value(); 12403 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 12404 SDValue Val = Parts[0]; 12405 12406 // Cast the f32 to i32, truncate to i16, and cast back to f16. 12407 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 12408 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 12409 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 12410 return Val; 12411 } 12412 12413 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 12414 LLVMContext &Context = *DAG.getContext(); 12415 SDValue Val = Parts[0]; 12416 EVT ValueEltVT = ValueVT.getVectorElementType(); 12417 EVT PartEltVT = PartVT.getVectorElementType(); 12418 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 12419 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 12420 if (PartVTBitSize % ValueVTBitSize == 0) { 12421 assert(PartVTBitSize >= ValueVTBitSize); 12422 EVT SameEltTypeVT = ValueVT; 12423 // If the element types are different, convert it to the same element type 12424 // of PartVT. 12425 // Give an example here, we want copy a <vscale x 1 x i8> value from 12426 // <vscale x 4 x i16>. 12427 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 12428 // then we can extract <vscale x 1 x i8>. 12429 if (ValueEltVT != PartEltVT) { 12430 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 12431 assert(Count != 0 && "The number of element should not be zero."); 12432 SameEltTypeVT = 12433 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 12434 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 12435 } 12436 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 12437 DAG.getVectorIdxConstant(0, DL)); 12438 return Val; 12439 } 12440 } 12441 return SDValue(); 12442 } 12443 12444 SDValue 12445 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 12446 SelectionDAG &DAG, 12447 SmallVectorImpl<SDNode *> &Created) const { 12448 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 12449 if (isIntDivCheap(N->getValueType(0), Attr)) 12450 return SDValue(N, 0); // Lower SDIV as SDIV 12451 12452 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 12453 "Unexpected divisor!"); 12454 12455 // Conditional move is needed, so do the transformation iff Zbt is enabled. 12456 if (!Subtarget.hasStdExtZbt()) 12457 return SDValue(); 12458 12459 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 12460 // Besides, more critical path instructions will be generated when dividing 12461 // by 2. So we keep using the original DAGs for these cases. 12462 unsigned Lg2 = Divisor.countTrailingZeros(); 12463 if (Lg2 == 1 || Lg2 >= 12) 12464 return SDValue(); 12465 12466 // fold (sdiv X, pow2) 12467 EVT VT = N->getValueType(0); 12468 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 12469 return SDValue(); 12470 12471 SDLoc DL(N); 12472 SDValue N0 = N->getOperand(0); 12473 SDValue Zero = DAG.getConstant(0, DL, VT); 12474 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 12475 12476 // Add (N0 < 0) ? Pow2 - 1 : 0; 12477 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 12478 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 12479 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 12480 12481 Created.push_back(Cmp.getNode()); 12482 Created.push_back(Add.getNode()); 12483 Created.push_back(Sel.getNode()); 12484 12485 // Divide by pow2. 12486 SDValue SRA = 12487 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 12488 12489 // If we're dividing by a positive value, we're done. Otherwise, we must 12490 // negate the result. 12491 if (Divisor.isNonNegative()) 12492 return SRA; 12493 12494 Created.push_back(SRA.getNode()); 12495 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 12496 } 12497 12498 #define GET_REGISTER_MATCHER 12499 #include "RISCVGenAsmMatcher.inc" 12500 12501 Register 12502 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 12503 const MachineFunction &MF) const { 12504 Register Reg = MatchRegisterAltName(RegName); 12505 if (Reg == RISCV::NoRegister) 12506 Reg = MatchRegisterName(RegName); 12507 if (Reg == RISCV::NoRegister) 12508 report_fatal_error( 12509 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 12510 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 12511 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 12512 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 12513 StringRef(RegName) + "\".")); 12514 return Reg; 12515 } 12516 12517 namespace llvm { 12518 namespace RISCVVIntrinsicsTable { 12519 12520 #define GET_RISCVVIntrinsicsTable_IMPL 12521 #include "RISCVGenSearchableTables.inc" 12522 12523 } // namespace RISCVVIntrinsicsTable 12524 12525 } // namespace llvm 12526