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 // If this is a single bit test that can't be handled by ANDI, shift the 1374 // bit to be tested to the MSB and perform a signed compare with 0. 1375 if (isIntEqualitySetCC(CC) && isNullConstant(RHS) && 1376 LHS.getOpcode() == ISD::AND && LHS.hasOneUse() && 1377 isa<ConstantSDNode>(LHS.getOperand(1))) { 1378 uint64_t Mask = LHS.getConstantOperandVal(1); 1379 if (isPowerOf2_64(Mask) && !isInt<12>(Mask)) { 1380 CC = CC == ISD::SETEQ ? ISD::SETGE : ISD::SETLT; 1381 unsigned ShAmt = LHS.getValueSizeInBits() - 1 - Log2_64(Mask); 1382 LHS = LHS.getOperand(0); 1383 if (ShAmt != 0) 1384 LHS = DAG.getNode(ISD::SHL, DL, LHS.getValueType(), LHS, 1385 DAG.getConstant(ShAmt, DL, LHS.getValueType())); 1386 return; 1387 } 1388 } 1389 1390 // Convert X > -1 to X >= 0. 1391 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1392 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1393 CC = ISD::SETGE; 1394 return; 1395 } 1396 // Convert X < 1 to 0 >= X. 1397 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1398 RHS = LHS; 1399 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1400 CC = ISD::SETGE; 1401 return; 1402 } 1403 1404 switch (CC) { 1405 default: 1406 break; 1407 case ISD::SETGT: 1408 case ISD::SETLE: 1409 case ISD::SETUGT: 1410 case ISD::SETULE: 1411 CC = ISD::getSetCCSwappedOperands(CC); 1412 std::swap(LHS, RHS); 1413 break; 1414 } 1415 } 1416 1417 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1418 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1419 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1420 if (VT.getVectorElementType() == MVT::i1) 1421 KnownSize *= 8; 1422 1423 switch (KnownSize) { 1424 default: 1425 llvm_unreachable("Invalid LMUL."); 1426 case 8: 1427 return RISCVII::VLMUL::LMUL_F8; 1428 case 16: 1429 return RISCVII::VLMUL::LMUL_F4; 1430 case 32: 1431 return RISCVII::VLMUL::LMUL_F2; 1432 case 64: 1433 return RISCVII::VLMUL::LMUL_1; 1434 case 128: 1435 return RISCVII::VLMUL::LMUL_2; 1436 case 256: 1437 return RISCVII::VLMUL::LMUL_4; 1438 case 512: 1439 return RISCVII::VLMUL::LMUL_8; 1440 } 1441 } 1442 1443 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1444 switch (LMul) { 1445 default: 1446 llvm_unreachable("Invalid LMUL."); 1447 case RISCVII::VLMUL::LMUL_F8: 1448 case RISCVII::VLMUL::LMUL_F4: 1449 case RISCVII::VLMUL::LMUL_F2: 1450 case RISCVII::VLMUL::LMUL_1: 1451 return RISCV::VRRegClassID; 1452 case RISCVII::VLMUL::LMUL_2: 1453 return RISCV::VRM2RegClassID; 1454 case RISCVII::VLMUL::LMUL_4: 1455 return RISCV::VRM4RegClassID; 1456 case RISCVII::VLMUL::LMUL_8: 1457 return RISCV::VRM8RegClassID; 1458 } 1459 } 1460 1461 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1462 RISCVII::VLMUL LMUL = getLMUL(VT); 1463 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1464 LMUL == RISCVII::VLMUL::LMUL_F4 || 1465 LMUL == RISCVII::VLMUL::LMUL_F2 || 1466 LMUL == RISCVII::VLMUL::LMUL_1) { 1467 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1468 "Unexpected subreg numbering"); 1469 return RISCV::sub_vrm1_0 + Index; 1470 } 1471 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1472 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1473 "Unexpected subreg numbering"); 1474 return RISCV::sub_vrm2_0 + Index; 1475 } 1476 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1477 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1478 "Unexpected subreg numbering"); 1479 return RISCV::sub_vrm4_0 + Index; 1480 } 1481 llvm_unreachable("Invalid vector type."); 1482 } 1483 1484 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1485 if (VT.getVectorElementType() == MVT::i1) 1486 return RISCV::VRRegClassID; 1487 return getRegClassIDForLMUL(getLMUL(VT)); 1488 } 1489 1490 // Attempt to decompose a subvector insert/extract between VecVT and 1491 // SubVecVT via subregister indices. Returns the subregister index that 1492 // can perform the subvector insert/extract with the given element index, as 1493 // well as the index corresponding to any leftover subvectors that must be 1494 // further inserted/extracted within the register class for SubVecVT. 1495 std::pair<unsigned, unsigned> 1496 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1497 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1498 const RISCVRegisterInfo *TRI) { 1499 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1500 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1501 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1502 "Register classes not ordered"); 1503 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1504 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1505 // Try to compose a subregister index that takes us from the incoming 1506 // LMUL>1 register class down to the outgoing one. At each step we half 1507 // the LMUL: 1508 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1509 // Note that this is not guaranteed to find a subregister index, such as 1510 // when we are extracting from one VR type to another. 1511 unsigned SubRegIdx = RISCV::NoSubRegister; 1512 for (const unsigned RCID : 1513 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1514 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1515 VecVT = VecVT.getHalfNumVectorElementsVT(); 1516 bool IsHi = 1517 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1518 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1519 getSubregIndexByMVT(VecVT, IsHi)); 1520 if (IsHi) 1521 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1522 } 1523 return {SubRegIdx, InsertExtractIdx}; 1524 } 1525 1526 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1527 // stores for those types. 1528 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1529 return !Subtarget.useRVVForFixedLengthVectors() || 1530 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1531 } 1532 1533 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1534 if (ScalarTy->isPointerTy()) 1535 return true; 1536 1537 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1538 ScalarTy->isIntegerTy(32)) 1539 return true; 1540 1541 if (ScalarTy->isIntegerTy(64)) 1542 return Subtarget.hasVInstructionsI64(); 1543 1544 if (ScalarTy->isHalfTy()) 1545 return Subtarget.hasVInstructionsF16(); 1546 if (ScalarTy->isFloatTy()) 1547 return Subtarget.hasVInstructionsF32(); 1548 if (ScalarTy->isDoubleTy()) 1549 return Subtarget.hasVInstructionsF64(); 1550 1551 return false; 1552 } 1553 1554 static SDValue getVLOperand(SDValue Op) { 1555 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1556 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1557 "Unexpected opcode"); 1558 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1559 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1560 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1561 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1562 if (!II) 1563 return SDValue(); 1564 return Op.getOperand(II->VLOperand + 1 + HasChain); 1565 } 1566 1567 static bool useRVVForFixedLengthVectorVT(MVT VT, 1568 const RISCVSubtarget &Subtarget) { 1569 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1570 if (!Subtarget.useRVVForFixedLengthVectors()) 1571 return false; 1572 1573 // We only support a set of vector types with a consistent maximum fixed size 1574 // across all supported vector element types to avoid legalization issues. 1575 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1576 // fixed-length vector type we support is 1024 bytes. 1577 if (VT.getFixedSizeInBits() > 1024 * 8) 1578 return false; 1579 1580 unsigned MinVLen = Subtarget.getRealMinVLen(); 1581 1582 MVT EltVT = VT.getVectorElementType(); 1583 1584 // Don't use RVV for vectors we cannot scalarize if required. 1585 switch (EltVT.SimpleTy) { 1586 // i1 is supported but has different rules. 1587 default: 1588 return false; 1589 case MVT::i1: 1590 // Masks can only use a single register. 1591 if (VT.getVectorNumElements() > MinVLen) 1592 return false; 1593 MinVLen /= 8; 1594 break; 1595 case MVT::i8: 1596 case MVT::i16: 1597 case MVT::i32: 1598 break; 1599 case MVT::i64: 1600 if (!Subtarget.hasVInstructionsI64()) 1601 return false; 1602 break; 1603 case MVT::f16: 1604 if (!Subtarget.hasVInstructionsF16()) 1605 return false; 1606 break; 1607 case MVT::f32: 1608 if (!Subtarget.hasVInstructionsF32()) 1609 return false; 1610 break; 1611 case MVT::f64: 1612 if (!Subtarget.hasVInstructionsF64()) 1613 return false; 1614 break; 1615 } 1616 1617 // Reject elements larger than ELEN. 1618 if (EltVT.getSizeInBits() > Subtarget.getELEN()) 1619 return false; 1620 1621 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1622 // Don't use RVV for types that don't fit. 1623 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1624 return false; 1625 1626 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1627 // the base fixed length RVV support in place. 1628 if (!VT.isPow2VectorType()) 1629 return false; 1630 1631 return true; 1632 } 1633 1634 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1635 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1636 } 1637 1638 // Return the largest legal scalable vector type that matches VT's element type. 1639 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1640 const RISCVSubtarget &Subtarget) { 1641 // This may be called before legal types are setup. 1642 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1643 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1644 "Expected legal fixed length vector!"); 1645 1646 unsigned MinVLen = Subtarget.getRealMinVLen(); 1647 unsigned MaxELen = Subtarget.getELEN(); 1648 1649 MVT EltVT = VT.getVectorElementType(); 1650 switch (EltVT.SimpleTy) { 1651 default: 1652 llvm_unreachable("unexpected element type for RVV container"); 1653 case MVT::i1: 1654 case MVT::i8: 1655 case MVT::i16: 1656 case MVT::i32: 1657 case MVT::i64: 1658 case MVT::f16: 1659 case MVT::f32: 1660 case MVT::f64: { 1661 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1662 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1663 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1664 unsigned NumElts = 1665 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1666 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1667 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1668 return MVT::getScalableVectorVT(EltVT, NumElts); 1669 } 1670 } 1671 } 1672 1673 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1674 const RISCVSubtarget &Subtarget) { 1675 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1676 Subtarget); 1677 } 1678 1679 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1680 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1681 } 1682 1683 // Grow V to consume an entire RVV register. 1684 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1685 const RISCVSubtarget &Subtarget) { 1686 assert(VT.isScalableVector() && 1687 "Expected to convert into a scalable vector!"); 1688 assert(V.getValueType().isFixedLengthVector() && 1689 "Expected a fixed length vector operand!"); 1690 SDLoc DL(V); 1691 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1692 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1693 } 1694 1695 // Shrink V so it's just big enough to maintain a VT's worth of data. 1696 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1697 const RISCVSubtarget &Subtarget) { 1698 assert(VT.isFixedLengthVector() && 1699 "Expected to convert into a fixed length vector!"); 1700 assert(V.getValueType().isScalableVector() && 1701 "Expected a scalable vector operand!"); 1702 SDLoc DL(V); 1703 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1704 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1705 } 1706 1707 /// Return the type of the mask type suitable for masking the provided 1708 /// vector type. This is simply an i1 element type vector of the same 1709 /// (possibly scalable) length. 1710 static MVT getMaskTypeFor(MVT VecVT) { 1711 assert(VecVT.isVector()); 1712 ElementCount EC = VecVT.getVectorElementCount(); 1713 return MVT::getVectorVT(MVT::i1, EC); 1714 } 1715 1716 /// Creates an all ones mask suitable for masking a vector of type VecTy with 1717 /// vector length VL. . 1718 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL, 1719 SelectionDAG &DAG) { 1720 MVT MaskVT = getMaskTypeFor(VecVT); 1721 return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1722 } 1723 1724 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1725 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1726 // the vector type that it is contained in. 1727 static std::pair<SDValue, SDValue> 1728 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1729 const RISCVSubtarget &Subtarget) { 1730 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1731 MVT XLenVT = Subtarget.getXLenVT(); 1732 SDValue VL = VecVT.isFixedLengthVector() 1733 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1734 : DAG.getRegister(RISCV::X0, XLenVT); 1735 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 1736 return {Mask, VL}; 1737 } 1738 1739 // As above but assuming the given type is a scalable vector type. 1740 static std::pair<SDValue, SDValue> 1741 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1742 const RISCVSubtarget &Subtarget) { 1743 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1744 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1745 } 1746 1747 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1748 // of either is (currently) supported. This can get us into an infinite loop 1749 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1750 // as a ..., etc. 1751 // Until either (or both) of these can reliably lower any node, reporting that 1752 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1753 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1754 // which is not desirable. 1755 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1756 EVT VT, unsigned DefinedValues) const { 1757 return false; 1758 } 1759 1760 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1761 const RISCVSubtarget &Subtarget) { 1762 // RISCV FP-to-int conversions saturate to the destination register size, but 1763 // don't produce 0 for nan. We can use a conversion instruction and fix the 1764 // nan case with a compare and a select. 1765 SDValue Src = Op.getOperand(0); 1766 1767 EVT DstVT = Op.getValueType(); 1768 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1769 1770 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1771 unsigned Opc; 1772 if (SatVT == DstVT) 1773 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1774 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1775 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1776 else 1777 return SDValue(); 1778 // FIXME: Support other SatVTs by clamping before or after the conversion. 1779 1780 SDLoc DL(Op); 1781 SDValue FpToInt = DAG.getNode( 1782 Opc, DL, DstVT, Src, 1783 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1784 1785 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1786 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1787 } 1788 1789 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1790 // and back. Taking care to avoid converting values that are nan or already 1791 // correct. 1792 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1793 // have FRM dependencies modeled yet. 1794 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1795 MVT VT = Op.getSimpleValueType(); 1796 assert(VT.isVector() && "Unexpected type"); 1797 1798 SDLoc DL(Op); 1799 1800 // Freeze the source since we are increasing the number of uses. 1801 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1802 1803 // Truncate to integer and convert back to FP. 1804 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1805 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1806 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1807 1808 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1809 1810 if (Op.getOpcode() == ISD::FCEIL) { 1811 // If the truncated value is the greater than or equal to the original 1812 // value, we've computed the ceil. Otherwise, we went the wrong way and 1813 // need to increase by 1. 1814 // FIXME: This should use a masked operation. Handle here or in isel? 1815 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1816 DAG.getConstantFP(1.0, DL, VT)); 1817 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1818 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1819 } else if (Op.getOpcode() == ISD::FFLOOR) { 1820 // If the truncated value is the less than or equal to the original value, 1821 // we've computed the floor. Otherwise, we went the wrong way and need to 1822 // decrease by 1. 1823 // FIXME: This should use a masked operation. Handle here or in isel? 1824 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1825 DAG.getConstantFP(1.0, DL, VT)); 1826 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1827 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1828 } 1829 1830 // Restore the original sign so that -0.0 is preserved. 1831 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1832 1833 // Determine the largest integer that can be represented exactly. This and 1834 // values larger than it don't have any fractional bits so don't need to 1835 // be converted. 1836 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1837 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1838 APFloat MaxVal = APFloat(FltSem); 1839 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1840 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1841 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1842 1843 // If abs(Src) was larger than MaxVal or nan, keep it. 1844 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1845 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1846 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1847 } 1848 1849 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1850 // This mode isn't supported in vector hardware on RISCV. But as long as we 1851 // aren't compiling with trapping math, we can emulate this with 1852 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1853 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1854 // dependencies modeled yet. 1855 // FIXME: Use masked operations to avoid final merge. 1856 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1857 MVT VT = Op.getSimpleValueType(); 1858 assert(VT.isVector() && "Unexpected type"); 1859 1860 SDLoc DL(Op); 1861 1862 // Freeze the source since we are increasing the number of uses. 1863 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1864 1865 // We do the conversion on the absolute value and fix the sign at the end. 1866 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1867 1868 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1869 bool Ignored; 1870 APFloat Point5Pred = APFloat(0.5f); 1871 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1872 Point5Pred.next(/*nextDown*/ true); 1873 1874 // Add the adjustment. 1875 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1876 DAG.getConstantFP(Point5Pred, DL, VT)); 1877 1878 // Truncate to integer and convert back to fp. 1879 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1880 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1881 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1882 1883 // Restore the original sign. 1884 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1885 1886 // Determine the largest integer that can be represented exactly. This and 1887 // values larger than it don't have any fractional bits so don't need to 1888 // be converted. 1889 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1890 APFloat MaxVal = APFloat(FltSem); 1891 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1892 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1893 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1894 1895 // If abs(Src) was larger than MaxVal or nan, keep it. 1896 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1897 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1898 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1899 } 1900 1901 struct VIDSequence { 1902 int64_t StepNumerator; 1903 unsigned StepDenominator; 1904 int64_t Addend; 1905 }; 1906 1907 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1908 // to the (non-zero) step S and start value X. This can be then lowered as the 1909 // RVV sequence (VID * S) + X, for example. 1910 // The step S is represented as an integer numerator divided by a positive 1911 // denominator. Note that the implementation currently only identifies 1912 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1913 // cannot detect 2/3, for example. 1914 // Note that this method will also match potentially unappealing index 1915 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1916 // determine whether this is worth generating code for. 1917 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1918 unsigned NumElts = Op.getNumOperands(); 1919 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1920 if (!Op.getValueType().isInteger()) 1921 return None; 1922 1923 Optional<unsigned> SeqStepDenom; 1924 Optional<int64_t> SeqStepNum, SeqAddend; 1925 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1926 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1927 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1928 // Assume undef elements match the sequence; we just have to be careful 1929 // when interpolating across them. 1930 if (Op.getOperand(Idx).isUndef()) 1931 continue; 1932 // The BUILD_VECTOR must be all constants. 1933 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1934 return None; 1935 1936 uint64_t Val = Op.getConstantOperandVal(Idx) & 1937 maskTrailingOnes<uint64_t>(EltSizeInBits); 1938 1939 if (PrevElt) { 1940 // Calculate the step since the last non-undef element, and ensure 1941 // it's consistent across the entire sequence. 1942 unsigned IdxDiff = Idx - PrevElt->second; 1943 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1944 1945 // A zero-value value difference means that we're somewhere in the middle 1946 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1947 // step change before evaluating the sequence. 1948 if (ValDiff == 0) 1949 continue; 1950 1951 int64_t Remainder = ValDiff % IdxDiff; 1952 // Normalize the step if it's greater than 1. 1953 if (Remainder != ValDiff) { 1954 // The difference must cleanly divide the element span. 1955 if (Remainder != 0) 1956 return None; 1957 ValDiff /= IdxDiff; 1958 IdxDiff = 1; 1959 } 1960 1961 if (!SeqStepNum) 1962 SeqStepNum = ValDiff; 1963 else if (ValDiff != SeqStepNum) 1964 return None; 1965 1966 if (!SeqStepDenom) 1967 SeqStepDenom = IdxDiff; 1968 else if (IdxDiff != *SeqStepDenom) 1969 return None; 1970 } 1971 1972 // Record this non-undef element for later. 1973 if (!PrevElt || PrevElt->first != Val) 1974 PrevElt = std::make_pair(Val, Idx); 1975 } 1976 1977 // We need to have logged a step for this to count as a legal index sequence. 1978 if (!SeqStepNum || !SeqStepDenom) 1979 return None; 1980 1981 // Loop back through the sequence and validate elements we might have skipped 1982 // while waiting for a valid step. While doing this, log any sequence addend. 1983 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1984 if (Op.getOperand(Idx).isUndef()) 1985 continue; 1986 uint64_t Val = Op.getConstantOperandVal(Idx) & 1987 maskTrailingOnes<uint64_t>(EltSizeInBits); 1988 uint64_t ExpectedVal = 1989 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1990 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1991 if (!SeqAddend) 1992 SeqAddend = Addend; 1993 else if (Addend != SeqAddend) 1994 return None; 1995 } 1996 1997 assert(SeqAddend && "Must have an addend if we have a step"); 1998 1999 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 2000 } 2001 2002 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 2003 // and lower it as a VRGATHER_VX_VL from the source vector. 2004 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 2005 SelectionDAG &DAG, 2006 const RISCVSubtarget &Subtarget) { 2007 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 2008 return SDValue(); 2009 SDValue Vec = SplatVal.getOperand(0); 2010 // Only perform this optimization on vectors of the same size for simplicity. 2011 // Don't perform this optimization for i1 vectors. 2012 // FIXME: Support i1 vectors, maybe by promoting to i8? 2013 if (Vec.getValueType() != VT || VT.getVectorElementType() == MVT::i1) 2014 return SDValue(); 2015 SDValue Idx = SplatVal.getOperand(1); 2016 // The index must be a legal type. 2017 if (Idx.getValueType() != Subtarget.getXLenVT()) 2018 return SDValue(); 2019 2020 MVT ContainerVT = VT; 2021 if (VT.isFixedLengthVector()) { 2022 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2023 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 2024 } 2025 2026 SDValue Mask, VL; 2027 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2028 2029 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 2030 Idx, Mask, DAG.getUNDEF(ContainerVT), VL); 2031 2032 if (!VT.isFixedLengthVector()) 2033 return Gather; 2034 2035 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2036 } 2037 2038 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 2039 const RISCVSubtarget &Subtarget) { 2040 MVT VT = Op.getSimpleValueType(); 2041 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 2042 2043 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2044 2045 SDLoc DL(Op); 2046 SDValue Mask, VL; 2047 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2048 2049 MVT XLenVT = Subtarget.getXLenVT(); 2050 unsigned NumElts = Op.getNumOperands(); 2051 2052 if (VT.getVectorElementType() == MVT::i1) { 2053 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 2054 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 2055 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 2056 } 2057 2058 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 2059 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 2060 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 2061 } 2062 2063 // Lower constant mask BUILD_VECTORs via an integer vector type, in 2064 // scalar integer chunks whose bit-width depends on the number of mask 2065 // bits and XLEN. 2066 // First, determine the most appropriate scalar integer type to use. This 2067 // is at most XLenVT, but may be shrunk to a smaller vector element type 2068 // according to the size of the final vector - use i8 chunks rather than 2069 // XLenVT if we're producing a v8i1. This results in more consistent 2070 // codegen across RV32 and RV64. 2071 unsigned NumViaIntegerBits = 2072 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 2073 NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN()); 2074 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 2075 // If we have to use more than one INSERT_VECTOR_ELT then this 2076 // optimization is likely to increase code size; avoid peforming it in 2077 // such a case. We can use a load from a constant pool in this case. 2078 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 2079 return SDValue(); 2080 // Now we can create our integer vector type. Note that it may be larger 2081 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 2082 MVT IntegerViaVecVT = 2083 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 2084 divideCeil(NumElts, NumViaIntegerBits)); 2085 2086 uint64_t Bits = 0; 2087 unsigned BitPos = 0, IntegerEltIdx = 0; 2088 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 2089 2090 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 2091 // Once we accumulate enough bits to fill our scalar type, insert into 2092 // our vector and clear our accumulated data. 2093 if (I != 0 && I % NumViaIntegerBits == 0) { 2094 if (NumViaIntegerBits <= 32) 2095 Bits = SignExtend64<32>(Bits); 2096 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2097 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2098 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2099 Bits = 0; 2100 BitPos = 0; 2101 IntegerEltIdx++; 2102 } 2103 SDValue V = Op.getOperand(I); 2104 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2105 Bits |= ((uint64_t)BitValue << BitPos); 2106 } 2107 2108 // Insert the (remaining) scalar value into position in our integer 2109 // vector type. 2110 if (NumViaIntegerBits <= 32) 2111 Bits = SignExtend64<32>(Bits); 2112 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2113 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2114 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2115 2116 if (NumElts < NumViaIntegerBits) { 2117 // If we're producing a smaller vector than our minimum legal integer 2118 // type, bitcast to the equivalent (known-legal) mask type, and extract 2119 // our final mask. 2120 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2121 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2122 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2123 DAG.getConstant(0, DL, XLenVT)); 2124 } else { 2125 // Else we must have produced an integer type with the same size as the 2126 // mask type; bitcast for the final result. 2127 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2128 Vec = DAG.getBitcast(VT, Vec); 2129 } 2130 2131 return Vec; 2132 } 2133 2134 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2135 // vector type, we have a legal equivalently-sized i8 type, so we can use 2136 // that. 2137 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2138 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2139 2140 SDValue WideVec; 2141 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2142 // For a splat, perform a scalar truncate before creating the wider 2143 // vector. 2144 assert(Splat.getValueType() == XLenVT && 2145 "Unexpected type for i1 splat value"); 2146 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2147 DAG.getConstant(1, DL, XLenVT)); 2148 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2149 } else { 2150 SmallVector<SDValue, 8> Ops(Op->op_values()); 2151 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2152 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2153 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2154 } 2155 2156 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2157 } 2158 2159 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2160 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2161 return Gather; 2162 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2163 : RISCVISD::VMV_V_X_VL; 2164 Splat = 2165 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2166 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2167 } 2168 2169 // Try and match index sequences, which we can lower to the vid instruction 2170 // with optional modifications. An all-undef vector is matched by 2171 // getSplatValue, above. 2172 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2173 int64_t StepNumerator = SimpleVID->StepNumerator; 2174 unsigned StepDenominator = SimpleVID->StepDenominator; 2175 int64_t Addend = SimpleVID->Addend; 2176 2177 assert(StepNumerator != 0 && "Invalid step"); 2178 bool Negate = false; 2179 int64_t SplatStepVal = StepNumerator; 2180 unsigned StepOpcode = ISD::MUL; 2181 if (StepNumerator != 1) { 2182 if (isPowerOf2_64(std::abs(StepNumerator))) { 2183 Negate = StepNumerator < 0; 2184 StepOpcode = ISD::SHL; 2185 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2186 } 2187 } 2188 2189 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2190 // threshold since it's the immediate value many RVV instructions accept. 2191 // There is no vmul.vi instruction so ensure multiply constant can fit in 2192 // a single addi instruction. 2193 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2194 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2195 isPowerOf2_32(StepDenominator) && 2196 (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) { 2197 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2198 // Convert right out of the scalable type so we can use standard ISD 2199 // nodes for the rest of the computation. If we used scalable types with 2200 // these, we'd lose the fixed-length vector info and generate worse 2201 // vsetvli code. 2202 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2203 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2204 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2205 SDValue SplatStep = DAG.getSplatBuildVector( 2206 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2207 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2208 } 2209 if (StepDenominator != 1) { 2210 SDValue SplatStep = DAG.getSplatBuildVector( 2211 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2212 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2213 } 2214 if (Addend != 0 || Negate) { 2215 SDValue SplatAddend = DAG.getSplatBuildVector( 2216 VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2217 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2218 } 2219 return VID; 2220 } 2221 } 2222 2223 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2224 // when re-interpreted as a vector with a larger element type. For example, 2225 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2226 // could be instead splat as 2227 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2228 // TODO: This optimization could also work on non-constant splats, but it 2229 // would require bit-manipulation instructions to construct the splat value. 2230 SmallVector<SDValue> Sequence; 2231 unsigned EltBitSize = VT.getScalarSizeInBits(); 2232 const auto *BV = cast<BuildVectorSDNode>(Op); 2233 if (VT.isInteger() && EltBitSize < 64 && 2234 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2235 BV->getRepeatedSequence(Sequence) && 2236 (Sequence.size() * EltBitSize) <= 64) { 2237 unsigned SeqLen = Sequence.size(); 2238 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2239 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2240 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2241 ViaIntVT == MVT::i64) && 2242 "Unexpected sequence type"); 2243 2244 unsigned EltIdx = 0; 2245 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2246 uint64_t SplatValue = 0; 2247 // Construct the amalgamated value which can be splatted as this larger 2248 // vector type. 2249 for (const auto &SeqV : Sequence) { 2250 if (!SeqV.isUndef()) 2251 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2252 << (EltIdx * EltBitSize)); 2253 EltIdx++; 2254 } 2255 2256 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2257 // achieve better constant materializion. 2258 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2259 SplatValue = SignExtend64<32>(SplatValue); 2260 2261 // Since we can't introduce illegal i64 types at this stage, we can only 2262 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2263 // way we can use RVV instructions to splat. 2264 assert((ViaIntVT.bitsLE(XLenVT) || 2265 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2266 "Unexpected bitcast sequence"); 2267 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2268 SDValue ViaVL = 2269 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2270 MVT ViaContainerVT = 2271 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2272 SDValue Splat = 2273 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2274 DAG.getUNDEF(ViaContainerVT), 2275 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2276 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2277 return DAG.getBitcast(VT, Splat); 2278 } 2279 } 2280 2281 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2282 // which constitute a large proportion of the elements. In such cases we can 2283 // splat a vector with the dominant element and make up the shortfall with 2284 // INSERT_VECTOR_ELTs. 2285 // Note that this includes vectors of 2 elements by association. The 2286 // upper-most element is the "dominant" one, allowing us to use a splat to 2287 // "insert" the upper element, and an insert of the lower element at position 2288 // 0, which improves codegen. 2289 SDValue DominantValue; 2290 unsigned MostCommonCount = 0; 2291 DenseMap<SDValue, unsigned> ValueCounts; 2292 unsigned NumUndefElts = 2293 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2294 2295 // Track the number of scalar loads we know we'd be inserting, estimated as 2296 // any non-zero floating-point constant. Other kinds of element are either 2297 // already in registers or are materialized on demand. The threshold at which 2298 // a vector load is more desirable than several scalar materializion and 2299 // vector-insertion instructions is not known. 2300 unsigned NumScalarLoads = 0; 2301 2302 for (SDValue V : Op->op_values()) { 2303 if (V.isUndef()) 2304 continue; 2305 2306 ValueCounts.insert(std::make_pair(V, 0)); 2307 unsigned &Count = ValueCounts[V]; 2308 2309 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2310 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2311 2312 // Is this value dominant? In case of a tie, prefer the highest element as 2313 // it's cheaper to insert near the beginning of a vector than it is at the 2314 // end. 2315 if (++Count >= MostCommonCount) { 2316 DominantValue = V; 2317 MostCommonCount = Count; 2318 } 2319 } 2320 2321 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2322 unsigned NumDefElts = NumElts - NumUndefElts; 2323 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2324 2325 // Don't perform this optimization when optimizing for size, since 2326 // materializing elements and inserting them tends to cause code bloat. 2327 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2328 ((MostCommonCount > DominantValueCountThreshold) || 2329 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2330 // Start by splatting the most common element. 2331 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2332 2333 DenseSet<SDValue> Processed{DominantValue}; 2334 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2335 for (const auto &OpIdx : enumerate(Op->ops())) { 2336 const SDValue &V = OpIdx.value(); 2337 if (V.isUndef() || !Processed.insert(V).second) 2338 continue; 2339 if (ValueCounts[V] == 1) { 2340 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2341 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2342 } else { 2343 // Blend in all instances of this value using a VSELECT, using a 2344 // mask where each bit signals whether that element is the one 2345 // we're after. 2346 SmallVector<SDValue> Ops; 2347 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2348 return DAG.getConstant(V == V1, DL, XLenVT); 2349 }); 2350 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2351 DAG.getBuildVector(SelMaskTy, DL, Ops), 2352 DAG.getSplatBuildVector(VT, DL, V), Vec); 2353 } 2354 } 2355 2356 return Vec; 2357 } 2358 2359 return SDValue(); 2360 } 2361 2362 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2363 SDValue Lo, SDValue Hi, SDValue VL, 2364 SelectionDAG &DAG) { 2365 if (!Passthru) 2366 Passthru = DAG.getUNDEF(VT); 2367 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2368 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2369 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2370 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2371 // node in order to try and match RVV vector/scalar instructions. 2372 if ((LoC >> 31) == HiC) 2373 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2374 2375 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2376 // vmv.v.x whose EEW = 32 to lower it. 2377 auto *Const = dyn_cast<ConstantSDNode>(VL); 2378 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2379 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2380 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2381 // access the subtarget here now. 2382 auto InterVec = DAG.getNode( 2383 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2384 DAG.getRegister(RISCV::X0, MVT::i32)); 2385 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2386 } 2387 } 2388 2389 // Fall back to a stack store and stride x0 vector load. 2390 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2391 Hi, VL); 2392 } 2393 2394 // Called by type legalization to handle splat of i64 on RV32. 2395 // FIXME: We can optimize this when the type has sign or zero bits in one 2396 // of the halves. 2397 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2398 SDValue Scalar, SDValue VL, 2399 SelectionDAG &DAG) { 2400 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2401 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2402 DAG.getConstant(0, DL, MVT::i32)); 2403 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2404 DAG.getConstant(1, DL, MVT::i32)); 2405 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2406 } 2407 2408 // This function lowers a splat of a scalar operand Splat with the vector 2409 // length VL. It ensures the final sequence is type legal, which is useful when 2410 // lowering a splat after type legalization. 2411 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2412 MVT VT, SDLoc DL, SelectionDAG &DAG, 2413 const RISCVSubtarget &Subtarget) { 2414 bool HasPassthru = Passthru && !Passthru.isUndef(); 2415 if (!HasPassthru && !Passthru) 2416 Passthru = DAG.getUNDEF(VT); 2417 if (VT.isFloatingPoint()) { 2418 // If VL is 1, we could use vfmv.s.f. 2419 if (isOneConstant(VL)) 2420 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2421 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2422 } 2423 2424 MVT XLenVT = Subtarget.getXLenVT(); 2425 2426 // Simplest case is that the operand needs to be promoted to XLenVT. 2427 if (Scalar.getValueType().bitsLE(XLenVT)) { 2428 // If the operand is a constant, sign extend to increase our chances 2429 // of being able to use a .vi instruction. ANY_EXTEND would become a 2430 // a zero extend and the simm5 check in isel would fail. 2431 // FIXME: Should we ignore the upper bits in isel instead? 2432 unsigned ExtOpc = 2433 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2434 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2435 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2436 // If VL is 1 and the scalar value won't benefit from immediate, we could 2437 // use vmv.s.x. 2438 if (isOneConstant(VL) && 2439 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2440 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2441 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2442 } 2443 2444 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2445 "Unexpected scalar for splat lowering!"); 2446 2447 if (isOneConstant(VL) && isNullConstant(Scalar)) 2448 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2449 DAG.getConstant(0, DL, XLenVT), VL); 2450 2451 // Otherwise use the more complicated splatting algorithm. 2452 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2453 } 2454 2455 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2456 const RISCVSubtarget &Subtarget) { 2457 // We need to be able to widen elements to the next larger integer type. 2458 if (VT.getScalarSizeInBits() >= Subtarget.getELEN()) 2459 return false; 2460 2461 int Size = Mask.size(); 2462 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2463 2464 int Srcs[] = {-1, -1}; 2465 for (int i = 0; i != Size; ++i) { 2466 // Ignore undef elements. 2467 if (Mask[i] < 0) 2468 continue; 2469 2470 // Is this an even or odd element. 2471 int Pol = i % 2; 2472 2473 // Ensure we consistently use the same source for this element polarity. 2474 int Src = Mask[i] / Size; 2475 if (Srcs[Pol] < 0) 2476 Srcs[Pol] = Src; 2477 if (Srcs[Pol] != Src) 2478 return false; 2479 2480 // Make sure the element within the source is appropriate for this element 2481 // in the destination. 2482 int Elt = Mask[i] % Size; 2483 if (Elt != i / 2) 2484 return false; 2485 } 2486 2487 // We need to find a source for each polarity and they can't be the same. 2488 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2489 return false; 2490 2491 // Swap the sources if the second source was in the even polarity. 2492 SwapSources = Srcs[0] > Srcs[1]; 2493 2494 return true; 2495 } 2496 2497 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2498 /// and then extract the original number of elements from the rotated result. 2499 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2500 /// returned rotation amount is for a rotate right, where elements move from 2501 /// higher elements to lower elements. \p LoSrc indicates the first source 2502 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2503 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2504 /// 0 or 1 if a rotation is found. 2505 /// 2506 /// NOTE: We talk about rotate to the right which matches how bit shift and 2507 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2508 /// and the table below write vectors with the lowest elements on the left. 2509 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2510 int Size = Mask.size(); 2511 2512 // We need to detect various ways of spelling a rotation: 2513 // [11, 12, 13, 14, 15, 0, 1, 2] 2514 // [-1, 12, 13, 14, -1, -1, 1, -1] 2515 // [-1, -1, -1, -1, -1, -1, 1, 2] 2516 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2517 // [-1, 4, 5, 6, -1, -1, 9, -1] 2518 // [-1, 4, 5, 6, -1, -1, -1, -1] 2519 int Rotation = 0; 2520 LoSrc = -1; 2521 HiSrc = -1; 2522 for (int i = 0; i != Size; ++i) { 2523 int M = Mask[i]; 2524 if (M < 0) 2525 continue; 2526 2527 // Determine where a rotate vector would have started. 2528 int StartIdx = i - (M % Size); 2529 // The identity rotation isn't interesting, stop. 2530 if (StartIdx == 0) 2531 return -1; 2532 2533 // If we found the tail of a vector the rotation must be the missing 2534 // front. If we found the head of a vector, it must be how much of the 2535 // head. 2536 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2537 2538 if (Rotation == 0) 2539 Rotation = CandidateRotation; 2540 else if (Rotation != CandidateRotation) 2541 // The rotations don't match, so we can't match this mask. 2542 return -1; 2543 2544 // Compute which value this mask is pointing at. 2545 int MaskSrc = M < Size ? 0 : 1; 2546 2547 // Compute which of the two target values this index should be assigned to. 2548 // This reflects whether the high elements are remaining or the low elemnts 2549 // are remaining. 2550 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2551 2552 // Either set up this value if we've not encountered it before, or check 2553 // that it remains consistent. 2554 if (TargetSrc < 0) 2555 TargetSrc = MaskSrc; 2556 else if (TargetSrc != MaskSrc) 2557 // This may be a rotation, but it pulls from the inputs in some 2558 // unsupported interleaving. 2559 return -1; 2560 } 2561 2562 // Check that we successfully analyzed the mask, and normalize the results. 2563 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2564 assert((LoSrc >= 0 || HiSrc >= 0) && 2565 "Failed to find a rotated input vector!"); 2566 2567 return Rotation; 2568 } 2569 2570 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2571 const RISCVSubtarget &Subtarget) { 2572 SDValue V1 = Op.getOperand(0); 2573 SDValue V2 = Op.getOperand(1); 2574 SDLoc DL(Op); 2575 MVT XLenVT = Subtarget.getXLenVT(); 2576 MVT VT = Op.getSimpleValueType(); 2577 unsigned NumElts = VT.getVectorNumElements(); 2578 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2579 2580 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2581 2582 SDValue TrueMask, VL; 2583 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2584 2585 if (SVN->isSplat()) { 2586 const int Lane = SVN->getSplatIndex(); 2587 if (Lane >= 0) { 2588 MVT SVT = VT.getVectorElementType(); 2589 2590 // Turn splatted vector load into a strided load with an X0 stride. 2591 SDValue V = V1; 2592 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2593 // with undef. 2594 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2595 int Offset = Lane; 2596 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2597 int OpElements = 2598 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2599 V = V.getOperand(Offset / OpElements); 2600 Offset %= OpElements; 2601 } 2602 2603 // We need to ensure the load isn't atomic or volatile. 2604 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2605 auto *Ld = cast<LoadSDNode>(V); 2606 Offset *= SVT.getStoreSize(); 2607 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2608 TypeSize::Fixed(Offset), DL); 2609 2610 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2611 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2612 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2613 SDValue IntID = 2614 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2615 SDValue Ops[] = {Ld->getChain(), 2616 IntID, 2617 DAG.getUNDEF(ContainerVT), 2618 NewAddr, 2619 DAG.getRegister(RISCV::X0, XLenVT), 2620 VL}; 2621 SDValue NewLoad = DAG.getMemIntrinsicNode( 2622 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2623 DAG.getMachineFunction().getMachineMemOperand( 2624 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2625 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2626 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2627 } 2628 2629 // Otherwise use a scalar load and splat. This will give the best 2630 // opportunity to fold a splat into the operation. ISel can turn it into 2631 // the x0 strided load if we aren't able to fold away the select. 2632 if (SVT.isFloatingPoint()) 2633 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2634 Ld->getPointerInfo().getWithOffset(Offset), 2635 Ld->getOriginalAlign(), 2636 Ld->getMemOperand()->getFlags()); 2637 else 2638 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2639 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2640 Ld->getOriginalAlign(), 2641 Ld->getMemOperand()->getFlags()); 2642 DAG.makeEquivalentMemoryOrdering(Ld, V); 2643 2644 unsigned Opc = 2645 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2646 SDValue Splat = 2647 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2648 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2649 } 2650 2651 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2652 assert(Lane < (int)NumElts && "Unexpected lane!"); 2653 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, 2654 V1, DAG.getConstant(Lane, DL, XLenVT), 2655 TrueMask, DAG.getUNDEF(ContainerVT), VL); 2656 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2657 } 2658 } 2659 2660 ArrayRef<int> Mask = SVN->getMask(); 2661 2662 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2663 // be undef which can be handled with a single SLIDEDOWN/UP. 2664 int LoSrc, HiSrc; 2665 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2666 if (Rotation > 0) { 2667 SDValue LoV, HiV; 2668 if (LoSrc >= 0) { 2669 LoV = LoSrc == 0 ? V1 : V2; 2670 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2671 } 2672 if (HiSrc >= 0) { 2673 HiV = HiSrc == 0 ? V1 : V2; 2674 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2675 } 2676 2677 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2678 // to slide LoV up by (NumElts - Rotation). 2679 unsigned InvRotate = NumElts - Rotation; 2680 2681 SDValue Res = DAG.getUNDEF(ContainerVT); 2682 if (HiV) { 2683 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2684 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2685 // causes multiple vsetvlis in some test cases such as lowering 2686 // reduce.mul 2687 SDValue DownVL = VL; 2688 if (LoV) 2689 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2690 Res = 2691 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2692 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2693 } 2694 if (LoV) 2695 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2696 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2697 2698 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2699 } 2700 2701 // Detect an interleave shuffle and lower to 2702 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2703 bool SwapSources; 2704 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2705 // Swap sources if needed. 2706 if (SwapSources) 2707 std::swap(V1, V2); 2708 2709 // Extract the lower half of the vectors. 2710 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2711 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2712 DAG.getConstant(0, DL, XLenVT)); 2713 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2714 DAG.getConstant(0, DL, XLenVT)); 2715 2716 // Double the element width and halve the number of elements in an int type. 2717 unsigned EltBits = VT.getScalarSizeInBits(); 2718 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2719 MVT WideIntVT = 2720 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2721 // Convert this to a scalable vector. We need to base this on the 2722 // destination size to ensure there's always a type with a smaller LMUL. 2723 MVT WideIntContainerVT = 2724 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2725 2726 // Convert sources to scalable vectors with the same element count as the 2727 // larger type. 2728 MVT HalfContainerVT = MVT::getVectorVT( 2729 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2730 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2731 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2732 2733 // Cast sources to integer. 2734 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2735 MVT IntHalfVT = 2736 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2737 V1 = DAG.getBitcast(IntHalfVT, V1); 2738 V2 = DAG.getBitcast(IntHalfVT, V2); 2739 2740 // Freeze V2 since we use it twice and we need to be sure that the add and 2741 // multiply see the same value. 2742 V2 = DAG.getFreeze(V2); 2743 2744 // Recreate TrueMask using the widened type's element count. 2745 TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG); 2746 2747 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2748 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2749 V2, TrueMask, VL); 2750 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2751 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2752 DAG.getUNDEF(IntHalfVT), 2753 DAG.getAllOnesConstant(DL, XLenVT)); 2754 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2755 V2, Multiplier, TrueMask, VL); 2756 // Add the new copies to our previous addition giving us 2^eltbits copies of 2757 // V2. This is equivalent to shifting V2 left by eltbits. This should 2758 // combine with the vwmulu.vv above to form vwmaccu.vv. 2759 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2760 TrueMask, VL); 2761 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2762 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2763 // vector VT. 2764 ContainerVT = 2765 MVT::getVectorVT(VT.getVectorElementType(), 2766 WideIntContainerVT.getVectorElementCount() * 2); 2767 Add = DAG.getBitcast(ContainerVT, Add); 2768 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2769 } 2770 2771 // Detect shuffles which can be re-expressed as vector selects; these are 2772 // shuffles in which each element in the destination is taken from an element 2773 // at the corresponding index in either source vectors. 2774 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2775 int MaskIndex = MaskIdx.value(); 2776 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2777 }); 2778 2779 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2780 2781 SmallVector<SDValue> MaskVals; 2782 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2783 // merged with a second vrgather. 2784 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2785 2786 // By default we preserve the original operand order, and use a mask to 2787 // select LHS as true and RHS as false. However, since RVV vector selects may 2788 // feature splats but only on the LHS, we may choose to invert our mask and 2789 // instead select between RHS and LHS. 2790 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2791 bool InvertMask = IsSelect == SwapOps; 2792 2793 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2794 // half. 2795 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2796 2797 // Now construct the mask that will be used by the vselect or blended 2798 // vrgather operation. For vrgathers, construct the appropriate indices into 2799 // each vector. 2800 for (int MaskIndex : Mask) { 2801 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2802 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2803 if (!IsSelect) { 2804 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2805 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2806 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2807 : DAG.getUNDEF(XLenVT)); 2808 GatherIndicesRHS.push_back( 2809 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2810 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2811 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2812 ++LHSIndexCounts[MaskIndex]; 2813 if (!IsLHSOrUndefIndex) 2814 ++RHSIndexCounts[MaskIndex - NumElts]; 2815 } 2816 } 2817 2818 if (SwapOps) { 2819 std::swap(V1, V2); 2820 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2821 } 2822 2823 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2824 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2825 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2826 2827 if (IsSelect) 2828 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2829 2830 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2831 // On such a large vector we're unable to use i8 as the index type. 2832 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2833 // may involve vector splitting if we're already at LMUL=8, or our 2834 // user-supplied maximum fixed-length LMUL. 2835 return SDValue(); 2836 } 2837 2838 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2839 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2840 MVT IndexVT = VT.changeTypeToInteger(); 2841 // Since we can't introduce illegal index types at this stage, use i16 and 2842 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2843 // than XLenVT. 2844 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2845 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2846 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2847 } 2848 2849 MVT IndexContainerVT = 2850 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2851 2852 SDValue Gather; 2853 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2854 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2855 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2856 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2857 Subtarget); 2858 } else { 2859 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2860 // If only one index is used, we can use a "splat" vrgather. 2861 // TODO: We can splat the most-common index and fix-up any stragglers, if 2862 // that's beneficial. 2863 if (LHSIndexCounts.size() == 1) { 2864 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2865 Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2866 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, 2867 DAG.getUNDEF(ContainerVT), VL); 2868 } else { 2869 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2870 LHSIndices = 2871 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2872 2873 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2874 TrueMask, DAG.getUNDEF(ContainerVT), VL); 2875 } 2876 } 2877 2878 // If a second vector operand is used by this shuffle, blend it in with an 2879 // additional vrgather. 2880 if (!V2.isUndef()) { 2881 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2882 2883 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2884 SelectMask = 2885 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2886 2887 // If only one index is used, we can use a "splat" vrgather. 2888 // TODO: We can splat the most-common index and fix-up any stragglers, if 2889 // that's beneficial. 2890 if (RHSIndexCounts.size() == 1) { 2891 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2892 Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2893 DAG.getConstant(SplatIndex, DL, XLenVT), SelectMask, 2894 Gather, VL); 2895 } else { 2896 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2897 RHSIndices = 2898 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2899 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, 2900 SelectMask, Gather, VL); 2901 } 2902 } 2903 2904 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2905 } 2906 2907 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2908 // Support splats for any type. These should type legalize well. 2909 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2910 return true; 2911 2912 // Only support legal VTs for other shuffles for now. 2913 if (!isTypeLegal(VT)) 2914 return false; 2915 2916 MVT SVT = VT.getSimpleVT(); 2917 2918 bool SwapSources; 2919 int LoSrc, HiSrc; 2920 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2921 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2922 } 2923 2924 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2925 // the exponent. 2926 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2927 MVT VT = Op.getSimpleValueType(); 2928 unsigned EltSize = VT.getScalarSizeInBits(); 2929 SDValue Src = Op.getOperand(0); 2930 SDLoc DL(Op); 2931 2932 // We need a FP type that can represent the value. 2933 // TODO: Use f16 for i8 when possible? 2934 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2935 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2936 2937 // Legal types should have been checked in the RISCVTargetLowering 2938 // constructor. 2939 // TODO: Splitting may make sense in some cases. 2940 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2941 "Expected legal float type!"); 2942 2943 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2944 // The trailing zero count is equal to log2 of this single bit value. 2945 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2946 SDValue Neg = 2947 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2948 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2949 } 2950 2951 // We have a legal FP type, convert to it. 2952 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2953 // Bitcast to integer and shift the exponent to the LSB. 2954 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2955 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2956 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2957 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2958 DAG.getConstant(ShiftAmt, DL, IntVT)); 2959 // Truncate back to original type to allow vnsrl. 2960 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2961 // The exponent contains log2 of the value in biased form. 2962 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2963 2964 // For trailing zeros, we just need to subtract the bias. 2965 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2966 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2967 DAG.getConstant(ExponentBias, DL, VT)); 2968 2969 // For leading zeros, we need to remove the bias and convert from log2 to 2970 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2971 unsigned Adjust = ExponentBias + (EltSize - 1); 2972 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2973 } 2974 2975 // While RVV has alignment restrictions, we should always be able to load as a 2976 // legal equivalently-sized byte-typed vector instead. This method is 2977 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2978 // the load is already correctly-aligned, it returns SDValue(). 2979 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2980 SelectionDAG &DAG) const { 2981 auto *Load = cast<LoadSDNode>(Op); 2982 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2983 2984 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2985 Load->getMemoryVT(), 2986 *Load->getMemOperand())) 2987 return SDValue(); 2988 2989 SDLoc DL(Op); 2990 MVT VT = Op.getSimpleValueType(); 2991 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2992 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2993 "Unexpected unaligned RVV load type"); 2994 MVT NewVT = 2995 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2996 assert(NewVT.isValid() && 2997 "Expecting equally-sized RVV vector types to be legal"); 2998 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2999 Load->getPointerInfo(), Load->getOriginalAlign(), 3000 Load->getMemOperand()->getFlags()); 3001 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 3002 } 3003 3004 // While RVV has alignment restrictions, we should always be able to store as a 3005 // legal equivalently-sized byte-typed vector instead. This method is 3006 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 3007 // returns SDValue() if the store is already correctly aligned. 3008 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 3009 SelectionDAG &DAG) const { 3010 auto *Store = cast<StoreSDNode>(Op); 3011 assert(Store && Store->getValue().getValueType().isVector() && 3012 "Expected vector store"); 3013 3014 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 3015 Store->getMemoryVT(), 3016 *Store->getMemOperand())) 3017 return SDValue(); 3018 3019 SDLoc DL(Op); 3020 SDValue StoredVal = Store->getValue(); 3021 MVT VT = StoredVal.getSimpleValueType(); 3022 unsigned EltSizeBits = VT.getScalarSizeInBits(); 3023 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 3024 "Unexpected unaligned RVV store type"); 3025 MVT NewVT = 3026 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 3027 assert(NewVT.isValid() && 3028 "Expecting equally-sized RVV vector types to be legal"); 3029 StoredVal = DAG.getBitcast(NewVT, StoredVal); 3030 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 3031 Store->getPointerInfo(), Store->getOriginalAlign(), 3032 Store->getMemOperand()->getFlags()); 3033 } 3034 3035 static SDValue lowerConstant(SDValue Op, SelectionDAG &DAG, 3036 const RISCVSubtarget &Subtarget) { 3037 assert(Op.getValueType() == MVT::i64 && "Unexpected VT"); 3038 3039 int64_t Imm = cast<ConstantSDNode>(Op)->getSExtValue(); 3040 3041 // All simm32 constants should be handled by isel. 3042 // NOTE: The getMaxBuildIntsCost call below should return a value >= 2 making 3043 // this check redundant, but small immediates are common so this check 3044 // should have better compile time. 3045 if (isInt<32>(Imm)) 3046 return Op; 3047 3048 // We only need to cost the immediate, if constant pool lowering is enabled. 3049 if (!Subtarget.useConstantPoolForLargeInts()) 3050 return Op; 3051 3052 RISCVMatInt::InstSeq Seq = 3053 RISCVMatInt::generateInstSeq(Imm, Subtarget.getFeatureBits()); 3054 if (Seq.size() <= Subtarget.getMaxBuildIntsCost()) 3055 return Op; 3056 3057 // Expand to a constant pool using the default expansion code. 3058 return SDValue(); 3059 } 3060 3061 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 3062 SelectionDAG &DAG) const { 3063 switch (Op.getOpcode()) { 3064 default: 3065 report_fatal_error("unimplemented operand"); 3066 case ISD::GlobalAddress: 3067 return lowerGlobalAddress(Op, DAG); 3068 case ISD::BlockAddress: 3069 return lowerBlockAddress(Op, DAG); 3070 case ISD::ConstantPool: 3071 return lowerConstantPool(Op, DAG); 3072 case ISD::JumpTable: 3073 return lowerJumpTable(Op, DAG); 3074 case ISD::GlobalTLSAddress: 3075 return lowerGlobalTLSAddress(Op, DAG); 3076 case ISD::Constant: 3077 return lowerConstant(Op, DAG, Subtarget); 3078 case ISD::SELECT: 3079 return lowerSELECT(Op, DAG); 3080 case ISD::BRCOND: 3081 return lowerBRCOND(Op, DAG); 3082 case ISD::VASTART: 3083 return lowerVASTART(Op, DAG); 3084 case ISD::FRAMEADDR: 3085 return lowerFRAMEADDR(Op, DAG); 3086 case ISD::RETURNADDR: 3087 return lowerRETURNADDR(Op, DAG); 3088 case ISD::SHL_PARTS: 3089 return lowerShiftLeftParts(Op, DAG); 3090 case ISD::SRA_PARTS: 3091 return lowerShiftRightParts(Op, DAG, true); 3092 case ISD::SRL_PARTS: 3093 return lowerShiftRightParts(Op, DAG, false); 3094 case ISD::BITCAST: { 3095 SDLoc DL(Op); 3096 EVT VT = Op.getValueType(); 3097 SDValue Op0 = Op.getOperand(0); 3098 EVT Op0VT = Op0.getValueType(); 3099 MVT XLenVT = Subtarget.getXLenVT(); 3100 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 3101 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 3102 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 3103 return FPConv; 3104 } 3105 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 3106 Subtarget.hasStdExtF()) { 3107 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 3108 SDValue FPConv = 3109 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 3110 return FPConv; 3111 } 3112 3113 // Consider other scalar<->scalar casts as legal if the types are legal. 3114 // Otherwise expand them. 3115 if (!VT.isVector() && !Op0VT.isVector()) { 3116 if (isTypeLegal(VT) && isTypeLegal(Op0VT)) 3117 return Op; 3118 return SDValue(); 3119 } 3120 3121 assert(!VT.isScalableVector() && !Op0VT.isScalableVector() && 3122 "Unexpected types"); 3123 3124 if (VT.isFixedLengthVector()) { 3125 // We can handle fixed length vector bitcasts with a simple replacement 3126 // in isel. 3127 if (Op0VT.isFixedLengthVector()) 3128 return Op; 3129 // When bitcasting from scalar to fixed-length vector, insert the scalar 3130 // into a one-element vector of the result type, and perform a vector 3131 // bitcast. 3132 if (!Op0VT.isVector()) { 3133 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 3134 if (!isTypeLegal(BVT)) 3135 return SDValue(); 3136 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 3137 DAG.getUNDEF(BVT), Op0, 3138 DAG.getConstant(0, DL, XLenVT))); 3139 } 3140 return SDValue(); 3141 } 3142 // Custom-legalize bitcasts from fixed-length vector types to scalar types 3143 // thus: bitcast the vector to a one-element vector type whose element type 3144 // is the same as the result type, and extract the first element. 3145 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 3146 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 3147 if (!isTypeLegal(BVT)) 3148 return SDValue(); 3149 SDValue BVec = DAG.getBitcast(BVT, Op0); 3150 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 3151 DAG.getConstant(0, DL, XLenVT)); 3152 } 3153 return SDValue(); 3154 } 3155 case ISD::INTRINSIC_WO_CHAIN: 3156 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3157 case ISD::INTRINSIC_W_CHAIN: 3158 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3159 case ISD::INTRINSIC_VOID: 3160 return LowerINTRINSIC_VOID(Op, DAG); 3161 case ISD::BSWAP: 3162 case ISD::BITREVERSE: { 3163 MVT VT = Op.getSimpleValueType(); 3164 SDLoc DL(Op); 3165 if (Subtarget.hasStdExtZbp()) { 3166 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3167 // Start with the maximum immediate value which is the bitwidth - 1. 3168 unsigned Imm = VT.getSizeInBits() - 1; 3169 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3170 if (Op.getOpcode() == ISD::BSWAP) 3171 Imm &= ~0x7U; 3172 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3173 DAG.getConstant(Imm, DL, VT)); 3174 } 3175 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3176 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3177 // Expand bitreverse to a bswap(rev8) followed by brev8. 3178 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3179 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3180 // as brev8 by an isel pattern. 3181 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3182 DAG.getConstant(7, DL, VT)); 3183 } 3184 case ISD::FSHL: 3185 case ISD::FSHR: { 3186 MVT VT = Op.getSimpleValueType(); 3187 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3188 SDLoc DL(Op); 3189 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3190 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3191 // accidentally setting the extra bit. 3192 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3193 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3194 DAG.getConstant(ShAmtWidth, DL, VT)); 3195 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3196 // instruction use different orders. fshl will return its first operand for 3197 // shift of zero, fshr will return its second operand. fsl and fsr both 3198 // return rs1 so the ISD nodes need to have different operand orders. 3199 // Shift amount is in rs2. 3200 SDValue Op0 = Op.getOperand(0); 3201 SDValue Op1 = Op.getOperand(1); 3202 unsigned Opc = RISCVISD::FSL; 3203 if (Op.getOpcode() == ISD::FSHR) { 3204 std::swap(Op0, Op1); 3205 Opc = RISCVISD::FSR; 3206 } 3207 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3208 } 3209 case ISD::TRUNCATE: 3210 // Only custom-lower vector truncates 3211 if (!Op.getSimpleValueType().isVector()) 3212 return Op; 3213 return lowerVectorTruncLike(Op, DAG); 3214 case ISD::ANY_EXTEND: 3215 case ISD::ZERO_EXTEND: 3216 if (Op.getOperand(0).getValueType().isVector() && 3217 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3218 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3219 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3220 case ISD::SIGN_EXTEND: 3221 if (Op.getOperand(0).getValueType().isVector() && 3222 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3223 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3224 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3225 case ISD::SPLAT_VECTOR_PARTS: 3226 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3227 case ISD::INSERT_VECTOR_ELT: 3228 return lowerINSERT_VECTOR_ELT(Op, DAG); 3229 case ISD::EXTRACT_VECTOR_ELT: 3230 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3231 case ISD::VSCALE: { 3232 MVT VT = Op.getSimpleValueType(); 3233 SDLoc DL(Op); 3234 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3235 // We define our scalable vector types for lmul=1 to use a 64 bit known 3236 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3237 // vscale as VLENB / 8. 3238 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3239 if (Subtarget.getRealMinVLen() < RISCV::RVVBitsPerBlock) 3240 report_fatal_error("Support for VLEN==32 is incomplete."); 3241 // We assume VLENB is a multiple of 8. We manually choose the best shift 3242 // here because SimplifyDemandedBits isn't always able to simplify it. 3243 uint64_t Val = Op.getConstantOperandVal(0); 3244 if (isPowerOf2_64(Val)) { 3245 uint64_t Log2 = Log2_64(Val); 3246 if (Log2 < 3) 3247 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3248 DAG.getConstant(3 - Log2, DL, VT)); 3249 if (Log2 > 3) 3250 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3251 DAG.getConstant(Log2 - 3, DL, VT)); 3252 return VLENB; 3253 } 3254 // If the multiplier is a multiple of 8, scale it down to avoid needing 3255 // to shift the VLENB value. 3256 if ((Val % 8) == 0) 3257 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3258 DAG.getConstant(Val / 8, DL, VT)); 3259 3260 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3261 DAG.getConstant(3, DL, VT)); 3262 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3263 } 3264 case ISD::FPOWI: { 3265 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3266 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3267 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3268 Op.getOperand(1).getValueType() == MVT::i32) { 3269 SDLoc DL(Op); 3270 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3271 SDValue Powi = 3272 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3273 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3274 DAG.getIntPtrConstant(0, DL)); 3275 } 3276 return SDValue(); 3277 } 3278 case ISD::FP_EXTEND: 3279 case ISD::FP_ROUND: 3280 if (!Op.getValueType().isVector()) 3281 return Op; 3282 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3283 case ISD::FP_TO_SINT: 3284 case ISD::FP_TO_UINT: 3285 case ISD::SINT_TO_FP: 3286 case ISD::UINT_TO_FP: { 3287 // RVV can only do fp<->int conversions to types half/double the size as 3288 // the source. We custom-lower any conversions that do two hops into 3289 // sequences. 3290 MVT VT = Op.getSimpleValueType(); 3291 if (!VT.isVector()) 3292 return Op; 3293 SDLoc DL(Op); 3294 SDValue Src = Op.getOperand(0); 3295 MVT EltVT = VT.getVectorElementType(); 3296 MVT SrcVT = Src.getSimpleValueType(); 3297 MVT SrcEltVT = SrcVT.getVectorElementType(); 3298 unsigned EltSize = EltVT.getSizeInBits(); 3299 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3300 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3301 "Unexpected vector element types"); 3302 3303 bool IsInt2FP = SrcEltVT.isInteger(); 3304 // Widening conversions 3305 if (EltSize > (2 * SrcEltSize)) { 3306 if (IsInt2FP) { 3307 // Do a regular integer sign/zero extension then convert to float. 3308 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), 3309 VT.getVectorElementCount()); 3310 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3311 ? ISD::ZERO_EXTEND 3312 : ISD::SIGN_EXTEND; 3313 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3314 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3315 } 3316 // FP2Int 3317 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3318 // Do one doubling fp_extend then complete the operation by converting 3319 // to int. 3320 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3321 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3322 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3323 } 3324 3325 // Narrowing conversions 3326 if (SrcEltSize > (2 * EltSize)) { 3327 if (IsInt2FP) { 3328 // One narrowing int_to_fp, then an fp_round. 3329 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3330 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3331 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3332 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3333 } 3334 // FP2Int 3335 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3336 // representable by the integer, the result is poison. 3337 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 3338 VT.getVectorElementCount()); 3339 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3340 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3341 } 3342 3343 // Scalable vectors can exit here. Patterns will handle equally-sized 3344 // conversions halving/doubling ones. 3345 if (!VT.isFixedLengthVector()) 3346 return Op; 3347 3348 // For fixed-length vectors we lower to a custom "VL" node. 3349 unsigned RVVOpc = 0; 3350 switch (Op.getOpcode()) { 3351 default: 3352 llvm_unreachable("Impossible opcode"); 3353 case ISD::FP_TO_SINT: 3354 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3355 break; 3356 case ISD::FP_TO_UINT: 3357 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3358 break; 3359 case ISD::SINT_TO_FP: 3360 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3361 break; 3362 case ISD::UINT_TO_FP: 3363 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3364 break; 3365 } 3366 3367 MVT ContainerVT, SrcContainerVT; 3368 // Derive the reference container type from the larger vector type. 3369 if (SrcEltSize > EltSize) { 3370 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3371 ContainerVT = 3372 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3373 } else { 3374 ContainerVT = getContainerForFixedLengthVector(VT); 3375 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3376 } 3377 3378 SDValue Mask, VL; 3379 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3380 3381 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3382 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3383 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3384 } 3385 case ISD::FP_TO_SINT_SAT: 3386 case ISD::FP_TO_UINT_SAT: 3387 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3388 case ISD::FTRUNC: 3389 case ISD::FCEIL: 3390 case ISD::FFLOOR: 3391 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3392 case ISD::FROUND: 3393 return lowerFROUND(Op, DAG); 3394 case ISD::VECREDUCE_ADD: 3395 case ISD::VECREDUCE_UMAX: 3396 case ISD::VECREDUCE_SMAX: 3397 case ISD::VECREDUCE_UMIN: 3398 case ISD::VECREDUCE_SMIN: 3399 return lowerVECREDUCE(Op, DAG); 3400 case ISD::VECREDUCE_AND: 3401 case ISD::VECREDUCE_OR: 3402 case ISD::VECREDUCE_XOR: 3403 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3404 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3405 return lowerVECREDUCE(Op, DAG); 3406 case ISD::VECREDUCE_FADD: 3407 case ISD::VECREDUCE_SEQ_FADD: 3408 case ISD::VECREDUCE_FMIN: 3409 case ISD::VECREDUCE_FMAX: 3410 return lowerFPVECREDUCE(Op, DAG); 3411 case ISD::VP_REDUCE_ADD: 3412 case ISD::VP_REDUCE_UMAX: 3413 case ISD::VP_REDUCE_SMAX: 3414 case ISD::VP_REDUCE_UMIN: 3415 case ISD::VP_REDUCE_SMIN: 3416 case ISD::VP_REDUCE_FADD: 3417 case ISD::VP_REDUCE_SEQ_FADD: 3418 case ISD::VP_REDUCE_FMIN: 3419 case ISD::VP_REDUCE_FMAX: 3420 return lowerVPREDUCE(Op, DAG); 3421 case ISD::VP_REDUCE_AND: 3422 case ISD::VP_REDUCE_OR: 3423 case ISD::VP_REDUCE_XOR: 3424 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3425 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3426 return lowerVPREDUCE(Op, DAG); 3427 case ISD::INSERT_SUBVECTOR: 3428 return lowerINSERT_SUBVECTOR(Op, DAG); 3429 case ISD::EXTRACT_SUBVECTOR: 3430 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3431 case ISD::STEP_VECTOR: 3432 return lowerSTEP_VECTOR(Op, DAG); 3433 case ISD::VECTOR_REVERSE: 3434 return lowerVECTOR_REVERSE(Op, DAG); 3435 case ISD::VECTOR_SPLICE: 3436 return lowerVECTOR_SPLICE(Op, DAG); 3437 case ISD::BUILD_VECTOR: 3438 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3439 case ISD::SPLAT_VECTOR: 3440 if (Op.getValueType().getVectorElementType() == MVT::i1) 3441 return lowerVectorMaskSplat(Op, DAG); 3442 return SDValue(); 3443 case ISD::VECTOR_SHUFFLE: 3444 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3445 case ISD::CONCAT_VECTORS: { 3446 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3447 // better than going through the stack, as the default expansion does. 3448 SDLoc DL(Op); 3449 MVT VT = Op.getSimpleValueType(); 3450 unsigned NumOpElts = 3451 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3452 SDValue Vec = DAG.getUNDEF(VT); 3453 for (const auto &OpIdx : enumerate(Op->ops())) { 3454 SDValue SubVec = OpIdx.value(); 3455 // Don't insert undef subvectors. 3456 if (SubVec.isUndef()) 3457 continue; 3458 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3459 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3460 } 3461 return Vec; 3462 } 3463 case ISD::LOAD: 3464 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3465 return V; 3466 if (Op.getValueType().isFixedLengthVector()) 3467 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3468 return Op; 3469 case ISD::STORE: 3470 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3471 return V; 3472 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3473 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3474 return Op; 3475 case ISD::MLOAD: 3476 case ISD::VP_LOAD: 3477 return lowerMaskedLoad(Op, DAG); 3478 case ISD::MSTORE: 3479 case ISD::VP_STORE: 3480 return lowerMaskedStore(Op, DAG); 3481 case ISD::SETCC: 3482 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3483 case ISD::ADD: 3484 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3485 case ISD::SUB: 3486 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3487 case ISD::MUL: 3488 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3489 case ISD::MULHS: 3490 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3491 case ISD::MULHU: 3492 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3493 case ISD::AND: 3494 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3495 RISCVISD::AND_VL); 3496 case ISD::OR: 3497 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3498 RISCVISD::OR_VL); 3499 case ISD::XOR: 3500 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3501 RISCVISD::XOR_VL); 3502 case ISD::SDIV: 3503 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3504 case ISD::SREM: 3505 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3506 case ISD::UDIV: 3507 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3508 case ISD::UREM: 3509 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3510 case ISD::SHL: 3511 case ISD::SRA: 3512 case ISD::SRL: 3513 if (Op.getSimpleValueType().isFixedLengthVector()) 3514 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3515 // This can be called for an i32 shift amount that needs to be promoted. 3516 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3517 "Unexpected custom legalisation"); 3518 return SDValue(); 3519 case ISD::SADDSAT: 3520 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3521 case ISD::UADDSAT: 3522 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3523 case ISD::SSUBSAT: 3524 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3525 case ISD::USUBSAT: 3526 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3527 case ISD::FADD: 3528 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3529 case ISD::FSUB: 3530 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3531 case ISD::FMUL: 3532 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3533 case ISD::FDIV: 3534 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3535 case ISD::FNEG: 3536 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3537 case ISD::FABS: 3538 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3539 case ISD::FSQRT: 3540 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3541 case ISD::FMA: 3542 return lowerToScalableOp(Op, DAG, RISCVISD::VFMADD_VL); 3543 case ISD::SMIN: 3544 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3545 case ISD::SMAX: 3546 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3547 case ISD::UMIN: 3548 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3549 case ISD::UMAX: 3550 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3551 case ISD::FMINNUM: 3552 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3553 case ISD::FMAXNUM: 3554 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3555 case ISD::ABS: 3556 return lowerABS(Op, DAG); 3557 case ISD::CTLZ_ZERO_UNDEF: 3558 case ISD::CTTZ_ZERO_UNDEF: 3559 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3560 case ISD::VSELECT: 3561 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3562 case ISD::FCOPYSIGN: 3563 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3564 case ISD::MGATHER: 3565 case ISD::VP_GATHER: 3566 return lowerMaskedGather(Op, DAG); 3567 case ISD::MSCATTER: 3568 case ISD::VP_SCATTER: 3569 return lowerMaskedScatter(Op, DAG); 3570 case ISD::FLT_ROUNDS_: 3571 return lowerGET_ROUNDING(Op, DAG); 3572 case ISD::SET_ROUNDING: 3573 return lowerSET_ROUNDING(Op, DAG); 3574 case ISD::EH_DWARF_CFA: 3575 return lowerEH_DWARF_CFA(Op, DAG); 3576 case ISD::VP_SELECT: 3577 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3578 case ISD::VP_MERGE: 3579 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3580 case ISD::VP_ADD: 3581 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3582 case ISD::VP_SUB: 3583 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3584 case ISD::VP_MUL: 3585 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3586 case ISD::VP_SDIV: 3587 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3588 case ISD::VP_UDIV: 3589 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3590 case ISD::VP_SREM: 3591 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3592 case ISD::VP_UREM: 3593 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3594 case ISD::VP_AND: 3595 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3596 case ISD::VP_OR: 3597 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3598 case ISD::VP_XOR: 3599 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3600 case ISD::VP_ASHR: 3601 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3602 case ISD::VP_LSHR: 3603 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3604 case ISD::VP_SHL: 3605 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3606 case ISD::VP_FADD: 3607 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3608 case ISD::VP_FSUB: 3609 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3610 case ISD::VP_FMUL: 3611 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3612 case ISD::VP_FDIV: 3613 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3614 case ISD::VP_FNEG: 3615 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3616 case ISD::VP_FMA: 3617 return lowerVPOp(Op, DAG, RISCVISD::VFMADD_VL); 3618 case ISD::VP_SIGN_EXTEND: 3619 case ISD::VP_ZERO_EXTEND: 3620 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3621 return lowerVPExtMaskOp(Op, DAG); 3622 return lowerVPOp(Op, DAG, 3623 Op.getOpcode() == ISD::VP_SIGN_EXTEND 3624 ? RISCVISD::VSEXT_VL 3625 : RISCVISD::VZEXT_VL); 3626 case ISD::VP_TRUNCATE: 3627 return lowerVectorTruncLike(Op, DAG); 3628 case ISD::VP_FP_EXTEND: 3629 case ISD::VP_FP_ROUND: 3630 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3631 case ISD::VP_FPTOSI: 3632 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL); 3633 case ISD::VP_FPTOUI: 3634 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL); 3635 case ISD::VP_SITOFP: 3636 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL); 3637 case ISD::VP_UITOFP: 3638 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL); 3639 case ISD::VP_SETCC: 3640 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3641 return lowerVPSetCCMaskOp(Op, DAG); 3642 return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL); 3643 } 3644 } 3645 3646 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3647 SelectionDAG &DAG, unsigned Flags) { 3648 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3649 } 3650 3651 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3652 SelectionDAG &DAG, unsigned Flags) { 3653 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3654 Flags); 3655 } 3656 3657 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3658 SelectionDAG &DAG, unsigned Flags) { 3659 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3660 N->getOffset(), Flags); 3661 } 3662 3663 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3664 SelectionDAG &DAG, unsigned Flags) { 3665 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3666 } 3667 3668 template <class NodeTy> 3669 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3670 bool IsLocal) const { 3671 SDLoc DL(N); 3672 EVT Ty = getPointerTy(DAG.getDataLayout()); 3673 3674 if (isPositionIndependent()) { 3675 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3676 if (IsLocal) 3677 // Use PC-relative addressing to access the symbol. This generates the 3678 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3679 // %pcrel_lo(auipc)). 3680 return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr); 3681 3682 // Use PC-relative addressing to access the GOT for this symbol, then load 3683 // the address from the GOT. This generates the pattern (PseudoLA sym), 3684 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3685 MachineFunction &MF = DAG.getMachineFunction(); 3686 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3687 MachinePointerInfo::getGOT(MF), 3688 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3689 MachineMemOperand::MOInvariant, 3690 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3691 SDValue Load = 3692 DAG.getMemIntrinsicNode(RISCVISD::LA, DL, DAG.getVTList(Ty, MVT::Other), 3693 {DAG.getEntryNode(), Addr}, Ty, MemOp); 3694 return Load; 3695 } 3696 3697 switch (getTargetMachine().getCodeModel()) { 3698 default: 3699 report_fatal_error("Unsupported code model for lowering"); 3700 case CodeModel::Small: { 3701 // Generate a sequence for accessing addresses within the first 2 GiB of 3702 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3703 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3704 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3705 SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi); 3706 return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNHi, AddrLo); 3707 } 3708 case CodeModel::Medium: { 3709 // Generate a sequence for accessing addresses within any 2GiB range within 3710 // the address space. This generates the pattern (PseudoLLA sym), which 3711 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3712 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3713 return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr); 3714 } 3715 } 3716 } 3717 3718 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3719 SelectionDAG &DAG) const { 3720 SDLoc DL(Op); 3721 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3722 assert(N->getOffset() == 0 && "unexpected offset in global node"); 3723 return getAddr(N, DAG, N->getGlobal()->isDSOLocal()); 3724 } 3725 3726 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3727 SelectionDAG &DAG) const { 3728 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3729 3730 return getAddr(N, DAG); 3731 } 3732 3733 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3734 SelectionDAG &DAG) const { 3735 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3736 3737 return getAddr(N, DAG); 3738 } 3739 3740 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3741 SelectionDAG &DAG) const { 3742 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3743 3744 return getAddr(N, DAG); 3745 } 3746 3747 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3748 SelectionDAG &DAG, 3749 bool UseGOT) const { 3750 SDLoc DL(N); 3751 EVT Ty = getPointerTy(DAG.getDataLayout()); 3752 const GlobalValue *GV = N->getGlobal(); 3753 MVT XLenVT = Subtarget.getXLenVT(); 3754 3755 if (UseGOT) { 3756 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3757 // load the address from the GOT and add the thread pointer. This generates 3758 // the pattern (PseudoLA_TLS_IE sym), which expands to 3759 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3760 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3761 MachineFunction &MF = DAG.getMachineFunction(); 3762 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3763 MachinePointerInfo::getGOT(MF), 3764 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3765 MachineMemOperand::MOInvariant, 3766 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3767 SDValue Load = DAG.getMemIntrinsicNode( 3768 RISCVISD::LA_TLS_IE, DL, DAG.getVTList(Ty, MVT::Other), 3769 {DAG.getEntryNode(), Addr}, Ty, MemOp); 3770 3771 // Add the thread pointer. 3772 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3773 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3774 } 3775 3776 // Generate a sequence for accessing the address relative to the thread 3777 // pointer, with the appropriate adjustment for the thread pointer offset. 3778 // This generates the pattern 3779 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3780 SDValue AddrHi = 3781 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3782 SDValue AddrAdd = 3783 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3784 SDValue AddrLo = 3785 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3786 3787 SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi); 3788 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3789 SDValue MNAdd = 3790 DAG.getNode(RISCVISD::ADD_TPREL, DL, Ty, MNHi, TPReg, AddrAdd); 3791 return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNAdd, AddrLo); 3792 } 3793 3794 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3795 SelectionDAG &DAG) const { 3796 SDLoc DL(N); 3797 EVT Ty = getPointerTy(DAG.getDataLayout()); 3798 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3799 const GlobalValue *GV = N->getGlobal(); 3800 3801 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3802 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3803 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3804 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3805 SDValue Load = DAG.getNode(RISCVISD::LA_TLS_GD, DL, Ty, Addr); 3806 3807 // Prepare argument list to generate call. 3808 ArgListTy Args; 3809 ArgListEntry Entry; 3810 Entry.Node = Load; 3811 Entry.Ty = CallTy; 3812 Args.push_back(Entry); 3813 3814 // Setup call to __tls_get_addr. 3815 TargetLowering::CallLoweringInfo CLI(DAG); 3816 CLI.setDebugLoc(DL) 3817 .setChain(DAG.getEntryNode()) 3818 .setLibCallee(CallingConv::C, CallTy, 3819 DAG.getExternalSymbol("__tls_get_addr", Ty), 3820 std::move(Args)); 3821 3822 return LowerCallTo(CLI).first; 3823 } 3824 3825 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3826 SelectionDAG &DAG) const { 3827 SDLoc DL(Op); 3828 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3829 assert(N->getOffset() == 0 && "unexpected offset in global node"); 3830 3831 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3832 3833 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3834 CallingConv::GHC) 3835 report_fatal_error("In GHC calling convention TLS is not supported"); 3836 3837 SDValue Addr; 3838 switch (Model) { 3839 case TLSModel::LocalExec: 3840 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3841 break; 3842 case TLSModel::InitialExec: 3843 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3844 break; 3845 case TLSModel::LocalDynamic: 3846 case TLSModel::GeneralDynamic: 3847 Addr = getDynamicTLSAddr(N, DAG); 3848 break; 3849 } 3850 3851 return Addr; 3852 } 3853 3854 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3855 SDValue CondV = Op.getOperand(0); 3856 SDValue TrueV = Op.getOperand(1); 3857 SDValue FalseV = Op.getOperand(2); 3858 SDLoc DL(Op); 3859 MVT VT = Op.getSimpleValueType(); 3860 MVT XLenVT = Subtarget.getXLenVT(); 3861 3862 // Lower vector SELECTs to VSELECTs by splatting the condition. 3863 if (VT.isVector()) { 3864 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3865 SDValue CondSplat = VT.isScalableVector() 3866 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3867 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3868 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3869 } 3870 3871 // If the result type is XLenVT and CondV is the output of a SETCC node 3872 // which also operated on XLenVT inputs, then merge the SETCC node into the 3873 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3874 // compare+branch instructions. i.e.: 3875 // (select (setcc lhs, rhs, cc), truev, falsev) 3876 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3877 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3878 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3879 SDValue LHS = CondV.getOperand(0); 3880 SDValue RHS = CondV.getOperand(1); 3881 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3882 ISD::CondCode CCVal = CC->get(); 3883 3884 // Special case for a select of 2 constants that have a diffence of 1. 3885 // Normally this is done by DAGCombine, but if the select is introduced by 3886 // type legalization or op legalization, we miss it. Restricting to SETLT 3887 // case for now because that is what signed saturating add/sub need. 3888 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3889 // but we would probably want to swap the true/false values if the condition 3890 // is SETGE/SETLE to avoid an XORI. 3891 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3892 CCVal == ISD::SETLT) { 3893 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3894 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3895 if (TrueVal - 1 == FalseVal) 3896 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3897 if (TrueVal + 1 == FalseVal) 3898 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3899 } 3900 3901 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3902 3903 SDValue TargetCC = DAG.getCondCode(CCVal); 3904 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3905 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3906 } 3907 3908 // Otherwise: 3909 // (select condv, truev, falsev) 3910 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3911 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3912 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3913 3914 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3915 3916 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3917 } 3918 3919 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3920 SDValue CondV = Op.getOperand(1); 3921 SDLoc DL(Op); 3922 MVT XLenVT = Subtarget.getXLenVT(); 3923 3924 if (CondV.getOpcode() == ISD::SETCC && 3925 CondV.getOperand(0).getValueType() == XLenVT) { 3926 SDValue LHS = CondV.getOperand(0); 3927 SDValue RHS = CondV.getOperand(1); 3928 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3929 3930 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3931 3932 SDValue TargetCC = DAG.getCondCode(CCVal); 3933 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3934 LHS, RHS, TargetCC, Op.getOperand(2)); 3935 } 3936 3937 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3938 CondV, DAG.getConstant(0, DL, XLenVT), 3939 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3940 } 3941 3942 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3943 MachineFunction &MF = DAG.getMachineFunction(); 3944 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3945 3946 SDLoc DL(Op); 3947 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3948 getPointerTy(MF.getDataLayout())); 3949 3950 // vastart just stores the address of the VarArgsFrameIndex slot into the 3951 // memory location argument. 3952 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3953 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3954 MachinePointerInfo(SV)); 3955 } 3956 3957 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3958 SelectionDAG &DAG) const { 3959 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3960 MachineFunction &MF = DAG.getMachineFunction(); 3961 MachineFrameInfo &MFI = MF.getFrameInfo(); 3962 MFI.setFrameAddressIsTaken(true); 3963 Register FrameReg = RI.getFrameRegister(MF); 3964 int XLenInBytes = Subtarget.getXLen() / 8; 3965 3966 EVT VT = Op.getValueType(); 3967 SDLoc DL(Op); 3968 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3969 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3970 while (Depth--) { 3971 int Offset = -(XLenInBytes * 2); 3972 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3973 DAG.getIntPtrConstant(Offset, DL)); 3974 FrameAddr = 3975 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3976 } 3977 return FrameAddr; 3978 } 3979 3980 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3981 SelectionDAG &DAG) const { 3982 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3983 MachineFunction &MF = DAG.getMachineFunction(); 3984 MachineFrameInfo &MFI = MF.getFrameInfo(); 3985 MFI.setReturnAddressIsTaken(true); 3986 MVT XLenVT = Subtarget.getXLenVT(); 3987 int XLenInBytes = Subtarget.getXLen() / 8; 3988 3989 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3990 return SDValue(); 3991 3992 EVT VT = Op.getValueType(); 3993 SDLoc DL(Op); 3994 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3995 if (Depth) { 3996 int Off = -XLenInBytes; 3997 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3998 SDValue Offset = DAG.getConstant(Off, DL, VT); 3999 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 4000 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 4001 MachinePointerInfo()); 4002 } 4003 4004 // Return the value of the return address register, marking it an implicit 4005 // live-in. 4006 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 4007 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 4008 } 4009 4010 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 4011 SelectionDAG &DAG) const { 4012 SDLoc DL(Op); 4013 SDValue Lo = Op.getOperand(0); 4014 SDValue Hi = Op.getOperand(1); 4015 SDValue Shamt = Op.getOperand(2); 4016 EVT VT = Lo.getValueType(); 4017 4018 // if Shamt-XLEN < 0: // Shamt < XLEN 4019 // Lo = Lo << Shamt 4020 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 4021 // else: 4022 // Lo = 0 4023 // Hi = Lo << (Shamt-XLEN) 4024 4025 SDValue Zero = DAG.getConstant(0, DL, VT); 4026 SDValue One = DAG.getConstant(1, DL, VT); 4027 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4028 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4029 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4030 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4031 4032 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 4033 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 4034 SDValue ShiftRightLo = 4035 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 4036 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 4037 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 4038 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 4039 4040 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4041 4042 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 4043 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4044 4045 SDValue Parts[2] = {Lo, Hi}; 4046 return DAG.getMergeValues(Parts, DL); 4047 } 4048 4049 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 4050 bool IsSRA) const { 4051 SDLoc DL(Op); 4052 SDValue Lo = Op.getOperand(0); 4053 SDValue Hi = Op.getOperand(1); 4054 SDValue Shamt = Op.getOperand(2); 4055 EVT VT = Lo.getValueType(); 4056 4057 // SRA expansion: 4058 // if Shamt-XLEN < 0: // Shamt < XLEN 4059 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4060 // Hi = Hi >>s Shamt 4061 // else: 4062 // Lo = Hi >>s (Shamt-XLEN); 4063 // Hi = Hi >>s (XLEN-1) 4064 // 4065 // SRL expansion: 4066 // if Shamt-XLEN < 0: // Shamt < XLEN 4067 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 4068 // Hi = Hi >>u Shamt 4069 // else: 4070 // Lo = Hi >>u (Shamt-XLEN); 4071 // Hi = 0; 4072 4073 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 4074 4075 SDValue Zero = DAG.getConstant(0, DL, VT); 4076 SDValue One = DAG.getConstant(1, DL, VT); 4077 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 4078 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 4079 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 4080 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 4081 4082 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 4083 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 4084 SDValue ShiftLeftHi = 4085 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 4086 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 4087 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 4088 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 4089 SDValue HiFalse = 4090 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 4091 4092 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4093 4094 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 4095 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4096 4097 SDValue Parts[2] = {Lo, Hi}; 4098 return DAG.getMergeValues(Parts, DL); 4099 } 4100 4101 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 4102 // legal equivalently-sized i8 type, so we can use that as a go-between. 4103 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4104 SelectionDAG &DAG) const { 4105 SDLoc DL(Op); 4106 MVT VT = Op.getSimpleValueType(); 4107 SDValue SplatVal = Op.getOperand(0); 4108 // All-zeros or all-ones splats are handled specially. 4109 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4110 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4111 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4112 } 4113 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4114 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4115 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4116 } 4117 MVT XLenVT = Subtarget.getXLenVT(); 4118 assert(SplatVal.getValueType() == XLenVT && 4119 "Unexpected type for i1 splat value"); 4120 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4121 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4122 DAG.getConstant(1, DL, XLenVT)); 4123 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4124 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4125 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4126 } 4127 4128 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4129 // illegal (currently only vXi64 RV32). 4130 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4131 // them to VMV_V_X_VL. 4132 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4133 SelectionDAG &DAG) const { 4134 SDLoc DL(Op); 4135 MVT VecVT = Op.getSimpleValueType(); 4136 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4137 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4138 4139 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4140 SDValue Lo = Op.getOperand(0); 4141 SDValue Hi = Op.getOperand(1); 4142 4143 if (VecVT.isFixedLengthVector()) { 4144 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4145 SDLoc DL(Op); 4146 SDValue Mask, VL; 4147 std::tie(Mask, VL) = 4148 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4149 4150 SDValue Res = 4151 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4152 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4153 } 4154 4155 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4156 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4157 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4158 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4159 // node in order to try and match RVV vector/scalar instructions. 4160 if ((LoC >> 31) == HiC) 4161 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4162 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4163 } 4164 4165 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4166 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4167 isa<ConstantSDNode>(Hi.getOperand(1)) && 4168 Hi.getConstantOperandVal(1) == 31) 4169 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4170 DAG.getRegister(RISCV::X0, MVT::i32)); 4171 4172 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4173 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4174 DAG.getUNDEF(VecVT), Lo, Hi, 4175 DAG.getRegister(RISCV::X0, MVT::i32)); 4176 } 4177 4178 // Custom-lower extensions from mask vectors by using a vselect either with 1 4179 // for zero/any-extension or -1 for sign-extension: 4180 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4181 // Note that any-extension is lowered identically to zero-extension. 4182 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4183 int64_t ExtTrueVal) const { 4184 SDLoc DL(Op); 4185 MVT VecVT = Op.getSimpleValueType(); 4186 SDValue Src = Op.getOperand(0); 4187 // Only custom-lower extensions from mask types 4188 assert(Src.getValueType().isVector() && 4189 Src.getValueType().getVectorElementType() == MVT::i1); 4190 4191 if (VecVT.isScalableVector()) { 4192 SDValue SplatZero = DAG.getConstant(0, DL, VecVT); 4193 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT); 4194 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4195 } 4196 4197 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4198 MVT I1ContainerVT = 4199 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4200 4201 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4202 4203 SDValue Mask, VL; 4204 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4205 4206 MVT XLenVT = Subtarget.getXLenVT(); 4207 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4208 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4209 4210 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4211 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4212 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4213 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4214 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4215 SplatTrueVal, SplatZero, VL); 4216 4217 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4218 } 4219 4220 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4221 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4222 MVT ExtVT = Op.getSimpleValueType(); 4223 // Only custom-lower extensions from fixed-length vector types. 4224 if (!ExtVT.isFixedLengthVector()) 4225 return Op; 4226 MVT VT = Op.getOperand(0).getSimpleValueType(); 4227 // Grab the canonical container type for the extended type. Infer the smaller 4228 // type from that to ensure the same number of vector elements, as we know 4229 // the LMUL will be sufficient to hold the smaller type. 4230 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4231 // Get the extended container type manually to ensure the same number of 4232 // vector elements between source and dest. 4233 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4234 ContainerExtVT.getVectorElementCount()); 4235 4236 SDValue Op1 = 4237 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4238 4239 SDLoc DL(Op); 4240 SDValue Mask, VL; 4241 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4242 4243 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4244 4245 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4246 } 4247 4248 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4249 // setcc operation: 4250 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4251 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op, 4252 SelectionDAG &DAG) const { 4253 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4254 SDLoc DL(Op); 4255 EVT MaskVT = Op.getValueType(); 4256 // Only expect to custom-lower truncations to mask types 4257 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4258 "Unexpected type for vector mask lowering"); 4259 SDValue Src = Op.getOperand(0); 4260 MVT VecVT = Src.getSimpleValueType(); 4261 SDValue Mask, VL; 4262 if (IsVPTrunc) { 4263 Mask = Op.getOperand(1); 4264 VL = Op.getOperand(2); 4265 } 4266 // If this is a fixed vector, we need to convert it to a scalable vector. 4267 MVT ContainerVT = VecVT; 4268 4269 if (VecVT.isFixedLengthVector()) { 4270 ContainerVT = getContainerForFixedLengthVector(VecVT); 4271 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4272 if (IsVPTrunc) { 4273 MVT MaskContainerVT = 4274 getContainerForFixedLengthVector(Mask.getSimpleValueType()); 4275 Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget); 4276 } 4277 } 4278 4279 if (!IsVPTrunc) { 4280 std::tie(Mask, VL) = 4281 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4282 } 4283 4284 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4285 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4286 4287 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4288 DAG.getUNDEF(ContainerVT), SplatOne, VL); 4289 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4290 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4291 4292 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4293 SDValue Trunc = 4294 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4295 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4296 DAG.getCondCode(ISD::SETNE), Mask, VL); 4297 if (MaskVT.isFixedLengthVector()) 4298 Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4299 return Trunc; 4300 } 4301 4302 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op, 4303 SelectionDAG &DAG) const { 4304 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4305 SDLoc DL(Op); 4306 4307 MVT VT = Op.getSimpleValueType(); 4308 // Only custom-lower vector truncates 4309 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4310 4311 // Truncates to mask types are handled differently 4312 if (VT.getVectorElementType() == MVT::i1) 4313 return lowerVectorMaskTruncLike(Op, DAG); 4314 4315 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 4316 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 4317 // truncate by one power of two at a time. 4318 MVT DstEltVT = VT.getVectorElementType(); 4319 4320 SDValue Src = Op.getOperand(0); 4321 MVT SrcVT = Src.getSimpleValueType(); 4322 MVT SrcEltVT = SrcVT.getVectorElementType(); 4323 4324 assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) && 4325 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 4326 "Unexpected vector truncate lowering"); 4327 4328 MVT ContainerVT = SrcVT; 4329 SDValue Mask, VL; 4330 if (IsVPTrunc) { 4331 Mask = Op.getOperand(1); 4332 VL = Op.getOperand(2); 4333 } 4334 if (SrcVT.isFixedLengthVector()) { 4335 ContainerVT = getContainerForFixedLengthVector(SrcVT); 4336 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4337 if (IsVPTrunc) { 4338 MVT MaskVT = getMaskTypeFor(ContainerVT); 4339 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4340 } 4341 } 4342 4343 SDValue Result = Src; 4344 if (!IsVPTrunc) { 4345 std::tie(Mask, VL) = 4346 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4347 } 4348 4349 LLVMContext &Context = *DAG.getContext(); 4350 const ElementCount Count = ContainerVT.getVectorElementCount(); 4351 do { 4352 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 4353 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 4354 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 4355 Mask, VL); 4356 } while (SrcEltVT != DstEltVT); 4357 4358 if (SrcVT.isFixedLengthVector()) 4359 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4360 4361 return Result; 4362 } 4363 4364 SDValue 4365 RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op, 4366 SelectionDAG &DAG) const { 4367 bool IsVP = 4368 Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND; 4369 bool IsExtend = 4370 Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND; 4371 // RVV can only do truncate fp to types half the size as the source. We 4372 // custom-lower f64->f16 rounds via RVV's round-to-odd float 4373 // conversion instruction. 4374 SDLoc DL(Op); 4375 MVT VT = Op.getSimpleValueType(); 4376 4377 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4378 4379 SDValue Src = Op.getOperand(0); 4380 MVT SrcVT = Src.getSimpleValueType(); 4381 4382 bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 || 4383 SrcVT.getVectorElementType() != MVT::f16); 4384 bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 || 4385 SrcVT.getVectorElementType() != MVT::f64); 4386 4387 bool IsDirectConv = IsDirectExtend || IsDirectTrunc; 4388 4389 // Prepare any fixed-length vector operands. 4390 MVT ContainerVT = VT; 4391 SDValue Mask, VL; 4392 if (IsVP) { 4393 Mask = Op.getOperand(1); 4394 VL = Op.getOperand(2); 4395 } 4396 if (VT.isFixedLengthVector()) { 4397 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 4398 ContainerVT = 4399 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 4400 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 4401 if (IsVP) { 4402 MVT MaskVT = getMaskTypeFor(ContainerVT); 4403 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4404 } 4405 } 4406 4407 if (!IsVP) 4408 std::tie(Mask, VL) = 4409 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4410 4411 unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL; 4412 4413 if (IsDirectConv) { 4414 Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL); 4415 if (VT.isFixedLengthVector()) 4416 Src = convertFromScalableVector(VT, Src, DAG, Subtarget); 4417 return Src; 4418 } 4419 4420 unsigned InterConvOpc = 4421 IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL; 4422 4423 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 4424 SDValue IntermediateConv = 4425 DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL); 4426 SDValue Result = 4427 DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL); 4428 if (VT.isFixedLengthVector()) 4429 return convertFromScalableVector(VT, Result, DAG, Subtarget); 4430 return Result; 4431 } 4432 4433 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4434 // first position of a vector, and that vector is slid up to the insert index. 4435 // By limiting the active vector length to index+1 and merging with the 4436 // original vector (with an undisturbed tail policy for elements >= VL), we 4437 // achieve the desired result of leaving all elements untouched except the one 4438 // at VL-1, which is replaced with the desired value. 4439 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4440 SelectionDAG &DAG) const { 4441 SDLoc DL(Op); 4442 MVT VecVT = Op.getSimpleValueType(); 4443 SDValue Vec = Op.getOperand(0); 4444 SDValue Val = Op.getOperand(1); 4445 SDValue Idx = Op.getOperand(2); 4446 4447 if (VecVT.getVectorElementType() == MVT::i1) { 4448 // FIXME: For now we just promote to an i8 vector and insert into that, 4449 // but this is probably not optimal. 4450 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4451 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4452 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4453 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4454 } 4455 4456 MVT ContainerVT = VecVT; 4457 // If the operand is a fixed-length vector, convert to a scalable one. 4458 if (VecVT.isFixedLengthVector()) { 4459 ContainerVT = getContainerForFixedLengthVector(VecVT); 4460 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4461 } 4462 4463 MVT XLenVT = Subtarget.getXLenVT(); 4464 4465 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4466 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4467 // Even i64-element vectors on RV32 can be lowered without scalar 4468 // legalization if the most-significant 32 bits of the value are not affected 4469 // by the sign-extension of the lower 32 bits. 4470 // TODO: We could also catch sign extensions of a 32-bit value. 4471 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4472 const auto *CVal = cast<ConstantSDNode>(Val); 4473 if (isInt<32>(CVal->getSExtValue())) { 4474 IsLegalInsert = true; 4475 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4476 } 4477 } 4478 4479 SDValue Mask, VL; 4480 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4481 4482 SDValue ValInVec; 4483 4484 if (IsLegalInsert) { 4485 unsigned Opc = 4486 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4487 if (isNullConstant(Idx)) { 4488 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4489 if (!VecVT.isFixedLengthVector()) 4490 return Vec; 4491 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4492 } 4493 ValInVec = 4494 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4495 } else { 4496 // On RV32, i64-element vectors must be specially handled to place the 4497 // value at element 0, by using two vslide1up instructions in sequence on 4498 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4499 // this. 4500 SDValue One = DAG.getConstant(1, DL, XLenVT); 4501 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4502 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4503 MVT I32ContainerVT = 4504 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4505 SDValue I32Mask = 4506 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4507 // Limit the active VL to two. 4508 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4509 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4510 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4511 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4512 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4513 // First slide in the hi value, then the lo in underneath it. 4514 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4515 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4516 I32Mask, InsertI64VL); 4517 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4518 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4519 I32Mask, InsertI64VL); 4520 // Bitcast back to the right container type. 4521 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4522 } 4523 4524 // Now that the value is in a vector, slide it into position. 4525 SDValue InsertVL = 4526 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4527 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4528 ValInVec, Idx, Mask, InsertVL); 4529 if (!VecVT.isFixedLengthVector()) 4530 return Slideup; 4531 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4532 } 4533 4534 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4535 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4536 // types this is done using VMV_X_S to allow us to glean information about the 4537 // sign bits of the result. 4538 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4539 SelectionDAG &DAG) const { 4540 SDLoc DL(Op); 4541 SDValue Idx = Op.getOperand(1); 4542 SDValue Vec = Op.getOperand(0); 4543 EVT EltVT = Op.getValueType(); 4544 MVT VecVT = Vec.getSimpleValueType(); 4545 MVT XLenVT = Subtarget.getXLenVT(); 4546 4547 if (VecVT.getVectorElementType() == MVT::i1) { 4548 if (VecVT.isFixedLengthVector()) { 4549 unsigned NumElts = VecVT.getVectorNumElements(); 4550 if (NumElts >= 8) { 4551 MVT WideEltVT; 4552 unsigned WidenVecLen; 4553 SDValue ExtractElementIdx; 4554 SDValue ExtractBitIdx; 4555 unsigned MaxEEW = Subtarget.getELEN(); 4556 MVT LargestEltVT = MVT::getIntegerVT( 4557 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4558 if (NumElts <= LargestEltVT.getSizeInBits()) { 4559 assert(isPowerOf2_32(NumElts) && 4560 "the number of elements should be power of 2"); 4561 WideEltVT = MVT::getIntegerVT(NumElts); 4562 WidenVecLen = 1; 4563 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4564 ExtractBitIdx = Idx; 4565 } else { 4566 WideEltVT = LargestEltVT; 4567 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4568 // extract element index = index / element width 4569 ExtractElementIdx = DAG.getNode( 4570 ISD::SRL, DL, XLenVT, Idx, 4571 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4572 // mask bit index = index % element width 4573 ExtractBitIdx = DAG.getNode( 4574 ISD::AND, DL, XLenVT, Idx, 4575 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4576 } 4577 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4578 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4579 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4580 Vec, ExtractElementIdx); 4581 // Extract the bit from GPR. 4582 SDValue ShiftRight = 4583 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4584 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4585 DAG.getConstant(1, DL, XLenVT)); 4586 } 4587 } 4588 // Otherwise, promote to an i8 vector and extract from that. 4589 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4590 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4591 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4592 } 4593 4594 // If this is a fixed vector, we need to convert it to a scalable vector. 4595 MVT ContainerVT = VecVT; 4596 if (VecVT.isFixedLengthVector()) { 4597 ContainerVT = getContainerForFixedLengthVector(VecVT); 4598 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4599 } 4600 4601 // If the index is 0, the vector is already in the right position. 4602 if (!isNullConstant(Idx)) { 4603 // Use a VL of 1 to avoid processing more elements than we need. 4604 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4605 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 4606 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4607 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4608 } 4609 4610 if (!EltVT.isInteger()) { 4611 // Floating-point extracts are handled in TableGen. 4612 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4613 DAG.getConstant(0, DL, XLenVT)); 4614 } 4615 4616 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4617 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4618 } 4619 4620 // Some RVV intrinsics may claim that they want an integer operand to be 4621 // promoted or expanded. 4622 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG, 4623 const RISCVSubtarget &Subtarget) { 4624 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4625 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4626 "Unexpected opcode"); 4627 4628 if (!Subtarget.hasVInstructions()) 4629 return SDValue(); 4630 4631 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4632 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4633 SDLoc DL(Op); 4634 4635 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4636 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4637 if (!II || !II->hasScalarOperand()) 4638 return SDValue(); 4639 4640 unsigned SplatOp = II->ScalarOperand + 1 + HasChain; 4641 assert(SplatOp < Op.getNumOperands()); 4642 4643 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4644 SDValue &ScalarOp = Operands[SplatOp]; 4645 MVT OpVT = ScalarOp.getSimpleValueType(); 4646 MVT XLenVT = Subtarget.getXLenVT(); 4647 4648 // If this isn't a scalar, or its type is XLenVT we're done. 4649 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4650 return SDValue(); 4651 4652 // Simplest case is that the operand needs to be promoted to XLenVT. 4653 if (OpVT.bitsLT(XLenVT)) { 4654 // If the operand is a constant, sign extend to increase our chances 4655 // of being able to use a .vi instruction. ANY_EXTEND would become a 4656 // a zero extend and the simm5 check in isel would fail. 4657 // FIXME: Should we ignore the upper bits in isel instead? 4658 unsigned ExtOpc = 4659 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4660 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4661 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4662 } 4663 4664 // Use the previous operand to get the vXi64 VT. The result might be a mask 4665 // VT for compares. Using the previous operand assumes that the previous 4666 // operand will never have a smaller element size than a scalar operand and 4667 // that a widening operation never uses SEW=64. 4668 // NOTE: If this fails the below assert, we can probably just find the 4669 // element count from any operand or result and use it to construct the VT. 4670 assert(II->ScalarOperand > 0 && "Unexpected splat operand!"); 4671 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4672 4673 // The more complex case is when the scalar is larger than XLenVT. 4674 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4675 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4676 4677 // If this is a sign-extended 32-bit value, we can truncate it and rely on the 4678 // instruction to sign-extend since SEW>XLEN. 4679 if (DAG.ComputeNumSignBits(ScalarOp) > 32) { 4680 ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp); 4681 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4682 } 4683 4684 switch (IntNo) { 4685 case Intrinsic::riscv_vslide1up: 4686 case Intrinsic::riscv_vslide1down: 4687 case Intrinsic::riscv_vslide1up_mask: 4688 case Intrinsic::riscv_vslide1down_mask: { 4689 // We need to special case these when the scalar is larger than XLen. 4690 unsigned NumOps = Op.getNumOperands(); 4691 bool IsMasked = NumOps == 7; 4692 4693 // Convert the vector source to the equivalent nxvXi32 vector. 4694 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4695 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4696 4697 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4698 DAG.getConstant(0, DL, XLenVT)); 4699 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4700 DAG.getConstant(1, DL, XLenVT)); 4701 4702 // Double the VL since we halved SEW. 4703 SDValue AVL = getVLOperand(Op); 4704 SDValue I32VL; 4705 4706 // Optimize for constant AVL 4707 if (isa<ConstantSDNode>(AVL)) { 4708 unsigned EltSize = VT.getScalarSizeInBits(); 4709 unsigned MinSize = VT.getSizeInBits().getKnownMinValue(); 4710 4711 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 4712 unsigned MaxVLMAX = 4713 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 4714 4715 unsigned VectorBitsMin = Subtarget.getRealMinVLen(); 4716 unsigned MinVLMAX = 4717 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize); 4718 4719 uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue(); 4720 if (AVLInt <= MinVLMAX) { 4721 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT); 4722 } else if (AVLInt >= 2 * MaxVLMAX) { 4723 // Just set vl to VLMAX in this situation 4724 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT); 4725 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4726 unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits()); 4727 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4728 SDValue SETVLMAX = DAG.getTargetConstant( 4729 Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32); 4730 I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW, 4731 LMUL); 4732 } else { 4733 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl 4734 // is related to the hardware implementation. 4735 // So let the following code handle 4736 } 4737 } 4738 if (!I32VL) { 4739 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT); 4740 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4741 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits()); 4742 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4743 SDValue SETVL = 4744 DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32); 4745 // Using vsetvli instruction to get actually used length which related to 4746 // the hardware implementation 4747 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL, 4748 SEW, LMUL); 4749 I32VL = 4750 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4751 } 4752 4753 SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG); 4754 4755 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4756 // instructions. 4757 SDValue Passthru; 4758 if (IsMasked) 4759 Passthru = DAG.getUNDEF(I32VT); 4760 else 4761 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4762 4763 if (IntNo == Intrinsic::riscv_vslide1up || 4764 IntNo == Intrinsic::riscv_vslide1up_mask) { 4765 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4766 ScalarHi, I32Mask, I32VL); 4767 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4768 ScalarLo, I32Mask, I32VL); 4769 } else { 4770 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4771 ScalarLo, I32Mask, I32VL); 4772 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4773 ScalarHi, I32Mask, I32VL); 4774 } 4775 4776 // Convert back to nxvXi64. 4777 Vec = DAG.getBitcast(VT, Vec); 4778 4779 if (!IsMasked) 4780 return Vec; 4781 // Apply mask after the operation. 4782 SDValue Mask = Operands[NumOps - 3]; 4783 SDValue MaskedOff = Operands[1]; 4784 // Assume Policy operand is the last operand. 4785 uint64_t Policy = 4786 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4787 // We don't need to select maskedoff if it's undef. 4788 if (MaskedOff.isUndef()) 4789 return Vec; 4790 // TAMU 4791 if (Policy == RISCVII::TAIL_AGNOSTIC) 4792 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4793 AVL); 4794 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4795 // It's fine because vmerge does not care mask policy. 4796 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, 4797 AVL); 4798 } 4799 } 4800 4801 // We need to convert the scalar to a splat vector. 4802 SDValue VL = getVLOperand(Op); 4803 assert(VL.getValueType() == XLenVT); 4804 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4805 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4806 } 4807 4808 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4809 SelectionDAG &DAG) const { 4810 unsigned IntNo = Op.getConstantOperandVal(0); 4811 SDLoc DL(Op); 4812 MVT XLenVT = Subtarget.getXLenVT(); 4813 4814 switch (IntNo) { 4815 default: 4816 break; // Don't custom lower most intrinsics. 4817 case Intrinsic::thread_pointer: { 4818 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4819 return DAG.getRegister(RISCV::X4, PtrVT); 4820 } 4821 case Intrinsic::riscv_orc_b: 4822 case Intrinsic::riscv_brev8: { 4823 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4824 unsigned Opc = 4825 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4826 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4827 DAG.getConstant(7, DL, XLenVT)); 4828 } 4829 case Intrinsic::riscv_grev: 4830 case Intrinsic::riscv_gorc: { 4831 unsigned Opc = 4832 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4833 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4834 } 4835 case Intrinsic::riscv_zip: 4836 case Intrinsic::riscv_unzip: { 4837 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4838 // For i32 the immediate is 15. For i64 the immediate is 31. 4839 unsigned Opc = 4840 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4841 unsigned BitWidth = Op.getValueSizeInBits(); 4842 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4843 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4844 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4845 } 4846 case Intrinsic::riscv_shfl: 4847 case Intrinsic::riscv_unshfl: { 4848 unsigned Opc = 4849 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4850 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4851 } 4852 case Intrinsic::riscv_bcompress: 4853 case Intrinsic::riscv_bdecompress: { 4854 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4855 : RISCVISD::BDECOMPRESS; 4856 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4857 } 4858 case Intrinsic::riscv_bfp: 4859 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4860 Op.getOperand(2)); 4861 case Intrinsic::riscv_fsl: 4862 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4863 Op.getOperand(2), Op.getOperand(3)); 4864 case Intrinsic::riscv_fsr: 4865 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4866 Op.getOperand(2), Op.getOperand(3)); 4867 case Intrinsic::riscv_vmv_x_s: 4868 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4869 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4870 Op.getOperand(1)); 4871 case Intrinsic::riscv_vmv_v_x: 4872 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4873 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4874 Subtarget); 4875 case Intrinsic::riscv_vfmv_v_f: 4876 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4877 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4878 case Intrinsic::riscv_vmv_s_x: { 4879 SDValue Scalar = Op.getOperand(2); 4880 4881 if (Scalar.getValueType().bitsLE(XLenVT)) { 4882 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4883 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4884 Op.getOperand(1), Scalar, Op.getOperand(3)); 4885 } 4886 4887 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4888 4889 // This is an i64 value that lives in two scalar registers. We have to 4890 // insert this in a convoluted way. First we build vXi64 splat containing 4891 // the two values that we assemble using some bit math. Next we'll use 4892 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4893 // to merge element 0 from our splat into the source vector. 4894 // FIXME: This is probably not the best way to do this, but it is 4895 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4896 // point. 4897 // sw lo, (a0) 4898 // sw hi, 4(a0) 4899 // vlse vX, (a0) 4900 // 4901 // vid.v vVid 4902 // vmseq.vx mMask, vVid, 0 4903 // vmerge.vvm vDest, vSrc, vVal, mMask 4904 MVT VT = Op.getSimpleValueType(); 4905 SDValue Vec = Op.getOperand(1); 4906 SDValue VL = getVLOperand(Op); 4907 4908 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4909 if (Op.getOperand(1).isUndef()) 4910 return SplattedVal; 4911 SDValue SplattedIdx = 4912 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4913 DAG.getConstant(0, DL, MVT::i32), VL); 4914 4915 MVT MaskVT = getMaskTypeFor(VT); 4916 SDValue Mask = getAllOnesMask(VT, VL, DL, DAG); 4917 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4918 SDValue SelectCond = 4919 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4920 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4921 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4922 Vec, VL); 4923 } 4924 } 4925 4926 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4927 } 4928 4929 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4930 SelectionDAG &DAG) const { 4931 unsigned IntNo = Op.getConstantOperandVal(1); 4932 switch (IntNo) { 4933 default: 4934 break; 4935 case Intrinsic::riscv_masked_strided_load: { 4936 SDLoc DL(Op); 4937 MVT XLenVT = Subtarget.getXLenVT(); 4938 4939 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4940 // the selection of the masked intrinsics doesn't do this for us. 4941 SDValue Mask = Op.getOperand(5); 4942 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4943 4944 MVT VT = Op->getSimpleValueType(0); 4945 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4946 4947 SDValue PassThru = Op.getOperand(2); 4948 if (!IsUnmasked) { 4949 MVT MaskVT = getMaskTypeFor(ContainerVT); 4950 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4951 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4952 } 4953 4954 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4955 4956 SDValue IntID = DAG.getTargetConstant( 4957 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4958 XLenVT); 4959 4960 auto *Load = cast<MemIntrinsicSDNode>(Op); 4961 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4962 if (IsUnmasked) 4963 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4964 else 4965 Ops.push_back(PassThru); 4966 Ops.push_back(Op.getOperand(3)); // Ptr 4967 Ops.push_back(Op.getOperand(4)); // Stride 4968 if (!IsUnmasked) 4969 Ops.push_back(Mask); 4970 Ops.push_back(VL); 4971 if (!IsUnmasked) { 4972 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4973 Ops.push_back(Policy); 4974 } 4975 4976 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4977 SDValue Result = 4978 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4979 Load->getMemoryVT(), Load->getMemOperand()); 4980 SDValue Chain = Result.getValue(1); 4981 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4982 return DAG.getMergeValues({Result, Chain}, DL); 4983 } 4984 case Intrinsic::riscv_seg2_load: 4985 case Intrinsic::riscv_seg3_load: 4986 case Intrinsic::riscv_seg4_load: 4987 case Intrinsic::riscv_seg5_load: 4988 case Intrinsic::riscv_seg6_load: 4989 case Intrinsic::riscv_seg7_load: 4990 case Intrinsic::riscv_seg8_load: { 4991 SDLoc DL(Op); 4992 static const Intrinsic::ID VlsegInts[7] = { 4993 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 4994 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 4995 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 4996 Intrinsic::riscv_vlseg8}; 4997 unsigned NF = Op->getNumValues() - 1; 4998 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 4999 MVT XLenVT = Subtarget.getXLenVT(); 5000 MVT VT = Op->getSimpleValueType(0); 5001 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5002 5003 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5004 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 5005 auto *Load = cast<MemIntrinsicSDNode>(Op); 5006 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 5007 ContainerVTs.push_back(MVT::Other); 5008 SDVTList VTs = DAG.getVTList(ContainerVTs); 5009 SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID}; 5010 Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT)); 5011 Ops.push_back(Op.getOperand(2)); 5012 Ops.push_back(VL); 5013 SDValue Result = 5014 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5015 Load->getMemoryVT(), Load->getMemOperand()); 5016 SmallVector<SDValue, 9> Results; 5017 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 5018 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 5019 DAG, Subtarget)); 5020 Results.push_back(Result.getValue(NF)); 5021 return DAG.getMergeValues(Results, DL); 5022 } 5023 } 5024 5025 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 5026 } 5027 5028 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 5029 SelectionDAG &DAG) const { 5030 unsigned IntNo = Op.getConstantOperandVal(1); 5031 switch (IntNo) { 5032 default: 5033 break; 5034 case Intrinsic::riscv_masked_strided_store: { 5035 SDLoc DL(Op); 5036 MVT XLenVT = Subtarget.getXLenVT(); 5037 5038 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 5039 // the selection of the masked intrinsics doesn't do this for us. 5040 SDValue Mask = Op.getOperand(5); 5041 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5042 5043 SDValue Val = Op.getOperand(2); 5044 MVT VT = Val.getSimpleValueType(); 5045 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5046 5047 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5048 if (!IsUnmasked) { 5049 MVT MaskVT = getMaskTypeFor(ContainerVT); 5050 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5051 } 5052 5053 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5054 5055 SDValue IntID = DAG.getTargetConstant( 5056 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 5057 XLenVT); 5058 5059 auto *Store = cast<MemIntrinsicSDNode>(Op); 5060 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 5061 Ops.push_back(Val); 5062 Ops.push_back(Op.getOperand(3)); // Ptr 5063 Ops.push_back(Op.getOperand(4)); // Stride 5064 if (!IsUnmasked) 5065 Ops.push_back(Mask); 5066 Ops.push_back(VL); 5067 5068 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 5069 Ops, Store->getMemoryVT(), 5070 Store->getMemOperand()); 5071 } 5072 } 5073 5074 return SDValue(); 5075 } 5076 5077 static MVT getLMUL1VT(MVT VT) { 5078 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 5079 "Unexpected vector MVT"); 5080 return MVT::getScalableVectorVT( 5081 VT.getVectorElementType(), 5082 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 5083 } 5084 5085 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 5086 switch (ISDOpcode) { 5087 default: 5088 llvm_unreachable("Unhandled reduction"); 5089 case ISD::VECREDUCE_ADD: 5090 return RISCVISD::VECREDUCE_ADD_VL; 5091 case ISD::VECREDUCE_UMAX: 5092 return RISCVISD::VECREDUCE_UMAX_VL; 5093 case ISD::VECREDUCE_SMAX: 5094 return RISCVISD::VECREDUCE_SMAX_VL; 5095 case ISD::VECREDUCE_UMIN: 5096 return RISCVISD::VECREDUCE_UMIN_VL; 5097 case ISD::VECREDUCE_SMIN: 5098 return RISCVISD::VECREDUCE_SMIN_VL; 5099 case ISD::VECREDUCE_AND: 5100 return RISCVISD::VECREDUCE_AND_VL; 5101 case ISD::VECREDUCE_OR: 5102 return RISCVISD::VECREDUCE_OR_VL; 5103 case ISD::VECREDUCE_XOR: 5104 return RISCVISD::VECREDUCE_XOR_VL; 5105 } 5106 } 5107 5108 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 5109 SelectionDAG &DAG, 5110 bool IsVP) const { 5111 SDLoc DL(Op); 5112 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 5113 MVT VecVT = Vec.getSimpleValueType(); 5114 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 5115 Op.getOpcode() == ISD::VECREDUCE_OR || 5116 Op.getOpcode() == ISD::VECREDUCE_XOR || 5117 Op.getOpcode() == ISD::VP_REDUCE_AND || 5118 Op.getOpcode() == ISD::VP_REDUCE_OR || 5119 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5120 "Unexpected reduction lowering"); 5121 5122 MVT XLenVT = Subtarget.getXLenVT(); 5123 assert(Op.getValueType() == XLenVT && 5124 "Expected reduction output to be legalized to XLenVT"); 5125 5126 MVT ContainerVT = VecVT; 5127 if (VecVT.isFixedLengthVector()) { 5128 ContainerVT = getContainerForFixedLengthVector(VecVT); 5129 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5130 } 5131 5132 SDValue Mask, VL; 5133 if (IsVP) { 5134 Mask = Op.getOperand(2); 5135 VL = Op.getOperand(3); 5136 } else { 5137 std::tie(Mask, VL) = 5138 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5139 } 5140 5141 unsigned BaseOpc; 5142 ISD::CondCode CC; 5143 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5144 5145 switch (Op.getOpcode()) { 5146 default: 5147 llvm_unreachable("Unhandled reduction"); 5148 case ISD::VECREDUCE_AND: 5149 case ISD::VP_REDUCE_AND: { 5150 // vcpop ~x == 0 5151 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5152 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5153 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5154 CC = ISD::SETEQ; 5155 BaseOpc = ISD::AND; 5156 break; 5157 } 5158 case ISD::VECREDUCE_OR: 5159 case ISD::VP_REDUCE_OR: 5160 // vcpop x != 0 5161 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5162 CC = ISD::SETNE; 5163 BaseOpc = ISD::OR; 5164 break; 5165 case ISD::VECREDUCE_XOR: 5166 case ISD::VP_REDUCE_XOR: { 5167 // ((vcpop x) & 1) != 0 5168 SDValue One = DAG.getConstant(1, DL, XLenVT); 5169 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5170 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5171 CC = ISD::SETNE; 5172 BaseOpc = ISD::XOR; 5173 break; 5174 } 5175 } 5176 5177 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5178 5179 if (!IsVP) 5180 return SetCC; 5181 5182 // Now include the start value in the operation. 5183 // Note that we must return the start value when no elements are operated 5184 // upon. The vcpop instructions we've emitted in each case above will return 5185 // 0 for an inactive vector, and so we've already received the neutral value: 5186 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5187 // can simply include the start value. 5188 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5189 } 5190 5191 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5192 SelectionDAG &DAG) const { 5193 SDLoc DL(Op); 5194 SDValue Vec = Op.getOperand(0); 5195 EVT VecEVT = Vec.getValueType(); 5196 5197 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5198 5199 // Due to ordering in legalize types we may have a vector type that needs to 5200 // be split. Do that manually so we can get down to a legal type. 5201 while (getTypeAction(*DAG.getContext(), VecEVT) == 5202 TargetLowering::TypeSplitVector) { 5203 SDValue Lo, Hi; 5204 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5205 VecEVT = Lo.getValueType(); 5206 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5207 } 5208 5209 // TODO: The type may need to be widened rather than split. Or widened before 5210 // it can be split. 5211 if (!isTypeLegal(VecEVT)) 5212 return SDValue(); 5213 5214 MVT VecVT = VecEVT.getSimpleVT(); 5215 MVT VecEltVT = VecVT.getVectorElementType(); 5216 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5217 5218 MVT ContainerVT = VecVT; 5219 if (VecVT.isFixedLengthVector()) { 5220 ContainerVT = getContainerForFixedLengthVector(VecVT); 5221 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5222 } 5223 5224 MVT M1VT = getLMUL1VT(ContainerVT); 5225 MVT XLenVT = Subtarget.getXLenVT(); 5226 5227 SDValue Mask, VL; 5228 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5229 5230 SDValue NeutralElem = 5231 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5232 SDValue IdentitySplat = 5233 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5234 M1VT, DL, DAG, Subtarget); 5235 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5236 IdentitySplat, Mask, VL); 5237 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5238 DAG.getConstant(0, DL, XLenVT)); 5239 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5240 } 5241 5242 // Given a reduction op, this function returns the matching reduction opcode, 5243 // the vector SDValue and the scalar SDValue required to lower this to a 5244 // RISCVISD node. 5245 static std::tuple<unsigned, SDValue, SDValue> 5246 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5247 SDLoc DL(Op); 5248 auto Flags = Op->getFlags(); 5249 unsigned Opcode = Op.getOpcode(); 5250 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5251 switch (Opcode) { 5252 default: 5253 llvm_unreachable("Unhandled reduction"); 5254 case ISD::VECREDUCE_FADD: { 5255 // Use positive zero if we can. It is cheaper to materialize. 5256 SDValue Zero = 5257 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5258 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5259 } 5260 case ISD::VECREDUCE_SEQ_FADD: 5261 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5262 Op.getOperand(0)); 5263 case ISD::VECREDUCE_FMIN: 5264 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5265 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5266 case ISD::VECREDUCE_FMAX: 5267 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5268 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5269 } 5270 } 5271 5272 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5273 SelectionDAG &DAG) const { 5274 SDLoc DL(Op); 5275 MVT VecEltVT = Op.getSimpleValueType(); 5276 5277 unsigned RVVOpcode; 5278 SDValue VectorVal, ScalarVal; 5279 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5280 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5281 MVT VecVT = VectorVal.getSimpleValueType(); 5282 5283 MVT ContainerVT = VecVT; 5284 if (VecVT.isFixedLengthVector()) { 5285 ContainerVT = getContainerForFixedLengthVector(VecVT); 5286 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5287 } 5288 5289 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5290 MVT XLenVT = Subtarget.getXLenVT(); 5291 5292 SDValue Mask, VL; 5293 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5294 5295 SDValue ScalarSplat = 5296 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5297 M1VT, DL, DAG, Subtarget); 5298 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5299 VectorVal, ScalarSplat, Mask, VL); 5300 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5301 DAG.getConstant(0, DL, XLenVT)); 5302 } 5303 5304 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5305 switch (ISDOpcode) { 5306 default: 5307 llvm_unreachable("Unhandled reduction"); 5308 case ISD::VP_REDUCE_ADD: 5309 return RISCVISD::VECREDUCE_ADD_VL; 5310 case ISD::VP_REDUCE_UMAX: 5311 return RISCVISD::VECREDUCE_UMAX_VL; 5312 case ISD::VP_REDUCE_SMAX: 5313 return RISCVISD::VECREDUCE_SMAX_VL; 5314 case ISD::VP_REDUCE_UMIN: 5315 return RISCVISD::VECREDUCE_UMIN_VL; 5316 case ISD::VP_REDUCE_SMIN: 5317 return RISCVISD::VECREDUCE_SMIN_VL; 5318 case ISD::VP_REDUCE_AND: 5319 return RISCVISD::VECREDUCE_AND_VL; 5320 case ISD::VP_REDUCE_OR: 5321 return RISCVISD::VECREDUCE_OR_VL; 5322 case ISD::VP_REDUCE_XOR: 5323 return RISCVISD::VECREDUCE_XOR_VL; 5324 case ISD::VP_REDUCE_FADD: 5325 return RISCVISD::VECREDUCE_FADD_VL; 5326 case ISD::VP_REDUCE_SEQ_FADD: 5327 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5328 case ISD::VP_REDUCE_FMAX: 5329 return RISCVISD::VECREDUCE_FMAX_VL; 5330 case ISD::VP_REDUCE_FMIN: 5331 return RISCVISD::VECREDUCE_FMIN_VL; 5332 } 5333 } 5334 5335 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5336 SelectionDAG &DAG) const { 5337 SDLoc DL(Op); 5338 SDValue Vec = Op.getOperand(1); 5339 EVT VecEVT = Vec.getValueType(); 5340 5341 // TODO: The type may need to be widened rather than split. Or widened before 5342 // it can be split. 5343 if (!isTypeLegal(VecEVT)) 5344 return SDValue(); 5345 5346 MVT VecVT = VecEVT.getSimpleVT(); 5347 MVT VecEltVT = VecVT.getVectorElementType(); 5348 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5349 5350 MVT ContainerVT = VecVT; 5351 if (VecVT.isFixedLengthVector()) { 5352 ContainerVT = getContainerForFixedLengthVector(VecVT); 5353 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5354 } 5355 5356 SDValue VL = Op.getOperand(3); 5357 SDValue Mask = Op.getOperand(2); 5358 5359 MVT M1VT = getLMUL1VT(ContainerVT); 5360 MVT XLenVT = Subtarget.getXLenVT(); 5361 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5362 5363 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5364 DAG.getConstant(1, DL, XLenVT), M1VT, 5365 DL, DAG, Subtarget); 5366 SDValue Reduction = 5367 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5368 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5369 DAG.getConstant(0, DL, XLenVT)); 5370 if (!VecVT.isInteger()) 5371 return Elt0; 5372 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5373 } 5374 5375 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5376 SelectionDAG &DAG) const { 5377 SDValue Vec = Op.getOperand(0); 5378 SDValue SubVec = Op.getOperand(1); 5379 MVT VecVT = Vec.getSimpleValueType(); 5380 MVT SubVecVT = SubVec.getSimpleValueType(); 5381 5382 SDLoc DL(Op); 5383 MVT XLenVT = Subtarget.getXLenVT(); 5384 unsigned OrigIdx = Op.getConstantOperandVal(2); 5385 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5386 5387 // We don't have the ability to slide mask vectors up indexed by their i1 5388 // elements; the smallest we can do is i8. Often we are able to bitcast to 5389 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5390 // into a scalable one, we might not necessarily have enough scalable 5391 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5392 if (SubVecVT.getVectorElementType() == MVT::i1 && 5393 (OrigIdx != 0 || !Vec.isUndef())) { 5394 if (VecVT.getVectorMinNumElements() >= 8 && 5395 SubVecVT.getVectorMinNumElements() >= 8) { 5396 assert(OrigIdx % 8 == 0 && "Invalid index"); 5397 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5398 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5399 "Unexpected mask vector lowering"); 5400 OrigIdx /= 8; 5401 SubVecVT = 5402 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5403 SubVecVT.isScalableVector()); 5404 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5405 VecVT.isScalableVector()); 5406 Vec = DAG.getBitcast(VecVT, Vec); 5407 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5408 } else { 5409 // We can't slide this mask vector up indexed by its i1 elements. 5410 // This poses a problem when we wish to insert a scalable vector which 5411 // can't be re-expressed as a larger type. Just choose the slow path and 5412 // extend to a larger type, then truncate back down. 5413 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5414 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5415 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5416 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5417 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5418 Op.getOperand(2)); 5419 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5420 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5421 } 5422 } 5423 5424 // If the subvector vector is a fixed-length type, we cannot use subregister 5425 // manipulation to simplify the codegen; we don't know which register of a 5426 // LMUL group contains the specific subvector as we only know the minimum 5427 // register size. Therefore we must slide the vector group up the full 5428 // amount. 5429 if (SubVecVT.isFixedLengthVector()) { 5430 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5431 return Op; 5432 MVT ContainerVT = VecVT; 5433 if (VecVT.isFixedLengthVector()) { 5434 ContainerVT = getContainerForFixedLengthVector(VecVT); 5435 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5436 } 5437 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5438 DAG.getUNDEF(ContainerVT), SubVec, 5439 DAG.getConstant(0, DL, XLenVT)); 5440 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5441 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5442 return DAG.getBitcast(Op.getValueType(), SubVec); 5443 } 5444 SDValue Mask = 5445 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5446 // Set the vector length to only the number of elements we care about. Note 5447 // that for slideup this includes the offset. 5448 SDValue VL = 5449 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5450 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5451 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5452 SubVec, SlideupAmt, Mask, VL); 5453 if (VecVT.isFixedLengthVector()) 5454 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5455 return DAG.getBitcast(Op.getValueType(), Slideup); 5456 } 5457 5458 unsigned SubRegIdx, RemIdx; 5459 std::tie(SubRegIdx, RemIdx) = 5460 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5461 VecVT, SubVecVT, OrigIdx, TRI); 5462 5463 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5464 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5465 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5466 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5467 5468 // 1. If the Idx has been completely eliminated and this subvector's size is 5469 // a vector register or a multiple thereof, or the surrounding elements are 5470 // undef, then this is a subvector insert which naturally aligns to a vector 5471 // register. These can easily be handled using subregister manipulation. 5472 // 2. If the subvector is smaller than a vector register, then the insertion 5473 // must preserve the undisturbed elements of the register. We do this by 5474 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5475 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5476 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5477 // LMUL=1 type back into the larger vector (resolving to another subregister 5478 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5479 // to avoid allocating a large register group to hold our subvector. 5480 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5481 return Op; 5482 5483 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5484 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5485 // (in our case undisturbed). This means we can set up a subvector insertion 5486 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5487 // size of the subvector. 5488 MVT InterSubVT = VecVT; 5489 SDValue AlignedExtract = Vec; 5490 unsigned AlignedIdx = OrigIdx - RemIdx; 5491 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5492 InterSubVT = getLMUL1VT(VecVT); 5493 // Extract a subvector equal to the nearest full vector register type. This 5494 // should resolve to a EXTRACT_SUBREG instruction. 5495 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5496 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5497 } 5498 5499 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5500 // For scalable vectors this must be further multiplied by vscale. 5501 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5502 5503 SDValue Mask, VL; 5504 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5505 5506 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5507 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5508 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5509 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5510 5511 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5512 DAG.getUNDEF(InterSubVT), SubVec, 5513 DAG.getConstant(0, DL, XLenVT)); 5514 5515 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5516 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5517 5518 // If required, insert this subvector back into the correct vector register. 5519 // This should resolve to an INSERT_SUBREG instruction. 5520 if (VecVT.bitsGT(InterSubVT)) 5521 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5522 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5523 5524 // We might have bitcast from a mask type: cast back to the original type if 5525 // required. 5526 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5527 } 5528 5529 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5530 SelectionDAG &DAG) const { 5531 SDValue Vec = Op.getOperand(0); 5532 MVT SubVecVT = Op.getSimpleValueType(); 5533 MVT VecVT = Vec.getSimpleValueType(); 5534 5535 SDLoc DL(Op); 5536 MVT XLenVT = Subtarget.getXLenVT(); 5537 unsigned OrigIdx = Op.getConstantOperandVal(1); 5538 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5539 5540 // We don't have the ability to slide mask vectors down indexed by their i1 5541 // elements; the smallest we can do is i8. Often we are able to bitcast to 5542 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5543 // from a scalable one, we might not necessarily have enough scalable 5544 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5545 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5546 if (VecVT.getVectorMinNumElements() >= 8 && 5547 SubVecVT.getVectorMinNumElements() >= 8) { 5548 assert(OrigIdx % 8 == 0 && "Invalid index"); 5549 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5550 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5551 "Unexpected mask vector lowering"); 5552 OrigIdx /= 8; 5553 SubVecVT = 5554 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5555 SubVecVT.isScalableVector()); 5556 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5557 VecVT.isScalableVector()); 5558 Vec = DAG.getBitcast(VecVT, Vec); 5559 } else { 5560 // We can't slide this mask vector down, indexed by its i1 elements. 5561 // This poses a problem when we wish to extract a scalable vector which 5562 // can't be re-expressed as a larger type. Just choose the slow path and 5563 // extend to a larger type, then truncate back down. 5564 // TODO: We could probably improve this when extracting certain fixed 5565 // from fixed, where we can extract as i8 and shift the correct element 5566 // right to reach the desired subvector? 5567 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5568 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5569 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5570 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5571 Op.getOperand(1)); 5572 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5573 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5574 } 5575 } 5576 5577 // If the subvector vector is a fixed-length type, we cannot use subregister 5578 // manipulation to simplify the codegen; we don't know which register of a 5579 // LMUL group contains the specific subvector as we only know the minimum 5580 // register size. Therefore we must slide the vector group down the full 5581 // amount. 5582 if (SubVecVT.isFixedLengthVector()) { 5583 // With an index of 0 this is a cast-like subvector, which can be performed 5584 // with subregister operations. 5585 if (OrigIdx == 0) 5586 return Op; 5587 MVT ContainerVT = VecVT; 5588 if (VecVT.isFixedLengthVector()) { 5589 ContainerVT = getContainerForFixedLengthVector(VecVT); 5590 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5591 } 5592 SDValue Mask = 5593 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5594 // Set the vector length to only the number of elements we care about. This 5595 // avoids sliding down elements we're going to discard straight away. 5596 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5597 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5598 SDValue Slidedown = 5599 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5600 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5601 // Now we can use a cast-like subvector extract to get the result. 5602 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5603 DAG.getConstant(0, DL, XLenVT)); 5604 return DAG.getBitcast(Op.getValueType(), Slidedown); 5605 } 5606 5607 unsigned SubRegIdx, RemIdx; 5608 std::tie(SubRegIdx, RemIdx) = 5609 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5610 VecVT, SubVecVT, OrigIdx, TRI); 5611 5612 // If the Idx has been completely eliminated then this is a subvector extract 5613 // which naturally aligns to a vector register. These can easily be handled 5614 // using subregister manipulation. 5615 if (RemIdx == 0) 5616 return Op; 5617 5618 // Else we must shift our vector register directly to extract the subvector. 5619 // Do this using VSLIDEDOWN. 5620 5621 // If the vector type is an LMUL-group type, extract a subvector equal to the 5622 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5623 // instruction. 5624 MVT InterSubVT = VecVT; 5625 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5626 InterSubVT = getLMUL1VT(VecVT); 5627 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5628 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5629 } 5630 5631 // Slide this vector register down by the desired number of elements in order 5632 // to place the desired subvector starting at element 0. 5633 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5634 // For scalable vectors this must be further multiplied by vscale. 5635 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5636 5637 SDValue Mask, VL; 5638 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5639 SDValue Slidedown = 5640 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5641 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5642 5643 // Now the vector is in the right position, extract our final subvector. This 5644 // should resolve to a COPY. 5645 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5646 DAG.getConstant(0, DL, XLenVT)); 5647 5648 // We might have bitcast from a mask type: cast back to the original type if 5649 // required. 5650 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5651 } 5652 5653 // Lower step_vector to the vid instruction. Any non-identity step value must 5654 // be accounted for my manual expansion. 5655 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5656 SelectionDAG &DAG) const { 5657 SDLoc DL(Op); 5658 MVT VT = Op.getSimpleValueType(); 5659 MVT XLenVT = Subtarget.getXLenVT(); 5660 SDValue Mask, VL; 5661 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5662 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5663 uint64_t StepValImm = Op.getConstantOperandVal(0); 5664 if (StepValImm != 1) { 5665 if (isPowerOf2_64(StepValImm)) { 5666 SDValue StepVal = 5667 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5668 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5669 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5670 } else { 5671 SDValue StepVal = lowerScalarSplat( 5672 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5673 VL, VT, DL, DAG, Subtarget); 5674 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5675 } 5676 } 5677 return StepVec; 5678 } 5679 5680 // Implement vector_reverse using vrgather.vv with indices determined by 5681 // subtracting the id of each element from (VLMAX-1). This will convert 5682 // the indices like so: 5683 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5684 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5685 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5686 SelectionDAG &DAG) const { 5687 SDLoc DL(Op); 5688 MVT VecVT = Op.getSimpleValueType(); 5689 if (VecVT.getVectorElementType() == MVT::i1) { 5690 MVT WidenVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 5691 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenVT, Op.getOperand(0)); 5692 SDValue Op2 = DAG.getNode(ISD::VECTOR_REVERSE, DL, WidenVT, Op1); 5693 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Op2); 5694 } 5695 unsigned EltSize = VecVT.getScalarSizeInBits(); 5696 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5697 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 5698 unsigned MaxVLMAX = 5699 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 5700 5701 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5702 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5703 5704 // If this is SEW=8 and VLMAX is potentially more than 256, we need 5705 // to use vrgatherei16.vv. 5706 // TODO: It's also possible to use vrgatherei16.vv for other types to 5707 // decrease register width for the index calculation. 5708 if (MaxVLMAX > 256 && EltSize == 8) { 5709 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5710 // Reverse each half, then reassemble them in reverse order. 5711 // NOTE: It's also possible that after splitting that VLMAX no longer 5712 // requires vrgatherei16.vv. 5713 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5714 SDValue Lo, Hi; 5715 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5716 EVT LoVT, HiVT; 5717 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5718 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5719 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5720 // Reassemble the low and high pieces reversed. 5721 // FIXME: This is a CONCAT_VECTORS. 5722 SDValue Res = 5723 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5724 DAG.getIntPtrConstant(0, DL)); 5725 return DAG.getNode( 5726 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5727 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5728 } 5729 5730 // Just promote the int type to i16 which will double the LMUL. 5731 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5732 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5733 } 5734 5735 MVT XLenVT = Subtarget.getXLenVT(); 5736 SDValue Mask, VL; 5737 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5738 5739 // Calculate VLMAX-1 for the desired SEW. 5740 unsigned MinElts = VecVT.getVectorMinNumElements(); 5741 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5742 DAG.getConstant(MinElts, DL, XLenVT)); 5743 SDValue VLMinus1 = 5744 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5745 5746 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5747 bool IsRV32E64 = 5748 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5749 SDValue SplatVL; 5750 if (!IsRV32E64) 5751 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5752 else 5753 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5754 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5755 5756 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5757 SDValue Indices = 5758 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5759 5760 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, 5761 DAG.getUNDEF(VecVT), VL); 5762 } 5763 5764 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5765 SelectionDAG &DAG) const { 5766 SDLoc DL(Op); 5767 SDValue V1 = Op.getOperand(0); 5768 SDValue V2 = Op.getOperand(1); 5769 MVT XLenVT = Subtarget.getXLenVT(); 5770 MVT VecVT = Op.getSimpleValueType(); 5771 5772 unsigned MinElts = VecVT.getVectorMinNumElements(); 5773 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5774 DAG.getConstant(MinElts, DL, XLenVT)); 5775 5776 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5777 SDValue DownOffset, UpOffset; 5778 if (ImmValue >= 0) { 5779 // The operand is a TargetConstant, we need to rebuild it as a regular 5780 // constant. 5781 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5782 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5783 } else { 5784 // The operand is a TargetConstant, we need to rebuild it as a regular 5785 // constant rather than negating the original operand. 5786 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5787 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5788 } 5789 5790 SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG); 5791 5792 SDValue SlideDown = 5793 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5794 DownOffset, TrueMask, UpOffset); 5795 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5796 TrueMask, DAG.getRegister(RISCV::X0, XLenVT)); 5797 } 5798 5799 SDValue 5800 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5801 SelectionDAG &DAG) const { 5802 SDLoc DL(Op); 5803 auto *Load = cast<LoadSDNode>(Op); 5804 5805 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5806 Load->getMemoryVT(), 5807 *Load->getMemOperand()) && 5808 "Expecting a correctly-aligned load"); 5809 5810 MVT VT = Op.getSimpleValueType(); 5811 MVT XLenVT = Subtarget.getXLenVT(); 5812 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5813 5814 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5815 5816 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5817 SDValue IntID = DAG.getTargetConstant( 5818 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 5819 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 5820 if (!IsMaskOp) 5821 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5822 Ops.push_back(Load->getBasePtr()); 5823 Ops.push_back(VL); 5824 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5825 SDValue NewLoad = 5826 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5827 Load->getMemoryVT(), Load->getMemOperand()); 5828 5829 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5830 return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL); 5831 } 5832 5833 SDValue 5834 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5835 SelectionDAG &DAG) const { 5836 SDLoc DL(Op); 5837 auto *Store = cast<StoreSDNode>(Op); 5838 5839 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5840 Store->getMemoryVT(), 5841 *Store->getMemOperand()) && 5842 "Expecting a correctly-aligned store"); 5843 5844 SDValue StoreVal = Store->getValue(); 5845 MVT VT = StoreVal.getSimpleValueType(); 5846 MVT XLenVT = Subtarget.getXLenVT(); 5847 5848 // If the size less than a byte, we need to pad with zeros to make a byte. 5849 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5850 VT = MVT::v8i1; 5851 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5852 DAG.getConstant(0, DL, VT), StoreVal, 5853 DAG.getIntPtrConstant(0, DL)); 5854 } 5855 5856 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5857 5858 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5859 5860 SDValue NewValue = 5861 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5862 5863 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5864 SDValue IntID = DAG.getTargetConstant( 5865 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 5866 return DAG.getMemIntrinsicNode( 5867 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 5868 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 5869 Store->getMemoryVT(), Store->getMemOperand()); 5870 } 5871 5872 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5873 SelectionDAG &DAG) const { 5874 SDLoc DL(Op); 5875 MVT VT = Op.getSimpleValueType(); 5876 5877 const auto *MemSD = cast<MemSDNode>(Op); 5878 EVT MemVT = MemSD->getMemoryVT(); 5879 MachineMemOperand *MMO = MemSD->getMemOperand(); 5880 SDValue Chain = MemSD->getChain(); 5881 SDValue BasePtr = MemSD->getBasePtr(); 5882 5883 SDValue Mask, PassThru, VL; 5884 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5885 Mask = VPLoad->getMask(); 5886 PassThru = DAG.getUNDEF(VT); 5887 VL = VPLoad->getVectorLength(); 5888 } else { 5889 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5890 Mask = MLoad->getMask(); 5891 PassThru = MLoad->getPassThru(); 5892 } 5893 5894 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5895 5896 MVT XLenVT = Subtarget.getXLenVT(); 5897 5898 MVT ContainerVT = VT; 5899 if (VT.isFixedLengthVector()) { 5900 ContainerVT = getContainerForFixedLengthVector(VT); 5901 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5902 if (!IsUnmasked) { 5903 MVT MaskVT = getMaskTypeFor(ContainerVT); 5904 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5905 } 5906 } 5907 5908 if (!VL) 5909 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5910 5911 unsigned IntID = 5912 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5913 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5914 if (IsUnmasked) 5915 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5916 else 5917 Ops.push_back(PassThru); 5918 Ops.push_back(BasePtr); 5919 if (!IsUnmasked) 5920 Ops.push_back(Mask); 5921 Ops.push_back(VL); 5922 if (!IsUnmasked) 5923 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5924 5925 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5926 5927 SDValue Result = 5928 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5929 Chain = Result.getValue(1); 5930 5931 if (VT.isFixedLengthVector()) 5932 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5933 5934 return DAG.getMergeValues({Result, Chain}, DL); 5935 } 5936 5937 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5938 SelectionDAG &DAG) const { 5939 SDLoc DL(Op); 5940 5941 const auto *MemSD = cast<MemSDNode>(Op); 5942 EVT MemVT = MemSD->getMemoryVT(); 5943 MachineMemOperand *MMO = MemSD->getMemOperand(); 5944 SDValue Chain = MemSD->getChain(); 5945 SDValue BasePtr = MemSD->getBasePtr(); 5946 SDValue Val, Mask, VL; 5947 5948 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5949 Val = VPStore->getValue(); 5950 Mask = VPStore->getMask(); 5951 VL = VPStore->getVectorLength(); 5952 } else { 5953 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5954 Val = MStore->getValue(); 5955 Mask = MStore->getMask(); 5956 } 5957 5958 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5959 5960 MVT VT = Val.getSimpleValueType(); 5961 MVT XLenVT = Subtarget.getXLenVT(); 5962 5963 MVT ContainerVT = VT; 5964 if (VT.isFixedLengthVector()) { 5965 ContainerVT = getContainerForFixedLengthVector(VT); 5966 5967 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5968 if (!IsUnmasked) { 5969 MVT MaskVT = getMaskTypeFor(ContainerVT); 5970 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5971 } 5972 } 5973 5974 if (!VL) 5975 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5976 5977 unsigned IntID = 5978 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5979 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5980 Ops.push_back(Val); 5981 Ops.push_back(BasePtr); 5982 if (!IsUnmasked) 5983 Ops.push_back(Mask); 5984 Ops.push_back(VL); 5985 5986 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5987 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5988 } 5989 5990 SDValue 5991 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5992 SelectionDAG &DAG) const { 5993 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5994 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5995 5996 MVT VT = Op.getSimpleValueType(); 5997 5998 SDValue Op1 = 5999 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 6000 SDValue Op2 = 6001 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 6002 6003 SDLoc DL(Op); 6004 SDValue VL = 6005 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 6006 6007 MVT MaskVT = getMaskTypeFor(ContainerVT); 6008 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 6009 6010 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 6011 Op.getOperand(2), Mask, VL); 6012 6013 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 6014 } 6015 6016 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 6017 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 6018 MVT VT = Op.getSimpleValueType(); 6019 6020 if (VT.getVectorElementType() == MVT::i1) 6021 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 6022 6023 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 6024 } 6025 6026 SDValue 6027 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 6028 SelectionDAG &DAG) const { 6029 unsigned Opc; 6030 switch (Op.getOpcode()) { 6031 default: llvm_unreachable("Unexpected opcode!"); 6032 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 6033 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 6034 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 6035 } 6036 6037 return lowerToScalableOp(Op, DAG, Opc); 6038 } 6039 6040 // Lower vector ABS to smax(X, sub(0, X)). 6041 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 6042 SDLoc DL(Op); 6043 MVT VT = Op.getSimpleValueType(); 6044 SDValue X = Op.getOperand(0); 6045 6046 assert(VT.isFixedLengthVector() && "Unexpected type"); 6047 6048 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6049 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 6050 6051 SDValue Mask, VL; 6052 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6053 6054 SDValue SplatZero = DAG.getNode( 6055 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 6056 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 6057 SDValue NegX = 6058 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 6059 SDValue Max = 6060 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 6061 6062 return convertFromScalableVector(VT, Max, DAG, Subtarget); 6063 } 6064 6065 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 6066 SDValue Op, SelectionDAG &DAG) const { 6067 SDLoc DL(Op); 6068 MVT VT = Op.getSimpleValueType(); 6069 SDValue Mag = Op.getOperand(0); 6070 SDValue Sign = Op.getOperand(1); 6071 assert(Mag.getValueType() == Sign.getValueType() && 6072 "Can only handle COPYSIGN with matching types."); 6073 6074 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6075 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 6076 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 6077 6078 SDValue Mask, VL; 6079 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6080 6081 SDValue CopySign = 6082 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 6083 6084 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 6085 } 6086 6087 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 6088 SDValue Op, SelectionDAG &DAG) const { 6089 MVT VT = Op.getSimpleValueType(); 6090 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6091 6092 MVT I1ContainerVT = 6093 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6094 6095 SDValue CC = 6096 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 6097 SDValue Op1 = 6098 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 6099 SDValue Op2 = 6100 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 6101 6102 SDLoc DL(Op); 6103 SDValue Mask, VL; 6104 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6105 6106 SDValue Select = 6107 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 6108 6109 return convertFromScalableVector(VT, Select, DAG, Subtarget); 6110 } 6111 6112 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 6113 unsigned NewOpc, 6114 bool HasMask) const { 6115 MVT VT = Op.getSimpleValueType(); 6116 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6117 6118 // Create list of operands by converting existing ones to scalable types. 6119 SmallVector<SDValue, 6> Ops; 6120 for (const SDValue &V : Op->op_values()) { 6121 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6122 6123 // Pass through non-vector operands. 6124 if (!V.getValueType().isVector()) { 6125 Ops.push_back(V); 6126 continue; 6127 } 6128 6129 // "cast" fixed length vector to a scalable vector. 6130 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6131 "Only fixed length vectors are supported!"); 6132 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6133 } 6134 6135 SDLoc DL(Op); 6136 SDValue Mask, VL; 6137 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6138 if (HasMask) 6139 Ops.push_back(Mask); 6140 Ops.push_back(VL); 6141 6142 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6143 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6144 } 6145 6146 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6147 // * Operands of each node are assumed to be in the same order. 6148 // * The EVL operand is promoted from i32 to i64 on RV64. 6149 // * Fixed-length vectors are converted to their scalable-vector container 6150 // types. 6151 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6152 unsigned RISCVISDOpc) const { 6153 SDLoc DL(Op); 6154 MVT VT = Op.getSimpleValueType(); 6155 SmallVector<SDValue, 4> Ops; 6156 6157 for (const auto &OpIdx : enumerate(Op->ops())) { 6158 SDValue V = OpIdx.value(); 6159 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6160 // Pass through operands which aren't fixed-length vectors. 6161 if (!V.getValueType().isFixedLengthVector()) { 6162 Ops.push_back(V); 6163 continue; 6164 } 6165 // "cast" fixed length vector to a scalable vector. 6166 MVT OpVT = V.getSimpleValueType(); 6167 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6168 assert(useRVVForFixedLengthVectorVT(OpVT) && 6169 "Only fixed length vectors are supported!"); 6170 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6171 } 6172 6173 if (!VT.isFixedLengthVector()) 6174 return DAG.getNode(RISCVISDOpc, DL, VT, Ops, Op->getFlags()); 6175 6176 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6177 6178 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops, Op->getFlags()); 6179 6180 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6181 } 6182 6183 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op, 6184 SelectionDAG &DAG) const { 6185 SDLoc DL(Op); 6186 MVT VT = Op.getSimpleValueType(); 6187 6188 SDValue Src = Op.getOperand(0); 6189 // NOTE: Mask is dropped. 6190 SDValue VL = Op.getOperand(2); 6191 6192 MVT ContainerVT = VT; 6193 if (VT.isFixedLengthVector()) { 6194 ContainerVT = getContainerForFixedLengthVector(VT); 6195 MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6196 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6197 } 6198 6199 MVT XLenVT = Subtarget.getXLenVT(); 6200 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6201 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6202 DAG.getUNDEF(ContainerVT), Zero, VL); 6203 6204 SDValue SplatValue = DAG.getConstant( 6205 Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT); 6206 SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6207 DAG.getUNDEF(ContainerVT), SplatValue, VL); 6208 6209 SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src, 6210 Splat, ZeroSplat, VL); 6211 if (!VT.isFixedLengthVector()) 6212 return Result; 6213 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6214 } 6215 6216 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op, 6217 SelectionDAG &DAG) const { 6218 SDLoc DL(Op); 6219 MVT VT = Op.getSimpleValueType(); 6220 6221 SDValue Op1 = Op.getOperand(0); 6222 SDValue Op2 = Op.getOperand(1); 6223 ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 6224 // NOTE: Mask is dropped. 6225 SDValue VL = Op.getOperand(4); 6226 6227 MVT ContainerVT = VT; 6228 if (VT.isFixedLengthVector()) { 6229 ContainerVT = getContainerForFixedLengthVector(VT); 6230 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6231 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6232 } 6233 6234 SDValue Result; 6235 SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 6236 6237 switch (Condition) { 6238 default: 6239 break; 6240 // X != Y --> (X^Y) 6241 case ISD::SETNE: 6242 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6243 break; 6244 // X == Y --> ~(X^Y) 6245 case ISD::SETEQ: { 6246 SDValue Temp = 6247 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6248 Result = 6249 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL); 6250 break; 6251 } 6252 // X >s Y --> X == 0 & Y == 1 --> ~X & Y 6253 // X <u Y --> X == 0 & Y == 1 --> ~X & Y 6254 case ISD::SETGT: 6255 case ISD::SETULT: { 6256 SDValue Temp = 6257 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6258 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL); 6259 break; 6260 } 6261 // X <s Y --> X == 1 & Y == 0 --> ~Y & X 6262 // X >u Y --> X == 1 & Y == 0 --> ~Y & X 6263 case ISD::SETLT: 6264 case ISD::SETUGT: { 6265 SDValue Temp = 6266 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6267 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL); 6268 break; 6269 } 6270 // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 6271 // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 6272 case ISD::SETGE: 6273 case ISD::SETULE: { 6274 SDValue Temp = 6275 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6276 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL); 6277 break; 6278 } 6279 // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 6280 // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 6281 case ISD::SETLE: 6282 case ISD::SETUGE: { 6283 SDValue Temp = 6284 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6285 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL); 6286 break; 6287 } 6288 } 6289 6290 if (!VT.isFixedLengthVector()) 6291 return Result; 6292 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6293 } 6294 6295 // Lower Floating-Point/Integer Type-Convert VP SDNodes 6296 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG, 6297 unsigned RISCVISDOpc) const { 6298 SDLoc DL(Op); 6299 6300 SDValue Src = Op.getOperand(0); 6301 SDValue Mask = Op.getOperand(1); 6302 SDValue VL = Op.getOperand(2); 6303 6304 MVT DstVT = Op.getSimpleValueType(); 6305 MVT SrcVT = Src.getSimpleValueType(); 6306 if (DstVT.isFixedLengthVector()) { 6307 DstVT = getContainerForFixedLengthVector(DstVT); 6308 SrcVT = getContainerForFixedLengthVector(SrcVT); 6309 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6310 MVT MaskVT = getMaskTypeFor(DstVT); 6311 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6312 } 6313 6314 unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL || 6315 RISCVISDOpc == RISCVISD::FP_TO_SINT_VL) 6316 ? RISCVISD::VSEXT_VL 6317 : RISCVISD::VZEXT_VL; 6318 6319 unsigned DstEltSize = DstVT.getScalarSizeInBits(); 6320 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 6321 6322 SDValue Result; 6323 if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion. 6324 if (SrcVT.isInteger()) { 6325 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6326 6327 // Do we need to do any pre-widening before converting? 6328 if (SrcEltSize == 1) { 6329 MVT IntVT = DstVT.changeVectorElementTypeToInteger(); 6330 MVT XLenVT = Subtarget.getXLenVT(); 6331 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6332 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6333 DAG.getUNDEF(IntVT), Zero, VL); 6334 SDValue One = DAG.getConstant( 6335 RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT); 6336 SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6337 DAG.getUNDEF(IntVT), One, VL); 6338 Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat, 6339 ZeroSplat, VL); 6340 } else if (DstEltSize > (2 * SrcEltSize)) { 6341 // Widen before converting. 6342 MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2), 6343 DstVT.getVectorElementCount()); 6344 Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL); 6345 } 6346 6347 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6348 } else { 6349 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6350 "Wrong input/output vector types"); 6351 6352 // Convert f16 to f32 then convert f32 to i64. 6353 if (DstEltSize > (2 * SrcEltSize)) { 6354 assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6355 MVT InterimFVT = 6356 MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6357 Src = 6358 DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL); 6359 } 6360 6361 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6362 } 6363 } else { // Narrowing + Conversion 6364 if (SrcVT.isInteger()) { 6365 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6366 // First do a narrowing convert to an FP type half the size, then round 6367 // the FP type to a small FP type if needed. 6368 6369 MVT InterimFVT = DstVT; 6370 if (SrcEltSize > (2 * DstEltSize)) { 6371 assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!"); 6372 assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6373 InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6374 } 6375 6376 Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL); 6377 6378 if (InterimFVT != DstVT) { 6379 Src = Result; 6380 Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL); 6381 } 6382 } else { 6383 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6384 "Wrong input/output vector types"); 6385 // First do a narrowing conversion to an integer half the size, then 6386 // truncate if needed. 6387 6388 if (DstEltSize == 1) { 6389 // First convert to the same size integer, then convert to mask using 6390 // setcc. 6391 assert(SrcEltSize >= 16 && "Unexpected FP type!"); 6392 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize), 6393 DstVT.getVectorElementCount()); 6394 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6395 6396 // Compare the integer result to 0. The integer should be 0 or 1/-1, 6397 // otherwise the conversion was undefined. 6398 MVT XLenVT = Subtarget.getXLenVT(); 6399 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 6400 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT, 6401 DAG.getUNDEF(InterimIVT), SplatZero); 6402 Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero, 6403 DAG.getCondCode(ISD::SETNE), Mask, VL); 6404 } else { 6405 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6406 DstVT.getVectorElementCount()); 6407 6408 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6409 6410 while (InterimIVT != DstVT) { 6411 SrcEltSize /= 2; 6412 Src = Result; 6413 InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6414 DstVT.getVectorElementCount()); 6415 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT, 6416 Src, Mask, VL); 6417 } 6418 } 6419 } 6420 } 6421 6422 MVT VT = Op.getSimpleValueType(); 6423 if (!VT.isFixedLengthVector()) 6424 return Result; 6425 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6426 } 6427 6428 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6429 unsigned MaskOpc, 6430 unsigned VecOpc) const { 6431 MVT VT = Op.getSimpleValueType(); 6432 if (VT.getVectorElementType() != MVT::i1) 6433 return lowerVPOp(Op, DAG, VecOpc); 6434 6435 // It is safe to drop mask parameter as masked-off elements are undef. 6436 SDValue Op1 = Op->getOperand(0); 6437 SDValue Op2 = Op->getOperand(1); 6438 SDValue VL = Op->getOperand(3); 6439 6440 MVT ContainerVT = VT; 6441 const bool IsFixed = VT.isFixedLengthVector(); 6442 if (IsFixed) { 6443 ContainerVT = getContainerForFixedLengthVector(VT); 6444 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6445 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6446 } 6447 6448 SDLoc DL(Op); 6449 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6450 if (!IsFixed) 6451 return Val; 6452 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6453 } 6454 6455 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6456 // matched to a RVV indexed load. The RVV indexed load instructions only 6457 // support the "unsigned unscaled" addressing mode; indices are implicitly 6458 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6459 // signed or scaled indexing is extended to the XLEN value type and scaled 6460 // accordingly. 6461 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6462 SelectionDAG &DAG) const { 6463 SDLoc DL(Op); 6464 MVT VT = Op.getSimpleValueType(); 6465 6466 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6467 EVT MemVT = MemSD->getMemoryVT(); 6468 MachineMemOperand *MMO = MemSD->getMemOperand(); 6469 SDValue Chain = MemSD->getChain(); 6470 SDValue BasePtr = MemSD->getBasePtr(); 6471 6472 ISD::LoadExtType LoadExtType; 6473 SDValue Index, Mask, PassThru, VL; 6474 6475 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6476 Index = VPGN->getIndex(); 6477 Mask = VPGN->getMask(); 6478 PassThru = DAG.getUNDEF(VT); 6479 VL = VPGN->getVectorLength(); 6480 // VP doesn't support extending loads. 6481 LoadExtType = ISD::NON_EXTLOAD; 6482 } else { 6483 // Else it must be a MGATHER. 6484 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6485 Index = MGN->getIndex(); 6486 Mask = MGN->getMask(); 6487 PassThru = MGN->getPassThru(); 6488 LoadExtType = MGN->getExtensionType(); 6489 } 6490 6491 MVT IndexVT = Index.getSimpleValueType(); 6492 MVT XLenVT = Subtarget.getXLenVT(); 6493 6494 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6495 "Unexpected VTs!"); 6496 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6497 // Targets have to explicitly opt-in for extending vector loads. 6498 assert(LoadExtType == ISD::NON_EXTLOAD && 6499 "Unexpected extending MGATHER/VP_GATHER"); 6500 (void)LoadExtType; 6501 6502 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6503 // the selection of the masked intrinsics doesn't do this for us. 6504 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6505 6506 MVT ContainerVT = VT; 6507 if (VT.isFixedLengthVector()) { 6508 ContainerVT = getContainerForFixedLengthVector(VT); 6509 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6510 ContainerVT.getVectorElementCount()); 6511 6512 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6513 6514 if (!IsUnmasked) { 6515 MVT MaskVT = getMaskTypeFor(ContainerVT); 6516 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6517 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6518 } 6519 } 6520 6521 if (!VL) 6522 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6523 6524 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6525 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6526 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6527 VL); 6528 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6529 TrueMask, VL); 6530 } 6531 6532 unsigned IntID = 6533 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6534 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6535 if (IsUnmasked) 6536 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6537 else 6538 Ops.push_back(PassThru); 6539 Ops.push_back(BasePtr); 6540 Ops.push_back(Index); 6541 if (!IsUnmasked) 6542 Ops.push_back(Mask); 6543 Ops.push_back(VL); 6544 if (!IsUnmasked) 6545 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6546 6547 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6548 SDValue Result = 6549 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6550 Chain = Result.getValue(1); 6551 6552 if (VT.isFixedLengthVector()) 6553 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6554 6555 return DAG.getMergeValues({Result, Chain}, DL); 6556 } 6557 6558 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6559 // matched to a RVV indexed store. The RVV indexed store instructions only 6560 // support the "unsigned unscaled" addressing mode; indices are implicitly 6561 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6562 // signed or scaled indexing is extended to the XLEN value type and scaled 6563 // accordingly. 6564 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6565 SelectionDAG &DAG) const { 6566 SDLoc DL(Op); 6567 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6568 EVT MemVT = MemSD->getMemoryVT(); 6569 MachineMemOperand *MMO = MemSD->getMemOperand(); 6570 SDValue Chain = MemSD->getChain(); 6571 SDValue BasePtr = MemSD->getBasePtr(); 6572 6573 bool IsTruncatingStore = false; 6574 SDValue Index, Mask, Val, VL; 6575 6576 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6577 Index = VPSN->getIndex(); 6578 Mask = VPSN->getMask(); 6579 Val = VPSN->getValue(); 6580 VL = VPSN->getVectorLength(); 6581 // VP doesn't support truncating stores. 6582 IsTruncatingStore = false; 6583 } else { 6584 // Else it must be a MSCATTER. 6585 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6586 Index = MSN->getIndex(); 6587 Mask = MSN->getMask(); 6588 Val = MSN->getValue(); 6589 IsTruncatingStore = MSN->isTruncatingStore(); 6590 } 6591 6592 MVT VT = Val.getSimpleValueType(); 6593 MVT IndexVT = Index.getSimpleValueType(); 6594 MVT XLenVT = Subtarget.getXLenVT(); 6595 6596 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6597 "Unexpected VTs!"); 6598 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6599 // Targets have to explicitly opt-in for extending vector loads and 6600 // truncating vector stores. 6601 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6602 (void)IsTruncatingStore; 6603 6604 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6605 // the selection of the masked intrinsics doesn't do this for us. 6606 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6607 6608 MVT ContainerVT = VT; 6609 if (VT.isFixedLengthVector()) { 6610 ContainerVT = getContainerForFixedLengthVector(VT); 6611 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6612 ContainerVT.getVectorElementCount()); 6613 6614 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6615 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6616 6617 if (!IsUnmasked) { 6618 MVT MaskVT = getMaskTypeFor(ContainerVT); 6619 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6620 } 6621 } 6622 6623 if (!VL) 6624 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6625 6626 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6627 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6628 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6629 VL); 6630 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6631 TrueMask, VL); 6632 } 6633 6634 unsigned IntID = 6635 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6636 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6637 Ops.push_back(Val); 6638 Ops.push_back(BasePtr); 6639 Ops.push_back(Index); 6640 if (!IsUnmasked) 6641 Ops.push_back(Mask); 6642 Ops.push_back(VL); 6643 6644 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6645 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6646 } 6647 6648 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6649 SelectionDAG &DAG) const { 6650 const MVT XLenVT = Subtarget.getXLenVT(); 6651 SDLoc DL(Op); 6652 SDValue Chain = Op->getOperand(0); 6653 SDValue SysRegNo = DAG.getTargetConstant( 6654 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6655 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6656 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6657 6658 // Encoding used for rounding mode in RISCV differs from that used in 6659 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6660 // table, which consists of a sequence of 4-bit fields, each representing 6661 // corresponding FLT_ROUNDS mode. 6662 static const int Table = 6663 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6664 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6665 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6666 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6667 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6668 6669 SDValue Shift = 6670 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6671 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6672 DAG.getConstant(Table, DL, XLenVT), Shift); 6673 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6674 DAG.getConstant(7, DL, XLenVT)); 6675 6676 return DAG.getMergeValues({Masked, Chain}, DL); 6677 } 6678 6679 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6680 SelectionDAG &DAG) const { 6681 const MVT XLenVT = Subtarget.getXLenVT(); 6682 SDLoc DL(Op); 6683 SDValue Chain = Op->getOperand(0); 6684 SDValue RMValue = Op->getOperand(1); 6685 SDValue SysRegNo = DAG.getTargetConstant( 6686 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6687 6688 // Encoding used for rounding mode in RISCV differs from that used in 6689 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6690 // a table, which consists of a sequence of 4-bit fields, each representing 6691 // corresponding RISCV mode. 6692 static const unsigned Table = 6693 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6694 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6695 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6696 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6697 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6698 6699 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6700 DAG.getConstant(2, DL, XLenVT)); 6701 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6702 DAG.getConstant(Table, DL, XLenVT), Shift); 6703 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6704 DAG.getConstant(0x7, DL, XLenVT)); 6705 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6706 RMValue); 6707 } 6708 6709 SDValue RISCVTargetLowering::lowerEH_DWARF_CFA(SDValue Op, 6710 SelectionDAG &DAG) const { 6711 MachineFunction &MF = DAG.getMachineFunction(); 6712 6713 bool isRISCV64 = Subtarget.is64Bit(); 6714 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6715 6716 int FI = MF.getFrameInfo().CreateFixedObject(isRISCV64 ? 8 : 4, 0, false); 6717 return DAG.getFrameIndex(FI, PtrVT); 6718 } 6719 6720 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6721 switch (IntNo) { 6722 default: 6723 llvm_unreachable("Unexpected Intrinsic"); 6724 case Intrinsic::riscv_bcompress: 6725 return RISCVISD::BCOMPRESSW; 6726 case Intrinsic::riscv_bdecompress: 6727 return RISCVISD::BDECOMPRESSW; 6728 case Intrinsic::riscv_bfp: 6729 return RISCVISD::BFPW; 6730 case Intrinsic::riscv_fsl: 6731 return RISCVISD::FSLW; 6732 case Intrinsic::riscv_fsr: 6733 return RISCVISD::FSRW; 6734 } 6735 } 6736 6737 // Converts the given intrinsic to a i64 operation with any extension. 6738 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6739 unsigned IntNo) { 6740 SDLoc DL(N); 6741 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6742 // Deal with the Instruction Operands 6743 SmallVector<SDValue, 3> NewOps; 6744 for (SDValue Op : drop_begin(N->ops())) 6745 // Promote the operand to i64 type 6746 NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op)); 6747 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps); 6748 // ReplaceNodeResults requires we maintain the same type for the return value. 6749 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6750 } 6751 6752 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6753 // form of the given Opcode. 6754 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6755 switch (Opcode) { 6756 default: 6757 llvm_unreachable("Unexpected opcode"); 6758 case ISD::SHL: 6759 return RISCVISD::SLLW; 6760 case ISD::SRA: 6761 return RISCVISD::SRAW; 6762 case ISD::SRL: 6763 return RISCVISD::SRLW; 6764 case ISD::SDIV: 6765 return RISCVISD::DIVW; 6766 case ISD::UDIV: 6767 return RISCVISD::DIVUW; 6768 case ISD::UREM: 6769 return RISCVISD::REMUW; 6770 case ISD::ROTL: 6771 return RISCVISD::ROLW; 6772 case ISD::ROTR: 6773 return RISCVISD::RORW; 6774 } 6775 } 6776 6777 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6778 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6779 // otherwise be promoted to i64, making it difficult to select the 6780 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6781 // type i8/i16/i32 is lost. 6782 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6783 unsigned ExtOpc = ISD::ANY_EXTEND) { 6784 SDLoc DL(N); 6785 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6786 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6787 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6788 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6789 // ReplaceNodeResults requires we maintain the same type for the return value. 6790 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6791 } 6792 6793 // Converts the given 32-bit operation to a i64 operation with signed extension 6794 // semantic to reduce the signed extension instructions. 6795 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6796 SDLoc DL(N); 6797 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6798 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6799 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6800 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6801 DAG.getValueType(MVT::i32)); 6802 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6803 } 6804 6805 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6806 SmallVectorImpl<SDValue> &Results, 6807 SelectionDAG &DAG) const { 6808 SDLoc DL(N); 6809 switch (N->getOpcode()) { 6810 default: 6811 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6812 case ISD::STRICT_FP_TO_SINT: 6813 case ISD::STRICT_FP_TO_UINT: 6814 case ISD::FP_TO_SINT: 6815 case ISD::FP_TO_UINT: { 6816 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6817 "Unexpected custom legalisation"); 6818 bool IsStrict = N->isStrictFPOpcode(); 6819 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6820 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6821 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6822 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6823 TargetLowering::TypeSoftenFloat) { 6824 if (!isTypeLegal(Op0.getValueType())) 6825 return; 6826 if (IsStrict) { 6827 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6828 : RISCVISD::STRICT_FCVT_WU_RV64; 6829 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6830 SDValue Res = DAG.getNode( 6831 Opc, DL, VTs, N->getOperand(0), Op0, 6832 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6833 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6834 Results.push_back(Res.getValue(1)); 6835 return; 6836 } 6837 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6838 SDValue Res = 6839 DAG.getNode(Opc, DL, MVT::i64, Op0, 6840 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6841 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6842 return; 6843 } 6844 // If the FP type needs to be softened, emit a library call using the 'si' 6845 // version. If we left it to default legalization we'd end up with 'di'. If 6846 // the FP type doesn't need to be softened just let generic type 6847 // legalization promote the result type. 6848 RTLIB::Libcall LC; 6849 if (IsSigned) 6850 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6851 else 6852 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6853 MakeLibCallOptions CallOptions; 6854 EVT OpVT = Op0.getValueType(); 6855 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6856 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6857 SDValue Result; 6858 std::tie(Result, Chain) = 6859 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6860 Results.push_back(Result); 6861 if (IsStrict) 6862 Results.push_back(Chain); 6863 break; 6864 } 6865 case ISD::READCYCLECOUNTER: { 6866 assert(!Subtarget.is64Bit() && 6867 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6868 6869 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6870 SDValue RCW = 6871 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6872 6873 Results.push_back( 6874 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6875 Results.push_back(RCW.getValue(2)); 6876 break; 6877 } 6878 case ISD::MUL: { 6879 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6880 unsigned XLen = Subtarget.getXLen(); 6881 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6882 if (Size > XLen) { 6883 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6884 SDValue LHS = N->getOperand(0); 6885 SDValue RHS = N->getOperand(1); 6886 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6887 6888 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6889 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6890 // We need exactly one side to be unsigned. 6891 if (LHSIsU == RHSIsU) 6892 return; 6893 6894 auto MakeMULPair = [&](SDValue S, SDValue U) { 6895 MVT XLenVT = Subtarget.getXLenVT(); 6896 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6897 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6898 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6899 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6900 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6901 }; 6902 6903 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6904 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6905 6906 // The other operand should be signed, but still prefer MULH when 6907 // possible. 6908 if (RHSIsU && LHSIsS && !RHSIsS) 6909 Results.push_back(MakeMULPair(LHS, RHS)); 6910 else if (LHSIsU && RHSIsS && !LHSIsS) 6911 Results.push_back(MakeMULPair(RHS, LHS)); 6912 6913 return; 6914 } 6915 LLVM_FALLTHROUGH; 6916 } 6917 case ISD::ADD: 6918 case ISD::SUB: 6919 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6920 "Unexpected custom legalisation"); 6921 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6922 break; 6923 case ISD::SHL: 6924 case ISD::SRA: 6925 case ISD::SRL: 6926 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6927 "Unexpected custom legalisation"); 6928 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6929 // If we can use a BSET instruction, allow default promotion to apply. 6930 if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() && 6931 isOneConstant(N->getOperand(0))) 6932 break; 6933 Results.push_back(customLegalizeToWOp(N, DAG)); 6934 break; 6935 } 6936 6937 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6938 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6939 // shift amount. 6940 if (N->getOpcode() == ISD::SHL) { 6941 SDLoc DL(N); 6942 SDValue NewOp0 = 6943 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6944 SDValue NewOp1 = 6945 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6946 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6947 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6948 DAG.getValueType(MVT::i32)); 6949 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6950 } 6951 6952 break; 6953 case ISD::ROTL: 6954 case ISD::ROTR: 6955 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6956 "Unexpected custom legalisation"); 6957 Results.push_back(customLegalizeToWOp(N, DAG)); 6958 break; 6959 case ISD::CTTZ: 6960 case ISD::CTTZ_ZERO_UNDEF: 6961 case ISD::CTLZ: 6962 case ISD::CTLZ_ZERO_UNDEF: { 6963 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6964 "Unexpected custom legalisation"); 6965 6966 SDValue NewOp0 = 6967 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6968 bool IsCTZ = 6969 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6970 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6971 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6972 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6973 return; 6974 } 6975 case ISD::SDIV: 6976 case ISD::UDIV: 6977 case ISD::UREM: { 6978 MVT VT = N->getSimpleValueType(0); 6979 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6980 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6981 "Unexpected custom legalisation"); 6982 // Don't promote division/remainder by constant since we should expand those 6983 // to multiply by magic constant. 6984 // FIXME: What if the expansion is disabled for minsize. 6985 if (N->getOperand(1).getOpcode() == ISD::Constant) 6986 return; 6987 6988 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6989 // the upper 32 bits. For other types we need to sign or zero extend 6990 // based on the opcode. 6991 unsigned ExtOpc = ISD::ANY_EXTEND; 6992 if (VT != MVT::i32) 6993 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6994 : ISD::ZERO_EXTEND; 6995 6996 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6997 break; 6998 } 6999 case ISD::UADDO: 7000 case ISD::USUBO: { 7001 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7002 "Unexpected custom legalisation"); 7003 bool IsAdd = N->getOpcode() == ISD::UADDO; 7004 // Create an ADDW or SUBW. 7005 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7006 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7007 SDValue Res = 7008 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 7009 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 7010 DAG.getValueType(MVT::i32)); 7011 7012 SDValue Overflow; 7013 if (IsAdd && isOneConstant(RHS)) { 7014 // Special case uaddo X, 1 overflowed if the addition result is 0. 7015 // The general case (X + C) < C is not necessarily beneficial. Although we 7016 // reduce the live range of X, we may introduce the materialization of 7017 // constant C, especially when the setcc result is used by branch. We have 7018 // no compare with constant and branch instructions. 7019 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, 7020 DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ); 7021 } else { 7022 // Sign extend the LHS and perform an unsigned compare with the ADDW 7023 // result. Since the inputs are sign extended from i32, this is equivalent 7024 // to comparing the lower 32 bits. 7025 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 7026 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 7027 IsAdd ? ISD::SETULT : ISD::SETUGT); 7028 } 7029 7030 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7031 Results.push_back(Overflow); 7032 return; 7033 } 7034 case ISD::UADDSAT: 7035 case ISD::USUBSAT: { 7036 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7037 "Unexpected custom legalisation"); 7038 if (Subtarget.hasStdExtZbb()) { 7039 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 7040 // sign extend allows overflow of the lower 32 bits to be detected on 7041 // the promoted size. 7042 SDValue LHS = 7043 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 7044 SDValue RHS = 7045 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 7046 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 7047 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7048 return; 7049 } 7050 7051 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 7052 // promotion for UADDO/USUBO. 7053 Results.push_back(expandAddSubSat(N, DAG)); 7054 return; 7055 } 7056 case ISD::ABS: { 7057 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7058 "Unexpected custom legalisation"); 7059 7060 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 7061 7062 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7063 7064 // Freeze the source so we can increase it's use count. 7065 Src = DAG.getFreeze(Src); 7066 7067 // Copy sign bit to all bits using the sraiw pattern. 7068 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 7069 DAG.getValueType(MVT::i32)); 7070 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 7071 DAG.getConstant(31, DL, MVT::i64)); 7072 7073 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 7074 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 7075 7076 // NOTE: The result is only required to be anyextended, but sext is 7077 // consistent with type legalization of sub. 7078 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 7079 DAG.getValueType(MVT::i32)); 7080 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 7081 return; 7082 } 7083 case ISD::BITCAST: { 7084 EVT VT = N->getValueType(0); 7085 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 7086 SDValue Op0 = N->getOperand(0); 7087 EVT Op0VT = Op0.getValueType(); 7088 MVT XLenVT = Subtarget.getXLenVT(); 7089 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 7090 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 7091 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 7092 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 7093 Subtarget.hasStdExtF()) { 7094 SDValue FPConv = 7095 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 7096 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 7097 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 7098 isTypeLegal(Op0VT)) { 7099 // Custom-legalize bitcasts from fixed-length vector types to illegal 7100 // scalar types in order to improve codegen. Bitcast the vector to a 7101 // one-element vector type whose element type is the same as the result 7102 // type, and extract the first element. 7103 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 7104 if (isTypeLegal(BVT)) { 7105 SDValue BVec = DAG.getBitcast(BVT, Op0); 7106 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 7107 DAG.getConstant(0, DL, XLenVT))); 7108 } 7109 } 7110 break; 7111 } 7112 case RISCVISD::GREV: 7113 case RISCVISD::GORC: 7114 case RISCVISD::SHFL: { 7115 MVT VT = N->getSimpleValueType(0); 7116 MVT XLenVT = Subtarget.getXLenVT(); 7117 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) && 7118 "Unexpected custom legalisation"); 7119 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 7120 assert((Subtarget.hasStdExtZbp() || 7121 (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV && 7122 N->getConstantOperandVal(1) == 7)) && 7123 "Unexpected extension"); 7124 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7125 SDValue NewOp1 = 7126 DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1)); 7127 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1); 7128 // ReplaceNodeResults requires we maintain the same type for the return 7129 // value. 7130 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes)); 7131 break; 7132 } 7133 case ISD::BSWAP: 7134 case ISD::BITREVERSE: { 7135 MVT VT = N->getSimpleValueType(0); 7136 MVT XLenVT = Subtarget.getXLenVT(); 7137 assert((VT == MVT::i8 || VT == MVT::i16 || 7138 (VT == MVT::i32 && Subtarget.is64Bit())) && 7139 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 7140 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7141 unsigned Imm = VT.getSizeInBits() - 1; 7142 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 7143 if (N->getOpcode() == ISD::BSWAP) 7144 Imm &= ~0x7U; 7145 SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0, 7146 DAG.getConstant(Imm, DL, XLenVT)); 7147 // ReplaceNodeResults requires we maintain the same type for the return 7148 // value. 7149 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 7150 break; 7151 } 7152 case ISD::FSHL: 7153 case ISD::FSHR: { 7154 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7155 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 7156 SDValue NewOp0 = 7157 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7158 SDValue NewOp1 = 7159 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7160 SDValue NewShAmt = 7161 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7162 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 7163 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 7164 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 7165 DAG.getConstant(0x1f, DL, MVT::i64)); 7166 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 7167 // instruction use different orders. fshl will return its first operand for 7168 // shift of zero, fshr will return its second operand. fsl and fsr both 7169 // return rs1 so the ISD nodes need to have different operand orders. 7170 // Shift amount is in rs2. 7171 unsigned Opc = RISCVISD::FSLW; 7172 if (N->getOpcode() == ISD::FSHR) { 7173 std::swap(NewOp0, NewOp1); 7174 Opc = RISCVISD::FSRW; 7175 } 7176 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 7177 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 7178 break; 7179 } 7180 case ISD::EXTRACT_VECTOR_ELT: { 7181 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 7182 // type is illegal (currently only vXi64 RV32). 7183 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 7184 // transferred to the destination register. We issue two of these from the 7185 // upper- and lower- halves of the SEW-bit vector element, slid down to the 7186 // first element. 7187 SDValue Vec = N->getOperand(0); 7188 SDValue Idx = N->getOperand(1); 7189 7190 // The vector type hasn't been legalized yet so we can't issue target 7191 // specific nodes if it needs legalization. 7192 // FIXME: We would manually legalize if it's important. 7193 if (!isTypeLegal(Vec.getValueType())) 7194 return; 7195 7196 MVT VecVT = Vec.getSimpleValueType(); 7197 7198 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 7199 VecVT.getVectorElementType() == MVT::i64 && 7200 "Unexpected EXTRACT_VECTOR_ELT legalization"); 7201 7202 // If this is a fixed vector, we need to convert it to a scalable vector. 7203 MVT ContainerVT = VecVT; 7204 if (VecVT.isFixedLengthVector()) { 7205 ContainerVT = getContainerForFixedLengthVector(VecVT); 7206 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 7207 } 7208 7209 MVT XLenVT = Subtarget.getXLenVT(); 7210 7211 // Use a VL of 1 to avoid processing more elements than we need. 7212 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7213 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 7214 7215 // Unless the index is known to be 0, we must slide the vector down to get 7216 // the desired element into index 0. 7217 if (!isNullConstant(Idx)) { 7218 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 7219 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 7220 } 7221 7222 // Extract the lower XLEN bits of the correct vector element. 7223 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7224 7225 // To extract the upper XLEN bits of the vector element, shift the first 7226 // element right by 32 bits and re-extract the lower XLEN bits. 7227 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 7228 DAG.getUNDEF(ContainerVT), 7229 DAG.getConstant(32, DL, XLenVT), VL); 7230 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 7231 ThirtyTwoV, Mask, VL); 7232 7233 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7234 7235 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7236 break; 7237 } 7238 case ISD::INTRINSIC_WO_CHAIN: { 7239 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7240 switch (IntNo) { 7241 default: 7242 llvm_unreachable( 7243 "Don't know how to custom type legalize this intrinsic!"); 7244 case Intrinsic::riscv_grev: 7245 case Intrinsic::riscv_gorc: { 7246 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7247 "Unexpected custom legalisation"); 7248 SDValue NewOp1 = 7249 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7250 SDValue NewOp2 = 7251 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7252 unsigned Opc = 7253 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 7254 // If the control is a constant, promote the node by clearing any extra 7255 // bits bits in the control. isel will form greviw/gorciw if the result is 7256 // sign extended. 7257 if (isa<ConstantSDNode>(NewOp2)) { 7258 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7259 DAG.getConstant(0x1f, DL, MVT::i64)); 7260 Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 7261 } 7262 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7263 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7264 break; 7265 } 7266 case Intrinsic::riscv_bcompress: 7267 case Intrinsic::riscv_bdecompress: 7268 case Intrinsic::riscv_bfp: 7269 case Intrinsic::riscv_fsl: 7270 case Intrinsic::riscv_fsr: { 7271 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7272 "Unexpected custom legalisation"); 7273 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 7274 break; 7275 } 7276 case Intrinsic::riscv_orc_b: { 7277 // Lower to the GORCI encoding for orc.b with the operand extended. 7278 SDValue NewOp = 7279 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7280 SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp, 7281 DAG.getConstant(7, DL, MVT::i64)); 7282 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7283 return; 7284 } 7285 case Intrinsic::riscv_shfl: 7286 case Intrinsic::riscv_unshfl: { 7287 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7288 "Unexpected custom legalisation"); 7289 SDValue NewOp1 = 7290 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7291 SDValue NewOp2 = 7292 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7293 unsigned Opc = 7294 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 7295 // There is no (UN)SHFLIW. If the control word is a constant, we can use 7296 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 7297 // will be shuffled the same way as the lower 32 bit half, but the two 7298 // halves won't cross. 7299 if (isa<ConstantSDNode>(NewOp2)) { 7300 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7301 DAG.getConstant(0xf, DL, MVT::i64)); 7302 Opc = 7303 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 7304 } 7305 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7306 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7307 break; 7308 } 7309 case Intrinsic::riscv_vmv_x_s: { 7310 EVT VT = N->getValueType(0); 7311 MVT XLenVT = Subtarget.getXLenVT(); 7312 if (VT.bitsLT(XLenVT)) { 7313 // Simple case just extract using vmv.x.s and truncate. 7314 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 7315 Subtarget.getXLenVT(), N->getOperand(1)); 7316 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 7317 return; 7318 } 7319 7320 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 7321 "Unexpected custom legalization"); 7322 7323 // We need to do the move in two steps. 7324 SDValue Vec = N->getOperand(1); 7325 MVT VecVT = Vec.getSimpleValueType(); 7326 7327 // First extract the lower XLEN bits of the element. 7328 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7329 7330 // To extract the upper XLEN bits of the vector element, shift the first 7331 // element right by 32 bits and re-extract the lower XLEN bits. 7332 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7333 SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG); 7334 7335 SDValue ThirtyTwoV = 7336 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 7337 DAG.getConstant(32, DL, XLenVT), VL); 7338 SDValue LShr32 = 7339 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 7340 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7341 7342 Results.push_back( 7343 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7344 break; 7345 } 7346 } 7347 break; 7348 } 7349 case ISD::VECREDUCE_ADD: 7350 case ISD::VECREDUCE_AND: 7351 case ISD::VECREDUCE_OR: 7352 case ISD::VECREDUCE_XOR: 7353 case ISD::VECREDUCE_SMAX: 7354 case ISD::VECREDUCE_UMAX: 7355 case ISD::VECREDUCE_SMIN: 7356 case ISD::VECREDUCE_UMIN: 7357 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 7358 Results.push_back(V); 7359 break; 7360 case ISD::VP_REDUCE_ADD: 7361 case ISD::VP_REDUCE_AND: 7362 case ISD::VP_REDUCE_OR: 7363 case ISD::VP_REDUCE_XOR: 7364 case ISD::VP_REDUCE_SMAX: 7365 case ISD::VP_REDUCE_UMAX: 7366 case ISD::VP_REDUCE_SMIN: 7367 case ISD::VP_REDUCE_UMIN: 7368 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 7369 Results.push_back(V); 7370 break; 7371 case ISD::FLT_ROUNDS_: { 7372 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7373 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7374 Results.push_back(Res.getValue(0)); 7375 Results.push_back(Res.getValue(1)); 7376 break; 7377 } 7378 } 7379 } 7380 7381 // A structure to hold one of the bit-manipulation patterns below. Together, a 7382 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7383 // (or (and (shl x, 1), 0xAAAAAAAA), 7384 // (and (srl x, 1), 0x55555555)) 7385 struct RISCVBitmanipPat { 7386 SDValue Op; 7387 unsigned ShAmt; 7388 bool IsSHL; 7389 7390 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7391 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7392 } 7393 }; 7394 7395 // Matches patterns of the form 7396 // (and (shl x, C2), (C1 << C2)) 7397 // (and (srl x, C2), C1) 7398 // (shl (and x, C1), C2) 7399 // (srl (and x, (C1 << C2)), C2) 7400 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7401 // The expected masks for each shift amount are specified in BitmanipMasks where 7402 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7403 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7404 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7405 // XLen is 64. 7406 static Optional<RISCVBitmanipPat> 7407 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7408 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7409 "Unexpected number of masks"); 7410 Optional<uint64_t> Mask; 7411 // Optionally consume a mask around the shift operation. 7412 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7413 Mask = Op.getConstantOperandVal(1); 7414 Op = Op.getOperand(0); 7415 } 7416 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7417 return None; 7418 bool IsSHL = Op.getOpcode() == ISD::SHL; 7419 7420 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7421 return None; 7422 uint64_t ShAmt = Op.getConstantOperandVal(1); 7423 7424 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7425 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7426 return None; 7427 // If we don't have enough masks for 64 bit, then we must be trying to 7428 // match SHFL so we're only allowed to shift 1/4 of the width. 7429 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7430 return None; 7431 7432 SDValue Src = Op.getOperand(0); 7433 7434 // The expected mask is shifted left when the AND is found around SHL 7435 // patterns. 7436 // ((x >> 1) & 0x55555555) 7437 // ((x << 1) & 0xAAAAAAAA) 7438 bool SHLExpMask = IsSHL; 7439 7440 if (!Mask) { 7441 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7442 // the mask is all ones: consume that now. 7443 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7444 Mask = Src.getConstantOperandVal(1); 7445 Src = Src.getOperand(0); 7446 // The expected mask is now in fact shifted left for SRL, so reverse the 7447 // decision. 7448 // ((x & 0xAAAAAAAA) >> 1) 7449 // ((x & 0x55555555) << 1) 7450 SHLExpMask = !SHLExpMask; 7451 } else { 7452 // Use a default shifted mask of all-ones if there's no AND, truncated 7453 // down to the expected width. This simplifies the logic later on. 7454 Mask = maskTrailingOnes<uint64_t>(Width); 7455 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7456 } 7457 } 7458 7459 unsigned MaskIdx = Log2_32(ShAmt); 7460 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7461 7462 if (SHLExpMask) 7463 ExpMask <<= ShAmt; 7464 7465 if (Mask != ExpMask) 7466 return None; 7467 7468 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7469 } 7470 7471 // Matches any of the following bit-manipulation patterns: 7472 // (and (shl x, 1), (0x55555555 << 1)) 7473 // (and (srl x, 1), 0x55555555) 7474 // (shl (and x, 0x55555555), 1) 7475 // (srl (and x, (0x55555555 << 1)), 1) 7476 // where the shift amount and mask may vary thus: 7477 // [1] = 0x55555555 / 0xAAAAAAAA 7478 // [2] = 0x33333333 / 0xCCCCCCCC 7479 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7480 // [8] = 0x00FF00FF / 0xFF00FF00 7481 // [16] = 0x0000FFFF / 0xFFFFFFFF 7482 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7483 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7484 // These are the unshifted masks which we use to match bit-manipulation 7485 // patterns. They may be shifted left in certain circumstances. 7486 static const uint64_t BitmanipMasks[] = { 7487 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7488 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7489 7490 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7491 } 7492 7493 // Try to fold (<bop> x, (reduction.<bop> vec, start)) 7494 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) { 7495 auto BinOpToRVVReduce = [](unsigned Opc) { 7496 switch (Opc) { 7497 default: 7498 llvm_unreachable("Unhandled binary to transfrom reduction"); 7499 case ISD::ADD: 7500 return RISCVISD::VECREDUCE_ADD_VL; 7501 case ISD::UMAX: 7502 return RISCVISD::VECREDUCE_UMAX_VL; 7503 case ISD::SMAX: 7504 return RISCVISD::VECREDUCE_SMAX_VL; 7505 case ISD::UMIN: 7506 return RISCVISD::VECREDUCE_UMIN_VL; 7507 case ISD::SMIN: 7508 return RISCVISD::VECREDUCE_SMIN_VL; 7509 case ISD::AND: 7510 return RISCVISD::VECREDUCE_AND_VL; 7511 case ISD::OR: 7512 return RISCVISD::VECREDUCE_OR_VL; 7513 case ISD::XOR: 7514 return RISCVISD::VECREDUCE_XOR_VL; 7515 case ISD::FADD: 7516 return RISCVISD::VECREDUCE_FADD_VL; 7517 case ISD::FMAXNUM: 7518 return RISCVISD::VECREDUCE_FMAX_VL; 7519 case ISD::FMINNUM: 7520 return RISCVISD::VECREDUCE_FMIN_VL; 7521 } 7522 }; 7523 7524 auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) { 7525 return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7526 isNullConstant(V.getOperand(1)) && 7527 V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc); 7528 }; 7529 7530 unsigned Opc = N->getOpcode(); 7531 unsigned ReduceIdx; 7532 if (IsReduction(N->getOperand(0), Opc)) 7533 ReduceIdx = 0; 7534 else if (IsReduction(N->getOperand(1), Opc)) 7535 ReduceIdx = 1; 7536 else 7537 return SDValue(); 7538 7539 // Skip if FADD disallows reassociation but the combiner needs. 7540 if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation()) 7541 return SDValue(); 7542 7543 SDValue Extract = N->getOperand(ReduceIdx); 7544 SDValue Reduce = Extract.getOperand(0); 7545 if (!Reduce.hasOneUse()) 7546 return SDValue(); 7547 7548 SDValue ScalarV = Reduce.getOperand(2); 7549 7550 // Make sure that ScalarV is a splat with VL=1. 7551 if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL && 7552 ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL && 7553 ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL) 7554 return SDValue(); 7555 7556 if (!isOneConstant(ScalarV.getOperand(2))) 7557 return SDValue(); 7558 7559 // TODO: Deal with value other than neutral element. 7560 auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) { 7561 if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() && 7562 isNullFPConstant(V)) 7563 return true; 7564 return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(), 7565 N->getFlags()) == V; 7566 }; 7567 7568 // Check the scalar of ScalarV is neutral element 7569 if (!IsRVVNeutralElement(N, ScalarV.getOperand(1))) 7570 return SDValue(); 7571 7572 if (!ScalarV.hasOneUse()) 7573 return SDValue(); 7574 7575 EVT SplatVT = ScalarV.getValueType(); 7576 SDValue NewStart = N->getOperand(1 - ReduceIdx); 7577 unsigned SplatOpc = RISCVISD::VFMV_S_F_VL; 7578 if (SplatVT.isInteger()) { 7579 auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode()); 7580 if (!C || C->isZero() || !isInt<5>(C->getSExtValue())) 7581 SplatOpc = RISCVISD::VMV_S_X_VL; 7582 else 7583 SplatOpc = RISCVISD::VMV_V_X_VL; 7584 } 7585 7586 SDValue NewScalarV = 7587 DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart, 7588 ScalarV.getOperand(2)); 7589 SDValue NewReduce = 7590 DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(), 7591 Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV, 7592 Reduce.getOperand(3), Reduce.getOperand(4)); 7593 return DAG.getNode(Extract.getOpcode(), SDLoc(Extract), 7594 Extract.getValueType(), NewReduce, Extract.getOperand(1)); 7595 } 7596 7597 // Match the following pattern as a GREVI(W) operation 7598 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7599 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7600 const RISCVSubtarget &Subtarget) { 7601 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7602 EVT VT = Op.getValueType(); 7603 7604 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7605 auto LHS = matchGREVIPat(Op.getOperand(0)); 7606 auto RHS = matchGREVIPat(Op.getOperand(1)); 7607 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7608 SDLoc DL(Op); 7609 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7610 DAG.getConstant(LHS->ShAmt, DL, VT)); 7611 } 7612 } 7613 return SDValue(); 7614 } 7615 7616 // Matches any the following pattern as a GORCI(W) operation 7617 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7618 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7619 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7620 // Note that with the variant of 3., 7621 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7622 // the inner pattern will first be matched as GREVI and then the outer 7623 // pattern will be matched to GORC via the first rule above. 7624 // 4. (or (rotl/rotr x, bitwidth/2), x) 7625 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7626 const RISCVSubtarget &Subtarget) { 7627 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7628 EVT VT = Op.getValueType(); 7629 7630 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7631 SDLoc DL(Op); 7632 SDValue Op0 = Op.getOperand(0); 7633 SDValue Op1 = Op.getOperand(1); 7634 7635 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7636 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7637 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7638 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7639 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7640 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7641 if ((Reverse.getOpcode() == ISD::ROTL || 7642 Reverse.getOpcode() == ISD::ROTR) && 7643 Reverse.getOperand(0) == X && 7644 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7645 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7646 if (RotAmt == (VT.getSizeInBits() / 2)) 7647 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7648 DAG.getConstant(RotAmt, DL, VT)); 7649 } 7650 return SDValue(); 7651 }; 7652 7653 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7654 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7655 return V; 7656 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7657 return V; 7658 7659 // OR is commutable so canonicalize its OR operand to the left 7660 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7661 std::swap(Op0, Op1); 7662 if (Op0.getOpcode() != ISD::OR) 7663 return SDValue(); 7664 SDValue OrOp0 = Op0.getOperand(0); 7665 SDValue OrOp1 = Op0.getOperand(1); 7666 auto LHS = matchGREVIPat(OrOp0); 7667 // OR is commutable so swap the operands and try again: x might have been 7668 // on the left 7669 if (!LHS) { 7670 std::swap(OrOp0, OrOp1); 7671 LHS = matchGREVIPat(OrOp0); 7672 } 7673 auto RHS = matchGREVIPat(Op1); 7674 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7675 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7676 DAG.getConstant(LHS->ShAmt, DL, VT)); 7677 } 7678 } 7679 return SDValue(); 7680 } 7681 7682 // Matches any of the following bit-manipulation patterns: 7683 // (and (shl x, 1), (0x22222222 << 1)) 7684 // (and (srl x, 1), 0x22222222) 7685 // (shl (and x, 0x22222222), 1) 7686 // (srl (and x, (0x22222222 << 1)), 1) 7687 // where the shift amount and mask may vary thus: 7688 // [1] = 0x22222222 / 0x44444444 7689 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7690 // [4] = 0x00F000F0 / 0x0F000F00 7691 // [8] = 0x0000FF00 / 0x00FF0000 7692 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7693 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7694 // These are the unshifted masks which we use to match bit-manipulation 7695 // patterns. They may be shifted left in certain circumstances. 7696 static const uint64_t BitmanipMasks[] = { 7697 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7698 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7699 7700 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7701 } 7702 7703 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7704 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7705 const RISCVSubtarget &Subtarget) { 7706 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7707 EVT VT = Op.getValueType(); 7708 7709 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7710 return SDValue(); 7711 7712 SDValue Op0 = Op.getOperand(0); 7713 SDValue Op1 = Op.getOperand(1); 7714 7715 // Or is commutable so canonicalize the second OR to the LHS. 7716 if (Op0.getOpcode() != ISD::OR) 7717 std::swap(Op0, Op1); 7718 if (Op0.getOpcode() != ISD::OR) 7719 return SDValue(); 7720 7721 // We found an inner OR, so our operands are the operands of the inner OR 7722 // and the other operand of the outer OR. 7723 SDValue A = Op0.getOperand(0); 7724 SDValue B = Op0.getOperand(1); 7725 SDValue C = Op1; 7726 7727 auto Match1 = matchSHFLPat(A); 7728 auto Match2 = matchSHFLPat(B); 7729 7730 // If neither matched, we failed. 7731 if (!Match1 && !Match2) 7732 return SDValue(); 7733 7734 // We had at least one match. if one failed, try the remaining C operand. 7735 if (!Match1) { 7736 std::swap(A, C); 7737 Match1 = matchSHFLPat(A); 7738 if (!Match1) 7739 return SDValue(); 7740 } else if (!Match2) { 7741 std::swap(B, C); 7742 Match2 = matchSHFLPat(B); 7743 if (!Match2) 7744 return SDValue(); 7745 } 7746 assert(Match1 && Match2); 7747 7748 // Make sure our matches pair up. 7749 if (!Match1->formsPairWith(*Match2)) 7750 return SDValue(); 7751 7752 // All the remains is to make sure C is an AND with the same input, that masks 7753 // out the bits that are being shuffled. 7754 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7755 C.getOperand(0) != Match1->Op) 7756 return SDValue(); 7757 7758 uint64_t Mask = C.getConstantOperandVal(1); 7759 7760 static const uint64_t BitmanipMasks[] = { 7761 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7762 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7763 }; 7764 7765 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7766 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7767 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7768 7769 if (Mask != ExpMask) 7770 return SDValue(); 7771 7772 SDLoc DL(Op); 7773 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7774 DAG.getConstant(Match1->ShAmt, DL, VT)); 7775 } 7776 7777 // Optimize (add (shl x, c0), (shl y, c1)) -> 7778 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7779 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7780 const RISCVSubtarget &Subtarget) { 7781 // Perform this optimization only in the zba extension. 7782 if (!Subtarget.hasStdExtZba()) 7783 return SDValue(); 7784 7785 // Skip for vector types and larger types. 7786 EVT VT = N->getValueType(0); 7787 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7788 return SDValue(); 7789 7790 // The two operand nodes must be SHL and have no other use. 7791 SDValue N0 = N->getOperand(0); 7792 SDValue N1 = N->getOperand(1); 7793 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7794 !N0->hasOneUse() || !N1->hasOneUse()) 7795 return SDValue(); 7796 7797 // Check c0 and c1. 7798 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7799 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7800 if (!N0C || !N1C) 7801 return SDValue(); 7802 int64_t C0 = N0C->getSExtValue(); 7803 int64_t C1 = N1C->getSExtValue(); 7804 if (C0 <= 0 || C1 <= 0) 7805 return SDValue(); 7806 7807 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7808 int64_t Bits = std::min(C0, C1); 7809 int64_t Diff = std::abs(C0 - C1); 7810 if (Diff != 1 && Diff != 2 && Diff != 3) 7811 return SDValue(); 7812 7813 // Build nodes. 7814 SDLoc DL(N); 7815 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7816 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7817 SDValue NA0 = 7818 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7819 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7820 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7821 } 7822 7823 // Combine 7824 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7825 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7826 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7827 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7828 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7829 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7830 // The grev patterns represents BSWAP. 7831 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7832 // off the grev. 7833 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7834 const RISCVSubtarget &Subtarget) { 7835 bool IsWInstruction = 7836 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7837 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7838 IsWInstruction) && 7839 "Unexpected opcode!"); 7840 SDValue Src = N->getOperand(0); 7841 EVT VT = N->getValueType(0); 7842 SDLoc DL(N); 7843 7844 if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV) 7845 return SDValue(); 7846 7847 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7848 !isa<ConstantSDNode>(Src.getOperand(1))) 7849 return SDValue(); 7850 7851 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7852 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7853 7854 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7855 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7856 unsigned ShAmt1 = N->getConstantOperandVal(1); 7857 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7858 if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7859 return SDValue(); 7860 7861 Src = Src.getOperand(0); 7862 7863 // Toggle bit the MSB of the shift. 7864 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7865 if (CombinedShAmt == 0) 7866 return Src; 7867 7868 SDValue Res = DAG.getNode( 7869 RISCVISD::GREV, DL, VT, Src, 7870 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7871 if (!IsWInstruction) 7872 return Res; 7873 7874 // Sign extend the result to match the behavior of the rotate. This will be 7875 // selected to GREVIW in isel. 7876 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res, 7877 DAG.getValueType(MVT::i32)); 7878 } 7879 7880 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7881 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7882 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7883 // not undo itself, but they are redundant. 7884 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7885 bool IsGORC = N->getOpcode() == RISCVISD::GORC; 7886 assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode"); 7887 SDValue Src = N->getOperand(0); 7888 7889 if (Src.getOpcode() != N->getOpcode()) 7890 return SDValue(); 7891 7892 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7893 !isa<ConstantSDNode>(Src.getOperand(1))) 7894 return SDValue(); 7895 7896 unsigned ShAmt1 = N->getConstantOperandVal(1); 7897 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7898 Src = Src.getOperand(0); 7899 7900 unsigned CombinedShAmt; 7901 if (IsGORC) 7902 CombinedShAmt = ShAmt1 | ShAmt2; 7903 else 7904 CombinedShAmt = ShAmt1 ^ ShAmt2; 7905 7906 if (CombinedShAmt == 0) 7907 return Src; 7908 7909 SDLoc DL(N); 7910 return DAG.getNode( 7911 N->getOpcode(), DL, N->getValueType(0), Src, 7912 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7913 } 7914 7915 // Combine a constant select operand into its use: 7916 // 7917 // (and (select cond, -1, c), x) 7918 // -> (select cond, x, (and x, c)) [AllOnes=1] 7919 // (or (select cond, 0, c), x) 7920 // -> (select cond, x, (or x, c)) [AllOnes=0] 7921 // (xor (select cond, 0, c), x) 7922 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7923 // (add (select cond, 0, c), x) 7924 // -> (select cond, x, (add x, c)) [AllOnes=0] 7925 // (sub x, (select cond, 0, c)) 7926 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7927 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7928 SelectionDAG &DAG, bool AllOnes) { 7929 EVT VT = N->getValueType(0); 7930 7931 // Skip vectors. 7932 if (VT.isVector()) 7933 return SDValue(); 7934 7935 if ((Slct.getOpcode() != ISD::SELECT && 7936 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7937 !Slct.hasOneUse()) 7938 return SDValue(); 7939 7940 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7941 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7942 }; 7943 7944 bool SwapSelectOps; 7945 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7946 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7947 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7948 SDValue NonConstantVal; 7949 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7950 SwapSelectOps = false; 7951 NonConstantVal = FalseVal; 7952 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7953 SwapSelectOps = true; 7954 NonConstantVal = TrueVal; 7955 } else 7956 return SDValue(); 7957 7958 // Slct is now know to be the desired identity constant when CC is true. 7959 TrueVal = OtherOp; 7960 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7961 // Unless SwapSelectOps says the condition should be false. 7962 if (SwapSelectOps) 7963 std::swap(TrueVal, FalseVal); 7964 7965 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7966 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7967 {Slct.getOperand(0), Slct.getOperand(1), 7968 Slct.getOperand(2), TrueVal, FalseVal}); 7969 7970 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7971 {Slct.getOperand(0), TrueVal, FalseVal}); 7972 } 7973 7974 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7975 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7976 bool AllOnes) { 7977 SDValue N0 = N->getOperand(0); 7978 SDValue N1 = N->getOperand(1); 7979 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7980 return Result; 7981 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7982 return Result; 7983 return SDValue(); 7984 } 7985 7986 // Transform (add (mul x, c0), c1) -> 7987 // (add (mul (add x, c1/c0), c0), c1%c0). 7988 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7989 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7990 // to an infinite loop in DAGCombine if transformed. 7991 // Or transform (add (mul x, c0), c1) -> 7992 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7993 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7994 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7995 // lead to an infinite loop in DAGCombine if transformed. 7996 // Or transform (add (mul x, c0), c1) -> 7997 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7998 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7999 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 8000 // lead to an infinite loop in DAGCombine if transformed. 8001 // Or transform (add (mul x, c0), c1) -> 8002 // (mul (add x, c1/c0), c0). 8003 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 8004 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 8005 const RISCVSubtarget &Subtarget) { 8006 // Skip for vector types and larger types. 8007 EVT VT = N->getValueType(0); 8008 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 8009 return SDValue(); 8010 // The first operand node must be a MUL and has no other use. 8011 SDValue N0 = N->getOperand(0); 8012 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 8013 return SDValue(); 8014 // Check if c0 and c1 match above conditions. 8015 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8016 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8017 if (!N0C || !N1C) 8018 return SDValue(); 8019 // If N0C has multiple uses it's possible one of the cases in 8020 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 8021 // in an infinite loop. 8022 if (!N0C->hasOneUse()) 8023 return SDValue(); 8024 int64_t C0 = N0C->getSExtValue(); 8025 int64_t C1 = N1C->getSExtValue(); 8026 int64_t CA, CB; 8027 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 8028 return SDValue(); 8029 // Search for proper CA (non-zero) and CB that both are simm12. 8030 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 8031 !isInt<12>(C0 * (C1 / C0))) { 8032 CA = C1 / C0; 8033 CB = C1 % C0; 8034 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 8035 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 8036 CA = C1 / C0 + 1; 8037 CB = C1 % C0 - C0; 8038 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 8039 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 8040 CA = C1 / C0 - 1; 8041 CB = C1 % C0 + C0; 8042 } else 8043 return SDValue(); 8044 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 8045 SDLoc DL(N); 8046 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 8047 DAG.getConstant(CA, DL, VT)); 8048 SDValue New1 = 8049 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 8050 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 8051 } 8052 8053 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 8054 const RISCVSubtarget &Subtarget) { 8055 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 8056 return V; 8057 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 8058 return V; 8059 if (SDValue V = combineBinOpToReduce(N, DAG)) 8060 return V; 8061 // fold (add (select lhs, rhs, cc, 0, y), x) -> 8062 // (select lhs, rhs, cc, x, (add x, y)) 8063 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8064 } 8065 8066 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 8067 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 8068 // (select lhs, rhs, cc, x, (sub x, y)) 8069 SDValue N0 = N->getOperand(0); 8070 SDValue N1 = N->getOperand(1); 8071 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 8072 } 8073 8074 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG, 8075 const RISCVSubtarget &Subtarget) { 8076 SDValue N0 = N->getOperand(0); 8077 // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero 8078 // extending X. This is safe since we only need the LSB after the shift and 8079 // shift amounts larger than 31 would produce poison. If we wait until 8080 // type legalization, we'll create RISCVISD::SRLW and we can't recover it 8081 // to use a BEXT instruction. 8082 if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() && 8083 N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) && 8084 N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) && 8085 N0.hasOneUse()) { 8086 SDLoc DL(N); 8087 SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0)); 8088 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1)); 8089 SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1); 8090 SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl, 8091 DAG.getConstant(1, DL, MVT::i64)); 8092 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And); 8093 } 8094 8095 if (SDValue V = combineBinOpToReduce(N, DAG)) 8096 return V; 8097 8098 // fold (and (select lhs, rhs, cc, -1, y), x) -> 8099 // (select lhs, rhs, cc, x, (and x, y)) 8100 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 8101 } 8102 8103 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 8104 const RISCVSubtarget &Subtarget) { 8105 if (Subtarget.hasStdExtZbp()) { 8106 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 8107 return GREV; 8108 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 8109 return GORC; 8110 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 8111 return SHFL; 8112 } 8113 8114 if (SDValue V = combineBinOpToReduce(N, DAG)) 8115 return V; 8116 // fold (or (select cond, 0, y), x) -> 8117 // (select cond, x, (or x, y)) 8118 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8119 } 8120 8121 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 8122 SDValue N0 = N->getOperand(0); 8123 SDValue N1 = N->getOperand(1); 8124 8125 // fold (xor (sllw 1, x), -1) -> (rolw ~1, x) 8126 // NOTE: Assumes ROL being legal means ROLW is legal. 8127 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8128 if (N0.getOpcode() == RISCVISD::SLLW && 8129 isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) && 8130 TLI.isOperationLegal(ISD::ROTL, MVT::i64)) { 8131 SDLoc DL(N); 8132 return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64, 8133 DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1)); 8134 } 8135 8136 if (SDValue V = combineBinOpToReduce(N, DAG)) 8137 return V; 8138 // fold (xor (select cond, 0, y), x) -> 8139 // (select cond, x, (xor x, y)) 8140 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8141 } 8142 8143 // Replace (seteq (i64 (and X, 0xffffffff)), C1) with 8144 // (seteq (i64 (sext_inreg (X, i32)), C1')) where C1' is C1 sign extended from 8145 // bit 31. Same for setne. C1' may be cheaper to materialize and the sext_inreg 8146 // can become a sext.w instead of a shift pair. 8147 static SDValue performSETCCCombine(SDNode *N, SelectionDAG &DAG, 8148 const RISCVSubtarget &Subtarget) { 8149 SDValue N0 = N->getOperand(0); 8150 SDValue N1 = N->getOperand(1); 8151 EVT VT = N->getValueType(0); 8152 EVT OpVT = N0.getValueType(); 8153 8154 if (OpVT != MVT::i64 || !Subtarget.is64Bit()) 8155 return SDValue(); 8156 8157 // RHS needs to be a constant. 8158 auto *N1C = dyn_cast<ConstantSDNode>(N1); 8159 if (!N1C) 8160 return SDValue(); 8161 8162 // LHS needs to be (and X, 0xffffffff). 8163 if (N0.getOpcode() != ISD::AND || !N0.hasOneUse() || 8164 !isa<ConstantSDNode>(N0.getOperand(1)) || 8165 N0.getConstantOperandVal(1) != UINT64_C(0xffffffff)) 8166 return SDValue(); 8167 8168 // Looking for an equality compare. 8169 ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8170 if (!isIntEqualitySetCC(Cond)) 8171 return SDValue(); 8172 8173 const APInt &C1 = cast<ConstantSDNode>(N1)->getAPIntValue(); 8174 8175 SDLoc dl(N); 8176 // If the constant is larger than 2^32 - 1 it is impossible for both sides 8177 // to be equal. 8178 if (C1.getActiveBits() > 32) 8179 return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT); 8180 8181 SDValue SExtOp = DAG.getNode(ISD::SIGN_EXTEND_INREG, N, OpVT, 8182 N0.getOperand(0), DAG.getValueType(MVT::i32)); 8183 return DAG.getSetCC(dl, VT, SExtOp, DAG.getConstant(C1.trunc(32).sext(64), 8184 dl, OpVT), Cond); 8185 } 8186 8187 static SDValue 8188 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 8189 const RISCVSubtarget &Subtarget) { 8190 SDValue Src = N->getOperand(0); 8191 EVT VT = N->getValueType(0); 8192 8193 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 8194 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8195 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 8196 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 8197 Src.getOperand(0)); 8198 8199 // Fold (i64 (sext_inreg (abs X), i32)) -> 8200 // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits. 8201 // The (sext_inreg (neg X), i32) will be selected to negw by isel. This 8202 // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user 8203 // of the (i32 (abs X)) is a sext or setcc or something else that causes type 8204 // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have 8205 // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg 8206 // may get combined into an earlier operation so we need to use 8207 // ComputeNumSignBits. 8208 // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for 8209 // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so 8210 // we can't assume that X has 33 sign bits. We must check. 8211 if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() && 8212 Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 && 8213 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 && 8214 DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) { 8215 SDLoc DL(N); 8216 SDValue Freeze = DAG.getFreeze(Src.getOperand(0)); 8217 SDValue Neg = 8218 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze); 8219 Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg, 8220 DAG.getValueType(MVT::i32)); 8221 return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg); 8222 } 8223 8224 return SDValue(); 8225 } 8226 8227 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 8228 // vwadd(u).vv/vx or vwsub(u).vv/vx. 8229 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 8230 bool Commute = false) { 8231 assert((N->getOpcode() == RISCVISD::ADD_VL || 8232 N->getOpcode() == RISCVISD::SUB_VL) && 8233 "Unexpected opcode"); 8234 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 8235 SDValue Op0 = N->getOperand(0); 8236 SDValue Op1 = N->getOperand(1); 8237 if (Commute) 8238 std::swap(Op0, Op1); 8239 8240 MVT VT = N->getSimpleValueType(0); 8241 8242 // Determine the narrow size for a widening add/sub. 8243 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8244 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8245 VT.getVectorElementCount()); 8246 8247 SDValue Mask = N->getOperand(2); 8248 SDValue VL = N->getOperand(3); 8249 8250 SDLoc DL(N); 8251 8252 // If the RHS is a sext or zext, we can form a widening op. 8253 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 8254 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 8255 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 8256 unsigned ExtOpc = Op1.getOpcode(); 8257 Op1 = Op1.getOperand(0); 8258 // Re-introduce narrower extends if needed. 8259 if (Op1.getValueType() != NarrowVT) 8260 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8261 8262 unsigned WOpc; 8263 if (ExtOpc == RISCVISD::VSEXT_VL) 8264 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 8265 else 8266 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 8267 8268 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 8269 } 8270 8271 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 8272 // sext/zext? 8273 8274 return SDValue(); 8275 } 8276 8277 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 8278 // vwsub(u).vv/vx. 8279 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 8280 SDValue Op0 = N->getOperand(0); 8281 SDValue Op1 = N->getOperand(1); 8282 SDValue Mask = N->getOperand(2); 8283 SDValue VL = N->getOperand(3); 8284 8285 MVT VT = N->getSimpleValueType(0); 8286 MVT NarrowVT = Op1.getSimpleValueType(); 8287 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 8288 8289 unsigned VOpc; 8290 switch (N->getOpcode()) { 8291 default: llvm_unreachable("Unexpected opcode"); 8292 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 8293 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 8294 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 8295 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 8296 } 8297 8298 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 8299 N->getOpcode() == RISCVISD::VWSUB_W_VL; 8300 8301 SDLoc DL(N); 8302 8303 // If the LHS is a sext or zext, we can narrow this op to the same size as 8304 // the RHS. 8305 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 8306 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 8307 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 8308 unsigned ExtOpc = Op0.getOpcode(); 8309 Op0 = Op0.getOperand(0); 8310 // Re-introduce narrower extends if needed. 8311 if (Op0.getValueType() != NarrowVT) 8312 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8313 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 8314 } 8315 8316 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 8317 N->getOpcode() == RISCVISD::VWADDU_W_VL; 8318 8319 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 8320 // to commute and use a vwadd(u).vx instead. 8321 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 8322 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 8323 Op0 = Op0.getOperand(1); 8324 8325 // See if have enough sign bits or zero bits in the scalar to use a 8326 // widening add/sub by splatting to smaller element size. 8327 unsigned EltBits = VT.getScalarSizeInBits(); 8328 unsigned ScalarBits = Op0.getValueSizeInBits(); 8329 // Make sure we're getting all element bits from the scalar register. 8330 // FIXME: Support implicit sign extension of vmv.v.x? 8331 if (ScalarBits < EltBits) 8332 return SDValue(); 8333 8334 if (IsSigned) { 8335 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 8336 return SDValue(); 8337 } else { 8338 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8339 if (!DAG.MaskedValueIsZero(Op0, Mask)) 8340 return SDValue(); 8341 } 8342 8343 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8344 DAG.getUNDEF(NarrowVT), Op0, VL); 8345 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 8346 } 8347 8348 return SDValue(); 8349 } 8350 8351 // Try to form VWMUL, VWMULU or VWMULSU. 8352 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 8353 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 8354 bool Commute) { 8355 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 8356 SDValue Op0 = N->getOperand(0); 8357 SDValue Op1 = N->getOperand(1); 8358 if (Commute) 8359 std::swap(Op0, Op1); 8360 8361 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 8362 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 8363 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 8364 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 8365 return SDValue(); 8366 8367 SDValue Mask = N->getOperand(2); 8368 SDValue VL = N->getOperand(3); 8369 8370 // Make sure the mask and VL match. 8371 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 8372 return SDValue(); 8373 8374 MVT VT = N->getSimpleValueType(0); 8375 8376 // Determine the narrow size for a widening multiply. 8377 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8378 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8379 VT.getVectorElementCount()); 8380 8381 SDLoc DL(N); 8382 8383 // See if the other operand is the same opcode. 8384 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 8385 if (!Op1.hasOneUse()) 8386 return SDValue(); 8387 8388 // Make sure the mask and VL match. 8389 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 8390 return SDValue(); 8391 8392 Op1 = Op1.getOperand(0); 8393 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 8394 // The operand is a splat of a scalar. 8395 8396 // The pasthru must be undef for tail agnostic 8397 if (!Op1.getOperand(0).isUndef()) 8398 return SDValue(); 8399 // The VL must be the same. 8400 if (Op1.getOperand(2) != VL) 8401 return SDValue(); 8402 8403 // Get the scalar value. 8404 Op1 = Op1.getOperand(1); 8405 8406 // See if have enough sign bits or zero bits in the scalar to use a 8407 // widening multiply by splatting to smaller element size. 8408 unsigned EltBits = VT.getScalarSizeInBits(); 8409 unsigned ScalarBits = Op1.getValueSizeInBits(); 8410 // Make sure we're getting all element bits from the scalar register. 8411 // FIXME: Support implicit sign extension of vmv.v.x? 8412 if (ScalarBits < EltBits) 8413 return SDValue(); 8414 8415 // If the LHS is a sign extend, try to use vwmul. 8416 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 8417 // Can use vwmul. 8418 } else { 8419 // Otherwise try to use vwmulu or vwmulsu. 8420 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8421 if (DAG.MaskedValueIsZero(Op1, Mask)) 8422 IsVWMULSU = IsSignExt; 8423 else 8424 return SDValue(); 8425 } 8426 8427 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8428 DAG.getUNDEF(NarrowVT), Op1, VL); 8429 } else 8430 return SDValue(); 8431 8432 Op0 = Op0.getOperand(0); 8433 8434 // Re-introduce narrower extends if needed. 8435 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 8436 if (Op0.getValueType() != NarrowVT) 8437 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8438 // vwmulsu requires second operand to be zero extended. 8439 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 8440 if (Op1.getValueType() != NarrowVT) 8441 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8442 8443 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 8444 if (!IsVWMULSU) 8445 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 8446 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 8447 } 8448 8449 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 8450 switch (Op.getOpcode()) { 8451 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 8452 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 8453 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 8454 case ISD::FCEIL: return RISCVFPRndMode::RUP; 8455 case ISD::FROUND: return RISCVFPRndMode::RMM; 8456 } 8457 8458 return RISCVFPRndMode::Invalid; 8459 } 8460 8461 // Fold 8462 // (fp_to_int (froundeven X)) -> fcvt X, rne 8463 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 8464 // (fp_to_int (ffloor X)) -> fcvt X, rdn 8465 // (fp_to_int (fceil X)) -> fcvt X, rup 8466 // (fp_to_int (fround X)) -> fcvt X, rmm 8467 static SDValue performFP_TO_INTCombine(SDNode *N, 8468 TargetLowering::DAGCombinerInfo &DCI, 8469 const RISCVSubtarget &Subtarget) { 8470 SelectionDAG &DAG = DCI.DAG; 8471 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8472 MVT XLenVT = Subtarget.getXLenVT(); 8473 8474 // Only handle XLen or i32 types. Other types narrower than XLen will 8475 // eventually be legalized to XLenVT. 8476 EVT VT = N->getValueType(0); 8477 if (VT != MVT::i32 && VT != XLenVT) 8478 return SDValue(); 8479 8480 SDValue Src = N->getOperand(0); 8481 8482 // Ensure the FP type is also legal. 8483 if (!TLI.isTypeLegal(Src.getValueType())) 8484 return SDValue(); 8485 8486 // Don't do this for f16 with Zfhmin and not Zfh. 8487 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8488 return SDValue(); 8489 8490 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8491 if (FRM == RISCVFPRndMode::Invalid) 8492 return SDValue(); 8493 8494 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8495 8496 unsigned Opc; 8497 if (VT == XLenVT) 8498 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8499 else 8500 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8501 8502 SDLoc DL(N); 8503 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 8504 DAG.getTargetConstant(FRM, DL, XLenVT)); 8505 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 8506 } 8507 8508 // Fold 8509 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 8510 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 8511 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8512 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8513 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8514 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8515 TargetLowering::DAGCombinerInfo &DCI, 8516 const RISCVSubtarget &Subtarget) { 8517 SelectionDAG &DAG = DCI.DAG; 8518 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8519 MVT XLenVT = Subtarget.getXLenVT(); 8520 8521 // Only handle XLen types. Other types narrower than XLen will eventually be 8522 // legalized to XLenVT. 8523 EVT DstVT = N->getValueType(0); 8524 if (DstVT != XLenVT) 8525 return SDValue(); 8526 8527 SDValue Src = N->getOperand(0); 8528 8529 // Ensure the FP type is also legal. 8530 if (!TLI.isTypeLegal(Src.getValueType())) 8531 return SDValue(); 8532 8533 // Don't do this for f16 with Zfhmin and not Zfh. 8534 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8535 return SDValue(); 8536 8537 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8538 8539 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8540 if (FRM == RISCVFPRndMode::Invalid) 8541 return SDValue(); 8542 8543 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8544 8545 unsigned Opc; 8546 if (SatVT == DstVT) 8547 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8548 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8549 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8550 else 8551 return SDValue(); 8552 // FIXME: Support other SatVTs by clamping before or after the conversion. 8553 8554 Src = Src.getOperand(0); 8555 8556 SDLoc DL(N); 8557 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8558 DAG.getTargetConstant(FRM, DL, XLenVT)); 8559 8560 // RISCV FP-to-int conversions saturate to the destination register size, but 8561 // don't produce 0 for nan. 8562 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8563 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8564 } 8565 8566 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is 8567 // smaller than XLenVT. 8568 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG, 8569 const RISCVSubtarget &Subtarget) { 8570 assert(Subtarget.hasStdExtZbkb() && "Unexpected extension"); 8571 8572 SDValue Src = N->getOperand(0); 8573 if (Src.getOpcode() != ISD::BSWAP) 8574 return SDValue(); 8575 8576 EVT VT = N->getValueType(0); 8577 if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() || 8578 !isPowerOf2_32(VT.getSizeInBits())) 8579 return SDValue(); 8580 8581 SDLoc DL(N); 8582 return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0), 8583 DAG.getConstant(7, DL, VT)); 8584 } 8585 8586 // Convert from one FMA opcode to another based on whether we are negating the 8587 // multiply result and/or the accumulator. 8588 // NOTE: Only supports RVV operations with VL. 8589 static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc) { 8590 assert((NegMul || NegAcc) && "Not negating anything?"); 8591 8592 // Negating the multiply result changes ADD<->SUB and toggles 'N'. 8593 if (NegMul) { 8594 // clang-format off 8595 switch (Opcode) { 8596 default: llvm_unreachable("Unexpected opcode"); 8597 case RISCVISD::VFMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break; 8598 case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFMADD_VL; break; 8599 case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFMSUB_VL; break; 8600 case RISCVISD::VFMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break; 8601 } 8602 // clang-format on 8603 } 8604 8605 // Negating the accumulator changes ADD<->SUB. 8606 if (NegAcc) { 8607 // clang-format off 8608 switch (Opcode) { 8609 default: llvm_unreachable("Unexpected opcode"); 8610 case RISCVISD::VFMADD_VL: Opcode = RISCVISD::VFMSUB_VL; break; 8611 case RISCVISD::VFMSUB_VL: Opcode = RISCVISD::VFMADD_VL; break; 8612 case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break; 8613 case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break; 8614 } 8615 // clang-format on 8616 } 8617 8618 return Opcode; 8619 } 8620 8621 static SDValue performSRACombine(SDNode *N, SelectionDAG &DAG, 8622 const RISCVSubtarget &Subtarget) { 8623 assert(N->getOpcode() == ISD::SRA && "Unexpected opcode"); 8624 8625 if (N->getValueType(0) != MVT::i64 || !Subtarget.is64Bit()) 8626 return SDValue(); 8627 8628 if (!isa<ConstantSDNode>(N->getOperand(1))) 8629 return SDValue(); 8630 uint64_t ShAmt = N->getConstantOperandVal(1); 8631 if (ShAmt > 32) 8632 return SDValue(); 8633 8634 SDValue N0 = N->getOperand(0); 8635 8636 // Combine (sra (sext_inreg (shl X, C1), i32), C2) -> 8637 // (sra (shl X, C1+32), C2+32) so it gets selected as SLLI+SRAI instead of 8638 // SLLIW+SRAIW. SLLI+SRAI have compressed forms. 8639 if (ShAmt < 32 && 8640 N0.getOpcode() == ISD::SIGN_EXTEND_INREG && N0.hasOneUse() && 8641 cast<VTSDNode>(N0.getOperand(1))->getVT() == MVT::i32 && 8642 N0.getOperand(0).getOpcode() == ISD::SHL && N0.getOperand(0).hasOneUse() && 8643 isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) { 8644 uint64_t LShAmt = N0.getOperand(0).getConstantOperandVal(1); 8645 if (LShAmt < 32) { 8646 SDLoc ShlDL(N0.getOperand(0)); 8647 SDValue Shl = DAG.getNode(ISD::SHL, ShlDL, MVT::i64, 8648 N0.getOperand(0).getOperand(0), 8649 DAG.getConstant(LShAmt + 32, ShlDL, MVT::i64)); 8650 SDLoc DL(N); 8651 return DAG.getNode(ISD::SRA, DL, MVT::i64, Shl, 8652 DAG.getConstant(ShAmt + 32, DL, MVT::i64)); 8653 } 8654 } 8655 8656 // Combine (sra (shl X, 32), 32 - C) -> (shl (sext_inreg X, i32), C) 8657 // FIXME: Should this be a generic combine? There's a similar combine on X86. 8658 // 8659 // Also try these folds where an add or sub is in the middle. 8660 // (sra (add (shl X, 32), C1), 32 - C) -> (shl (sext_inreg (add X, C1), C) 8661 // (sra (sub C1, (shl X, 32)), 32 - C) -> (shl (sext_inreg (sub C1, X), C) 8662 SDValue Shl; 8663 ConstantSDNode *AddC = nullptr; 8664 8665 // We might have an ADD or SUB between the SRA and SHL. 8666 bool IsAdd = N0.getOpcode() == ISD::ADD; 8667 if ((IsAdd || N0.getOpcode() == ISD::SUB)) { 8668 if (!N0.hasOneUse()) 8669 return SDValue(); 8670 // Other operand needs to be a constant we can modify. 8671 AddC = dyn_cast<ConstantSDNode>(N0.getOperand(IsAdd ? 1 : 0)); 8672 if (!AddC) 8673 return SDValue(); 8674 8675 // AddC needs to have at least 32 trailing zeros. 8676 if (AddC->getAPIntValue().countTrailingZeros() < 32) 8677 return SDValue(); 8678 8679 Shl = N0.getOperand(IsAdd ? 0 : 1); 8680 } else { 8681 // Not an ADD or SUB. 8682 Shl = N0; 8683 } 8684 8685 // Look for a shift left by 32. 8686 if (Shl.getOpcode() != ISD::SHL || !Shl.hasOneUse() || 8687 !isa<ConstantSDNode>(Shl.getOperand(1)) || 8688 Shl.getConstantOperandVal(1) != 32) 8689 return SDValue(); 8690 8691 SDLoc DL(N); 8692 SDValue In = Shl.getOperand(0); 8693 8694 // If we looked through an ADD or SUB, we need to rebuild it with the shifted 8695 // constant. 8696 if (AddC) { 8697 SDValue ShiftedAddC = 8698 DAG.getConstant(AddC->getAPIntValue().lshr(32), DL, MVT::i64); 8699 if (IsAdd) 8700 In = DAG.getNode(ISD::ADD, DL, MVT::i64, In, ShiftedAddC); 8701 else 8702 In = DAG.getNode(ISD::SUB, DL, MVT::i64, ShiftedAddC, In); 8703 } 8704 8705 SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, In, 8706 DAG.getValueType(MVT::i32)); 8707 if (ShAmt == 32) 8708 return SExt; 8709 8710 return DAG.getNode( 8711 ISD::SHL, DL, MVT::i64, SExt, 8712 DAG.getConstant(32 - ShAmt, DL, MVT::i64)); 8713 } 8714 8715 // Perform common combines for BR_CC and SELECT_CC condtions. 8716 static bool combine_CC(SDValue &LHS, SDValue &RHS, SDValue &CC, const SDLoc &DL, 8717 SelectionDAG &DAG, const RISCVSubtarget &Subtarget) { 8718 ISD::CondCode CCVal = cast<CondCodeSDNode>(CC)->get(); 8719 if (!ISD::isIntEqualitySetCC(CCVal)) 8720 return false; 8721 8722 // Fold ((setlt X, Y), 0, ne) -> (X, Y, lt) 8723 // Sometimes the setcc is introduced after br_cc/select_cc has been formed. 8724 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8725 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8726 // If we're looking for eq 0 instead of ne 0, we need to invert the 8727 // condition. 8728 bool Invert = CCVal == ISD::SETEQ; 8729 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8730 if (Invert) 8731 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8732 8733 RHS = LHS.getOperand(1); 8734 LHS = LHS.getOperand(0); 8735 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8736 8737 CC = DAG.getCondCode(CCVal); 8738 return true; 8739 } 8740 8741 // Fold ((xor X, Y), 0, eq/ne) -> (X, Y, eq/ne) 8742 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) { 8743 RHS = LHS.getOperand(1); 8744 LHS = LHS.getOperand(0); 8745 return true; 8746 } 8747 8748 // Fold ((srl (and X, 1<<C), C), 0, eq/ne) -> ((shl X, XLen-1-C), 0, ge/lt) 8749 if (isNullConstant(RHS) && LHS.getOpcode() == ISD::SRL && LHS.hasOneUse() && 8750 LHS.getOperand(1).getOpcode() == ISD::Constant) { 8751 SDValue LHS0 = LHS.getOperand(0); 8752 if (LHS0.getOpcode() == ISD::AND && 8753 LHS0.getOperand(1).getOpcode() == ISD::Constant) { 8754 uint64_t Mask = LHS0.getConstantOperandVal(1); 8755 uint64_t ShAmt = LHS.getConstantOperandVal(1); 8756 if (isPowerOf2_64(Mask) && Log2_64(Mask) == ShAmt) { 8757 CCVal = CCVal == ISD::SETEQ ? ISD::SETGE : ISD::SETLT; 8758 CC = DAG.getCondCode(CCVal); 8759 8760 ShAmt = LHS.getValueSizeInBits() - 1 - ShAmt; 8761 LHS = LHS0.getOperand(0); 8762 if (ShAmt != 0) 8763 LHS = 8764 DAG.getNode(ISD::SHL, DL, LHS.getValueType(), LHS0.getOperand(0), 8765 DAG.getConstant(ShAmt, DL, LHS.getValueType())); 8766 return true; 8767 } 8768 } 8769 } 8770 8771 // (X, 1, setne) -> // (X, 0, seteq) if we can prove X is 0/1. 8772 // This can occur when legalizing some floating point comparisons. 8773 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8774 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8775 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8776 CC = DAG.getCondCode(CCVal); 8777 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8778 return true; 8779 } 8780 8781 return false; 8782 } 8783 8784 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8785 DAGCombinerInfo &DCI) const { 8786 SelectionDAG &DAG = DCI.DAG; 8787 8788 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8789 // bits are demanded. N will be added to the Worklist if it was not deleted. 8790 // Caller should return SDValue(N, 0) if this returns true. 8791 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8792 SDValue Op = N->getOperand(OpNo); 8793 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8794 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8795 return false; 8796 8797 if (N->getOpcode() != ISD::DELETED_NODE) 8798 DCI.AddToWorklist(N); 8799 return true; 8800 }; 8801 8802 switch (N->getOpcode()) { 8803 default: 8804 break; 8805 case RISCVISD::SplitF64: { 8806 SDValue Op0 = N->getOperand(0); 8807 // If the input to SplitF64 is just BuildPairF64 then the operation is 8808 // redundant. Instead, use BuildPairF64's operands directly. 8809 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8810 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8811 8812 if (Op0->isUndef()) { 8813 SDValue Lo = DAG.getUNDEF(MVT::i32); 8814 SDValue Hi = DAG.getUNDEF(MVT::i32); 8815 return DCI.CombineTo(N, Lo, Hi); 8816 } 8817 8818 SDLoc DL(N); 8819 8820 // It's cheaper to materialise two 32-bit integers than to load a double 8821 // from the constant pool and transfer it to integer registers through the 8822 // stack. 8823 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8824 APInt V = C->getValueAPF().bitcastToAPInt(); 8825 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8826 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8827 return DCI.CombineTo(N, Lo, Hi); 8828 } 8829 8830 // This is a target-specific version of a DAGCombine performed in 8831 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8832 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8833 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8834 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8835 !Op0.getNode()->hasOneUse()) 8836 break; 8837 SDValue NewSplitF64 = 8838 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8839 Op0.getOperand(0)); 8840 SDValue Lo = NewSplitF64.getValue(0); 8841 SDValue Hi = NewSplitF64.getValue(1); 8842 APInt SignBit = APInt::getSignMask(32); 8843 if (Op0.getOpcode() == ISD::FNEG) { 8844 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8845 DAG.getConstant(SignBit, DL, MVT::i32)); 8846 return DCI.CombineTo(N, Lo, NewHi); 8847 } 8848 assert(Op0.getOpcode() == ISD::FABS); 8849 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8850 DAG.getConstant(~SignBit, DL, MVT::i32)); 8851 return DCI.CombineTo(N, Lo, NewHi); 8852 } 8853 case RISCVISD::SLLW: 8854 case RISCVISD::SRAW: 8855 case RISCVISD::SRLW: { 8856 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8857 if (SimplifyDemandedLowBitsHelper(0, 32) || 8858 SimplifyDemandedLowBitsHelper(1, 5)) 8859 return SDValue(N, 0); 8860 8861 break; 8862 } 8863 case ISD::ROTR: 8864 case ISD::ROTL: 8865 case RISCVISD::RORW: 8866 case RISCVISD::ROLW: { 8867 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8868 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8869 if (SimplifyDemandedLowBitsHelper(0, 32) || 8870 SimplifyDemandedLowBitsHelper(1, 5)) 8871 return SDValue(N, 0); 8872 } 8873 8874 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8875 } 8876 case RISCVISD::CLZW: 8877 case RISCVISD::CTZW: { 8878 // Only the lower 32 bits of the first operand are read 8879 if (SimplifyDemandedLowBitsHelper(0, 32)) 8880 return SDValue(N, 0); 8881 break; 8882 } 8883 case RISCVISD::GREV: 8884 case RISCVISD::GORC: { 8885 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8886 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8887 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8888 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8889 return SDValue(N, 0); 8890 8891 return combineGREVI_GORCI(N, DAG); 8892 } 8893 case RISCVISD::GREVW: 8894 case RISCVISD::GORCW: { 8895 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8896 if (SimplifyDemandedLowBitsHelper(0, 32) || 8897 SimplifyDemandedLowBitsHelper(1, 5)) 8898 return SDValue(N, 0); 8899 8900 break; 8901 } 8902 case RISCVISD::SHFL: 8903 case RISCVISD::UNSHFL: { 8904 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8905 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8906 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8907 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8908 return SDValue(N, 0); 8909 8910 break; 8911 } 8912 case RISCVISD::SHFLW: 8913 case RISCVISD::UNSHFLW: { 8914 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8915 if (SimplifyDemandedLowBitsHelper(0, 32) || 8916 SimplifyDemandedLowBitsHelper(1, 4)) 8917 return SDValue(N, 0); 8918 8919 break; 8920 } 8921 case RISCVISD::BCOMPRESSW: 8922 case RISCVISD::BDECOMPRESSW: { 8923 // Only the lower 32 bits of LHS and RHS are read. 8924 if (SimplifyDemandedLowBitsHelper(0, 32) || 8925 SimplifyDemandedLowBitsHelper(1, 32)) 8926 return SDValue(N, 0); 8927 8928 break; 8929 } 8930 case RISCVISD::FSR: 8931 case RISCVISD::FSL: 8932 case RISCVISD::FSRW: 8933 case RISCVISD::FSLW: { 8934 bool IsWInstruction = 8935 N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW; 8936 unsigned BitWidth = 8937 IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits(); 8938 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8939 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 8940 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1)) 8941 return SDValue(N, 0); 8942 8943 break; 8944 } 8945 case RISCVISD::FMV_X_ANYEXTH: 8946 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8947 SDLoc DL(N); 8948 SDValue Op0 = N->getOperand(0); 8949 MVT VT = N->getSimpleValueType(0); 8950 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8951 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8952 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8953 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8954 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8955 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8956 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8957 assert(Op0.getOperand(0).getValueType() == VT && 8958 "Unexpected value type!"); 8959 return Op0.getOperand(0); 8960 } 8961 8962 // This is a target-specific version of a DAGCombine performed in 8963 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8964 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8965 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8966 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8967 !Op0.getNode()->hasOneUse()) 8968 break; 8969 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8970 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8971 APInt SignBit = APInt::getSignMask(FPBits).sext(VT.getSizeInBits()); 8972 if (Op0.getOpcode() == ISD::FNEG) 8973 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8974 DAG.getConstant(SignBit, DL, VT)); 8975 8976 assert(Op0.getOpcode() == ISD::FABS); 8977 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8978 DAG.getConstant(~SignBit, DL, VT)); 8979 } 8980 case ISD::ADD: 8981 return performADDCombine(N, DAG, Subtarget); 8982 case ISD::SUB: 8983 return performSUBCombine(N, DAG); 8984 case ISD::AND: 8985 return performANDCombine(N, DAG, Subtarget); 8986 case ISD::OR: 8987 return performORCombine(N, DAG, Subtarget); 8988 case ISD::XOR: 8989 return performXORCombine(N, DAG); 8990 case ISD::FADD: 8991 case ISD::UMAX: 8992 case ISD::UMIN: 8993 case ISD::SMAX: 8994 case ISD::SMIN: 8995 case ISD::FMAXNUM: 8996 case ISD::FMINNUM: 8997 return combineBinOpToReduce(N, DAG); 8998 case ISD::SETCC: 8999 return performSETCCCombine(N, DAG, Subtarget); 9000 case ISD::SIGN_EXTEND_INREG: 9001 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 9002 case ISD::ZERO_EXTEND: 9003 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 9004 // type legalization. This is safe because fp_to_uint produces poison if 9005 // it overflows. 9006 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 9007 SDValue Src = N->getOperand(0); 9008 if (Src.getOpcode() == ISD::FP_TO_UINT && 9009 isTypeLegal(Src.getOperand(0).getValueType())) 9010 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 9011 Src.getOperand(0)); 9012 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 9013 isTypeLegal(Src.getOperand(1).getValueType())) { 9014 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 9015 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 9016 Src.getOperand(0), Src.getOperand(1)); 9017 DCI.CombineTo(N, Res); 9018 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 9019 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 9020 return SDValue(N, 0); // Return N so it doesn't get rechecked. 9021 } 9022 } 9023 return SDValue(); 9024 case RISCVISD::SELECT_CC: { 9025 // Transform 9026 SDValue LHS = N->getOperand(0); 9027 SDValue RHS = N->getOperand(1); 9028 SDValue CC = N->getOperand(2); 9029 SDValue TrueV = N->getOperand(3); 9030 SDValue FalseV = N->getOperand(4); 9031 SDLoc DL(N); 9032 9033 // If the True and False values are the same, we don't need a select_cc. 9034 if (TrueV == FalseV) 9035 return TrueV; 9036 9037 if (combine_CC(LHS, RHS, CC, DL, DAG, Subtarget)) 9038 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 9039 {LHS, RHS, CC, TrueV, FalseV}); 9040 9041 return SDValue(); 9042 } 9043 case RISCVISD::BR_CC: { 9044 SDValue LHS = N->getOperand(1); 9045 SDValue RHS = N->getOperand(2); 9046 SDValue CC = N->getOperand(3); 9047 SDLoc DL(N); 9048 9049 if (combine_CC(LHS, RHS, CC, DL, DAG, Subtarget)) 9050 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 9051 N->getOperand(0), LHS, RHS, CC, N->getOperand(4)); 9052 9053 return SDValue(); 9054 } 9055 case ISD::BITREVERSE: 9056 return performBITREVERSECombine(N, DAG, Subtarget); 9057 case ISD::FP_TO_SINT: 9058 case ISD::FP_TO_UINT: 9059 return performFP_TO_INTCombine(N, DCI, Subtarget); 9060 case ISD::FP_TO_SINT_SAT: 9061 case ISD::FP_TO_UINT_SAT: 9062 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 9063 case ISD::FCOPYSIGN: { 9064 EVT VT = N->getValueType(0); 9065 if (!VT.isVector()) 9066 break; 9067 // There is a form of VFSGNJ which injects the negated sign of its second 9068 // operand. Try and bubble any FNEG up after the extend/round to produce 9069 // this optimized pattern. Avoid modifying cases where FP_ROUND and 9070 // TRUNC=1. 9071 SDValue In2 = N->getOperand(1); 9072 // Avoid cases where the extend/round has multiple uses, as duplicating 9073 // those is typically more expensive than removing a fneg. 9074 if (!In2.hasOneUse()) 9075 break; 9076 if (In2.getOpcode() != ISD::FP_EXTEND && 9077 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 9078 break; 9079 In2 = In2.getOperand(0); 9080 if (In2.getOpcode() != ISD::FNEG) 9081 break; 9082 SDLoc DL(N); 9083 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 9084 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 9085 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 9086 } 9087 case ISD::MGATHER: 9088 case ISD::MSCATTER: 9089 case ISD::VP_GATHER: 9090 case ISD::VP_SCATTER: { 9091 if (!DCI.isBeforeLegalize()) 9092 break; 9093 SDValue Index, ScaleOp; 9094 bool IsIndexScaled = false; 9095 bool IsIndexSigned = false; 9096 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 9097 Index = VPGSN->getIndex(); 9098 ScaleOp = VPGSN->getScale(); 9099 IsIndexScaled = VPGSN->isIndexScaled(); 9100 IsIndexSigned = VPGSN->isIndexSigned(); 9101 } else { 9102 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 9103 Index = MGSN->getIndex(); 9104 ScaleOp = MGSN->getScale(); 9105 IsIndexScaled = MGSN->isIndexScaled(); 9106 IsIndexSigned = MGSN->isIndexSigned(); 9107 } 9108 EVT IndexVT = Index.getValueType(); 9109 MVT XLenVT = Subtarget.getXLenVT(); 9110 // RISCV indexed loads only support the "unsigned unscaled" addressing 9111 // mode, so anything else must be manually legalized. 9112 bool NeedsIdxLegalization = 9113 IsIndexScaled || 9114 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 9115 if (!NeedsIdxLegalization) 9116 break; 9117 9118 SDLoc DL(N); 9119 9120 // Any index legalization should first promote to XLenVT, so we don't lose 9121 // bits when scaling. This may create an illegal index type so we let 9122 // LLVM's legalization take care of the splitting. 9123 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 9124 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 9125 IndexVT = IndexVT.changeVectorElementType(XLenVT); 9126 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 9127 DL, IndexVT, Index); 9128 } 9129 9130 if (IsIndexScaled) { 9131 // Manually scale the indices. 9132 // TODO: Sanitize the scale operand here? 9133 // TODO: For VP nodes, should we use VP_SHL here? 9134 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 9135 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 9136 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 9137 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 9138 ScaleOp = DAG.getTargetConstant(1, DL, ScaleOp.getValueType()); 9139 } 9140 9141 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_SCALED; 9142 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 9143 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 9144 {VPGN->getChain(), VPGN->getBasePtr(), Index, 9145 ScaleOp, VPGN->getMask(), 9146 VPGN->getVectorLength()}, 9147 VPGN->getMemOperand(), NewIndexTy); 9148 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 9149 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 9150 {VPSN->getChain(), VPSN->getValue(), 9151 VPSN->getBasePtr(), Index, ScaleOp, 9152 VPSN->getMask(), VPSN->getVectorLength()}, 9153 VPSN->getMemOperand(), NewIndexTy); 9154 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 9155 return DAG.getMaskedGather( 9156 N->getVTList(), MGN->getMemoryVT(), DL, 9157 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 9158 MGN->getBasePtr(), Index, ScaleOp}, 9159 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 9160 const auto *MSN = cast<MaskedScatterSDNode>(N); 9161 return DAG.getMaskedScatter( 9162 N->getVTList(), MSN->getMemoryVT(), DL, 9163 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 9164 Index, ScaleOp}, 9165 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 9166 } 9167 case RISCVISD::SRA_VL: 9168 case RISCVISD::SRL_VL: 9169 case RISCVISD::SHL_VL: { 9170 SDValue ShAmt = N->getOperand(1); 9171 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 9172 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 9173 SDLoc DL(N); 9174 SDValue VL = N->getOperand(3); 9175 EVT VT = N->getValueType(0); 9176 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 9177 ShAmt.getOperand(1), VL); 9178 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 9179 N->getOperand(2), N->getOperand(3)); 9180 } 9181 break; 9182 } 9183 case ISD::SRA: 9184 if (SDValue V = performSRACombine(N, DAG, Subtarget)) 9185 return V; 9186 LLVM_FALLTHROUGH; 9187 case ISD::SRL: 9188 case ISD::SHL: { 9189 SDValue ShAmt = N->getOperand(1); 9190 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 9191 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 9192 SDLoc DL(N); 9193 EVT VT = N->getValueType(0); 9194 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 9195 ShAmt.getOperand(1), 9196 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 9197 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 9198 } 9199 break; 9200 } 9201 case RISCVISD::ADD_VL: 9202 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 9203 return V; 9204 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 9205 case RISCVISD::SUB_VL: 9206 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 9207 case RISCVISD::VWADD_W_VL: 9208 case RISCVISD::VWADDU_W_VL: 9209 case RISCVISD::VWSUB_W_VL: 9210 case RISCVISD::VWSUBU_W_VL: 9211 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 9212 case RISCVISD::MUL_VL: 9213 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 9214 return V; 9215 // Mul is commutative. 9216 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 9217 case RISCVISD::VFMADD_VL: 9218 case RISCVISD::VFNMADD_VL: 9219 case RISCVISD::VFMSUB_VL: 9220 case RISCVISD::VFNMSUB_VL: { 9221 // Fold FNEG_VL into FMA opcodes. 9222 SDValue A = N->getOperand(0); 9223 SDValue B = N->getOperand(1); 9224 SDValue C = N->getOperand(2); 9225 SDValue Mask = N->getOperand(3); 9226 SDValue VL = N->getOperand(4); 9227 9228 auto invertIfNegative = [&Mask, &VL](SDValue &V) { 9229 if (V.getOpcode() == RISCVISD::FNEG_VL && V.getOperand(1) == Mask && 9230 V.getOperand(2) == VL) { 9231 // Return the negated input. 9232 V = V.getOperand(0); 9233 return true; 9234 } 9235 9236 return false; 9237 }; 9238 9239 bool NegA = invertIfNegative(A); 9240 bool NegB = invertIfNegative(B); 9241 bool NegC = invertIfNegative(C); 9242 9243 // If no operands are negated, we're done. 9244 if (!NegA && !NegB && !NegC) 9245 return SDValue(); 9246 9247 unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC); 9248 return DAG.getNode(NewOpcode, SDLoc(N), N->getValueType(0), A, B, C, Mask, 9249 VL); 9250 } 9251 case ISD::STORE: { 9252 auto *Store = cast<StoreSDNode>(N); 9253 SDValue Val = Store->getValue(); 9254 // Combine store of vmv.x.s to vse with VL of 1. 9255 // FIXME: Support FP. 9256 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 9257 SDValue Src = Val.getOperand(0); 9258 MVT VecVT = Src.getSimpleValueType(); 9259 EVT MemVT = Store->getMemoryVT(); 9260 // The memory VT and the element type must match. 9261 if (MemVT == VecVT.getVectorElementType()) { 9262 SDLoc DL(N); 9263 MVT MaskVT = getMaskTypeFor(VecVT); 9264 return DAG.getStoreVP( 9265 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 9266 DAG.getConstant(1, DL, MaskVT), 9267 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 9268 Store->getMemOperand(), Store->getAddressingMode(), 9269 Store->isTruncatingStore(), /*IsCompress*/ false); 9270 } 9271 } 9272 9273 break; 9274 } 9275 case ISD::SPLAT_VECTOR: { 9276 EVT VT = N->getValueType(0); 9277 // Only perform this combine on legal MVT types. 9278 if (!isTypeLegal(VT)) 9279 break; 9280 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 9281 DAG, Subtarget)) 9282 return Gather; 9283 break; 9284 } 9285 case RISCVISD::VMV_V_X_VL: { 9286 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 9287 // scalar input. 9288 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 9289 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 9290 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 9291 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 9292 return SDValue(N, 0); 9293 9294 break; 9295 } 9296 case ISD::INTRINSIC_WO_CHAIN: { 9297 unsigned IntNo = N->getConstantOperandVal(0); 9298 switch (IntNo) { 9299 // By default we do not combine any intrinsic. 9300 default: 9301 return SDValue(); 9302 case Intrinsic::riscv_vcpop: 9303 case Intrinsic::riscv_vcpop_mask: 9304 case Intrinsic::riscv_vfirst: 9305 case Intrinsic::riscv_vfirst_mask: { 9306 SDValue VL = N->getOperand(2); 9307 if (IntNo == Intrinsic::riscv_vcpop_mask || 9308 IntNo == Intrinsic::riscv_vfirst_mask) 9309 VL = N->getOperand(3); 9310 if (!isNullConstant(VL)) 9311 return SDValue(); 9312 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 9313 SDLoc DL(N); 9314 EVT VT = N->getValueType(0); 9315 if (IntNo == Intrinsic::riscv_vfirst || 9316 IntNo == Intrinsic::riscv_vfirst_mask) 9317 return DAG.getConstant(-1, DL, VT); 9318 return DAG.getConstant(0, DL, VT); 9319 } 9320 } 9321 } 9322 case ISD::BITCAST: { 9323 assert(Subtarget.useRVVForFixedLengthVectors()); 9324 SDValue N0 = N->getOperand(0); 9325 EVT VT = N->getValueType(0); 9326 EVT SrcVT = N0.getValueType(); 9327 // If this is a bitcast between a MVT::v4i1/v2i1/v1i1 and an illegal integer 9328 // type, widen both sides to avoid a trip through memory. 9329 if ((SrcVT == MVT::v1i1 || SrcVT == MVT::v2i1 || SrcVT == MVT::v4i1) && 9330 VT.isScalarInteger()) { 9331 unsigned NumConcats = 8 / SrcVT.getVectorNumElements(); 9332 SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT)); 9333 Ops[0] = N0; 9334 SDLoc DL(N); 9335 N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i1, Ops); 9336 N0 = DAG.getBitcast(MVT::i8, N0); 9337 return DAG.getNode(ISD::TRUNCATE, DL, VT, N0); 9338 } 9339 9340 return SDValue(); 9341 } 9342 } 9343 9344 return SDValue(); 9345 } 9346 9347 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 9348 const SDNode *N, CombineLevel Level) const { 9349 assert((N->getOpcode() == ISD::SHL || N->getOpcode() == ISD::SRA || 9350 N->getOpcode() == ISD::SRL) && 9351 "Expected shift op"); 9352 9353 // The following folds are only desirable if `(OP _, c1 << c2)` can be 9354 // materialised in fewer instructions than `(OP _, c1)`: 9355 // 9356 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 9357 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 9358 SDValue N0 = N->getOperand(0); 9359 EVT Ty = N0.getValueType(); 9360 if (Ty.isScalarInteger() && 9361 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 9362 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 9363 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9364 if (C1 && C2) { 9365 const APInt &C1Int = C1->getAPIntValue(); 9366 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 9367 9368 // We can materialise `c1 << c2` into an add immediate, so it's "free", 9369 // and the combine should happen, to potentially allow further combines 9370 // later. 9371 if (ShiftedC1Int.getMinSignedBits() <= 64 && 9372 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 9373 return true; 9374 9375 // We can materialise `c1` in an add immediate, so it's "free", and the 9376 // combine should be prevented. 9377 if (C1Int.getMinSignedBits() <= 64 && 9378 isLegalAddImmediate(C1Int.getSExtValue())) 9379 return false; 9380 9381 // Neither constant will fit into an immediate, so find materialisation 9382 // costs. 9383 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 9384 Subtarget.getFeatureBits(), 9385 /*CompressionCost*/true); 9386 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 9387 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 9388 /*CompressionCost*/true); 9389 9390 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 9391 // combine should be prevented. 9392 if (C1Cost < ShiftedC1Cost) 9393 return false; 9394 } 9395 } 9396 return true; 9397 } 9398 9399 bool RISCVTargetLowering::targetShrinkDemandedConstant( 9400 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 9401 TargetLoweringOpt &TLO) const { 9402 // Delay this optimization as late as possible. 9403 if (!TLO.LegalOps) 9404 return false; 9405 9406 EVT VT = Op.getValueType(); 9407 if (VT.isVector()) 9408 return false; 9409 9410 // Only handle AND for now. 9411 unsigned Opcode = Op.getOpcode(); 9412 if (Opcode != ISD::AND && Opcode != ISD::OR && Opcode != ISD::XOR) 9413 return false; 9414 9415 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 9416 if (!C) 9417 return false; 9418 9419 const APInt &Mask = C->getAPIntValue(); 9420 9421 // Clear all non-demanded bits initially. 9422 APInt ShrunkMask = Mask & DemandedBits; 9423 9424 // Try to make a smaller immediate by setting undemanded bits. 9425 9426 APInt ExpandedMask = Mask | ~DemandedBits; 9427 9428 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 9429 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 9430 }; 9431 auto UseMask = [Mask, Op, &TLO](const APInt &NewMask) -> bool { 9432 if (NewMask == Mask) 9433 return true; 9434 SDLoc DL(Op); 9435 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, Op.getValueType()); 9436 SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), DL, Op.getValueType(), 9437 Op.getOperand(0), NewC); 9438 return TLO.CombineTo(Op, NewOp); 9439 }; 9440 9441 // If the shrunk mask fits in sign extended 12 bits, let the target 9442 // independent code apply it. 9443 if (ShrunkMask.isSignedIntN(12)) 9444 return false; 9445 9446 // And has a few special cases for zext. 9447 if (Opcode == ISD::AND) { 9448 // Preserve (and X, 0xffff) when zext.h is supported. 9449 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 9450 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 9451 if (IsLegalMask(NewMask)) 9452 return UseMask(NewMask); 9453 } 9454 9455 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 9456 if (VT == MVT::i64) { 9457 APInt NewMask = APInt(64, 0xffffffff); 9458 if (IsLegalMask(NewMask)) 9459 return UseMask(NewMask); 9460 } 9461 } 9462 9463 // For the remaining optimizations, we need to be able to make a negative 9464 // number through a combination of mask and undemanded bits. 9465 if (!ExpandedMask.isNegative()) 9466 return false; 9467 9468 // What is the fewest number of bits we need to represent the negative number. 9469 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 9470 9471 // Try to make a 12 bit negative immediate. If that fails try to make a 32 9472 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 9473 // If we can't create a simm12, we shouldn't change opaque constants. 9474 APInt NewMask = ShrunkMask; 9475 if (MinSignedBits <= 12) 9476 NewMask.setBitsFrom(11); 9477 else if (!C->isOpaque() && MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 9478 NewMask.setBitsFrom(31); 9479 else 9480 return false; 9481 9482 // Check that our new mask is a subset of the demanded mask. 9483 assert(IsLegalMask(NewMask)); 9484 return UseMask(NewMask); 9485 } 9486 9487 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) { 9488 static const uint64_t GREVMasks[] = { 9489 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 9490 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 9491 9492 for (unsigned Stage = 0; Stage != 6; ++Stage) { 9493 unsigned Shift = 1 << Stage; 9494 if (ShAmt & Shift) { 9495 uint64_t Mask = GREVMasks[Stage]; 9496 uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask); 9497 if (IsGORC) 9498 Res |= x; 9499 x = Res; 9500 } 9501 } 9502 9503 return x; 9504 } 9505 9506 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 9507 KnownBits &Known, 9508 const APInt &DemandedElts, 9509 const SelectionDAG &DAG, 9510 unsigned Depth) const { 9511 unsigned BitWidth = Known.getBitWidth(); 9512 unsigned Opc = Op.getOpcode(); 9513 assert((Opc >= ISD::BUILTIN_OP_END || 9514 Opc == ISD::INTRINSIC_WO_CHAIN || 9515 Opc == ISD::INTRINSIC_W_CHAIN || 9516 Opc == ISD::INTRINSIC_VOID) && 9517 "Should use MaskedValueIsZero if you don't know whether Op" 9518 " is a target node!"); 9519 9520 Known.resetAll(); 9521 switch (Opc) { 9522 default: break; 9523 case RISCVISD::SELECT_CC: { 9524 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 9525 // If we don't know any bits, early out. 9526 if (Known.isUnknown()) 9527 break; 9528 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 9529 9530 // Only known if known in both the LHS and RHS. 9531 Known = KnownBits::commonBits(Known, Known2); 9532 break; 9533 } 9534 case RISCVISD::REMUW: { 9535 KnownBits Known2; 9536 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9537 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9538 // We only care about the lower 32 bits. 9539 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 9540 // Restore the original width by sign extending. 9541 Known = Known.sext(BitWidth); 9542 break; 9543 } 9544 case RISCVISD::DIVUW: { 9545 KnownBits Known2; 9546 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9547 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9548 // We only care about the lower 32 bits. 9549 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 9550 // Restore the original width by sign extending. 9551 Known = Known.sext(BitWidth); 9552 break; 9553 } 9554 case RISCVISD::CTZW: { 9555 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9556 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 9557 unsigned LowBits = Log2_32(PossibleTZ) + 1; 9558 Known.Zero.setBitsFrom(LowBits); 9559 break; 9560 } 9561 case RISCVISD::CLZW: { 9562 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9563 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 9564 unsigned LowBits = Log2_32(PossibleLZ) + 1; 9565 Known.Zero.setBitsFrom(LowBits); 9566 break; 9567 } 9568 case RISCVISD::GREV: 9569 case RISCVISD::GORC: { 9570 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 9571 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9572 unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1); 9573 bool IsGORC = Op.getOpcode() == RISCVISD::GORC; 9574 // To compute zeros, we need to invert the value and invert it back after. 9575 Known.Zero = 9576 ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC); 9577 Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC); 9578 } 9579 break; 9580 } 9581 case RISCVISD::READ_VLENB: { 9582 // We can use the minimum and maximum VLEN values to bound VLENB. We 9583 // know VLEN must be a power of two. 9584 const unsigned MinVLenB = Subtarget.getRealMinVLen() / 8; 9585 const unsigned MaxVLenB = Subtarget.getRealMaxVLen() / 8; 9586 assert(MinVLenB > 0 && "READ_VLENB without vector extension enabled?"); 9587 Known.Zero.setLowBits(Log2_32(MinVLenB)); 9588 Known.Zero.setBitsFrom(Log2_32(MaxVLenB)+1); 9589 if (MaxVLenB == MinVLenB) 9590 Known.One.setBit(Log2_32(MinVLenB)); 9591 break; 9592 } 9593 case ISD::INTRINSIC_W_CHAIN: 9594 case ISD::INTRINSIC_WO_CHAIN: { 9595 unsigned IntNo = 9596 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 9597 switch (IntNo) { 9598 default: 9599 // We can't do anything for most intrinsics. 9600 break; 9601 case Intrinsic::riscv_vsetvli: 9602 case Intrinsic::riscv_vsetvlimax: 9603 case Intrinsic::riscv_vsetvli_opt: 9604 case Intrinsic::riscv_vsetvlimax_opt: 9605 // Assume that VL output is positive and would fit in an int32_t. 9606 // TODO: VLEN might be capped at 16 bits in a future V spec update. 9607 if (BitWidth >= 32) 9608 Known.Zero.setBitsFrom(31); 9609 break; 9610 } 9611 break; 9612 } 9613 } 9614 } 9615 9616 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 9617 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 9618 unsigned Depth) const { 9619 switch (Op.getOpcode()) { 9620 default: 9621 break; 9622 case RISCVISD::SELECT_CC: { 9623 unsigned Tmp = 9624 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 9625 if (Tmp == 1) return 1; // Early out. 9626 unsigned Tmp2 = 9627 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 9628 return std::min(Tmp, Tmp2); 9629 } 9630 case RISCVISD::SLLW: 9631 case RISCVISD::SRAW: 9632 case RISCVISD::SRLW: 9633 case RISCVISD::DIVW: 9634 case RISCVISD::DIVUW: 9635 case RISCVISD::REMUW: 9636 case RISCVISD::ROLW: 9637 case RISCVISD::RORW: 9638 case RISCVISD::GREVW: 9639 case RISCVISD::GORCW: 9640 case RISCVISD::FSLW: 9641 case RISCVISD::FSRW: 9642 case RISCVISD::SHFLW: 9643 case RISCVISD::UNSHFLW: 9644 case RISCVISD::BCOMPRESSW: 9645 case RISCVISD::BDECOMPRESSW: 9646 case RISCVISD::BFPW: 9647 case RISCVISD::FCVT_W_RV64: 9648 case RISCVISD::FCVT_WU_RV64: 9649 case RISCVISD::STRICT_FCVT_W_RV64: 9650 case RISCVISD::STRICT_FCVT_WU_RV64: 9651 // TODO: As the result is sign-extended, this is conservatively correct. A 9652 // more precise answer could be calculated for SRAW depending on known 9653 // bits in the shift amount. 9654 return 33; 9655 case RISCVISD::SHFL: 9656 case RISCVISD::UNSHFL: { 9657 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 9658 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 9659 // will stay within the upper 32 bits. If there were more than 32 sign bits 9660 // before there will be at least 33 sign bits after. 9661 if (Op.getValueType() == MVT::i64 && 9662 isa<ConstantSDNode>(Op.getOperand(1)) && 9663 (Op.getConstantOperandVal(1) & 0x10) == 0) { 9664 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 9665 if (Tmp > 32) 9666 return 33; 9667 } 9668 break; 9669 } 9670 case RISCVISD::VMV_X_S: { 9671 // The number of sign bits of the scalar result is computed by obtaining the 9672 // element type of the input vector operand, subtracting its width from the 9673 // XLEN, and then adding one (sign bit within the element type). If the 9674 // element type is wider than XLen, the least-significant XLEN bits are 9675 // taken. 9676 unsigned XLen = Subtarget.getXLen(); 9677 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 9678 if (EltBits <= XLen) 9679 return XLen - EltBits + 1; 9680 break; 9681 } 9682 } 9683 9684 return 1; 9685 } 9686 9687 const Constant * 9688 RISCVTargetLowering::getTargetConstantFromLoad(LoadSDNode *Ld) const { 9689 assert(Ld && "Unexpected null LoadSDNode"); 9690 if (!ISD::isNormalLoad(Ld)) 9691 return nullptr; 9692 9693 SDValue Ptr = Ld->getBasePtr(); 9694 9695 // Only constant pools with no offset are supported. 9696 auto GetSupportedConstantPool = [](SDValue Ptr) -> ConstantPoolSDNode * { 9697 auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr); 9698 if (!CNode || CNode->isMachineConstantPoolEntry() || 9699 CNode->getOffset() != 0) 9700 return nullptr; 9701 9702 return CNode; 9703 }; 9704 9705 // Simple case, LLA. 9706 if (Ptr.getOpcode() == RISCVISD::LLA) { 9707 auto *CNode = GetSupportedConstantPool(Ptr); 9708 if (!CNode || CNode->getTargetFlags() != 0) 9709 return nullptr; 9710 9711 return CNode->getConstVal(); 9712 } 9713 9714 // Look for a HI and ADD_LO pair. 9715 if (Ptr.getOpcode() != RISCVISD::ADD_LO || 9716 Ptr.getOperand(0).getOpcode() != RISCVISD::HI) 9717 return nullptr; 9718 9719 auto *CNodeLo = GetSupportedConstantPool(Ptr.getOperand(1)); 9720 auto *CNodeHi = GetSupportedConstantPool(Ptr.getOperand(0).getOperand(0)); 9721 9722 if (!CNodeLo || CNodeLo->getTargetFlags() != RISCVII::MO_LO || 9723 !CNodeHi || CNodeHi->getTargetFlags() != RISCVII::MO_HI) 9724 return nullptr; 9725 9726 if (CNodeLo->getConstVal() != CNodeHi->getConstVal()) 9727 return nullptr; 9728 9729 return CNodeLo->getConstVal(); 9730 } 9731 9732 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 9733 MachineBasicBlock *BB) { 9734 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 9735 9736 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 9737 // Should the count have wrapped while it was being read, we need to try 9738 // again. 9739 // ... 9740 // read: 9741 // rdcycleh x3 # load high word of cycle 9742 // rdcycle x2 # load low word of cycle 9743 // rdcycleh x4 # load high word of cycle 9744 // bne x3, x4, read # check if high word reads match, otherwise try again 9745 // ... 9746 9747 MachineFunction &MF = *BB->getParent(); 9748 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9749 MachineFunction::iterator It = ++BB->getIterator(); 9750 9751 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9752 MF.insert(It, LoopMBB); 9753 9754 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9755 MF.insert(It, DoneMBB); 9756 9757 // Transfer the remainder of BB and its successor edges to DoneMBB. 9758 DoneMBB->splice(DoneMBB->begin(), BB, 9759 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9760 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 9761 9762 BB->addSuccessor(LoopMBB); 9763 9764 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9765 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9766 Register LoReg = MI.getOperand(0).getReg(); 9767 Register HiReg = MI.getOperand(1).getReg(); 9768 DebugLoc DL = MI.getDebugLoc(); 9769 9770 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 9771 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 9772 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9773 .addReg(RISCV::X0); 9774 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 9775 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 9776 .addReg(RISCV::X0); 9777 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 9778 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9779 .addReg(RISCV::X0); 9780 9781 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 9782 .addReg(HiReg) 9783 .addReg(ReadAgainReg) 9784 .addMBB(LoopMBB); 9785 9786 LoopMBB->addSuccessor(LoopMBB); 9787 LoopMBB->addSuccessor(DoneMBB); 9788 9789 MI.eraseFromParent(); 9790 9791 return DoneMBB; 9792 } 9793 9794 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9795 MachineBasicBlock *BB) { 9796 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9797 9798 MachineFunction &MF = *BB->getParent(); 9799 DebugLoc DL = MI.getDebugLoc(); 9800 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9801 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9802 Register LoReg = MI.getOperand(0).getReg(); 9803 Register HiReg = MI.getOperand(1).getReg(); 9804 Register SrcReg = MI.getOperand(2).getReg(); 9805 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9806 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9807 9808 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9809 RI); 9810 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9811 MachineMemOperand *MMOLo = 9812 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9813 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9814 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9815 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9816 .addFrameIndex(FI) 9817 .addImm(0) 9818 .addMemOperand(MMOLo); 9819 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9820 .addFrameIndex(FI) 9821 .addImm(4) 9822 .addMemOperand(MMOHi); 9823 MI.eraseFromParent(); // The pseudo instruction is gone now. 9824 return BB; 9825 } 9826 9827 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9828 MachineBasicBlock *BB) { 9829 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9830 "Unexpected instruction"); 9831 9832 MachineFunction &MF = *BB->getParent(); 9833 DebugLoc DL = MI.getDebugLoc(); 9834 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9835 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9836 Register DstReg = MI.getOperand(0).getReg(); 9837 Register LoReg = MI.getOperand(1).getReg(); 9838 Register HiReg = MI.getOperand(2).getReg(); 9839 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9840 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9841 9842 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9843 MachineMemOperand *MMOLo = 9844 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9845 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9846 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9847 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9848 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9849 .addFrameIndex(FI) 9850 .addImm(0) 9851 .addMemOperand(MMOLo); 9852 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9853 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9854 .addFrameIndex(FI) 9855 .addImm(4) 9856 .addMemOperand(MMOHi); 9857 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9858 MI.eraseFromParent(); // The pseudo instruction is gone now. 9859 return BB; 9860 } 9861 9862 static bool isSelectPseudo(MachineInstr &MI) { 9863 switch (MI.getOpcode()) { 9864 default: 9865 return false; 9866 case RISCV::Select_GPR_Using_CC_GPR: 9867 case RISCV::Select_FPR16_Using_CC_GPR: 9868 case RISCV::Select_FPR32_Using_CC_GPR: 9869 case RISCV::Select_FPR64_Using_CC_GPR: 9870 return true; 9871 } 9872 } 9873 9874 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9875 unsigned RelOpcode, unsigned EqOpcode, 9876 const RISCVSubtarget &Subtarget) { 9877 DebugLoc DL = MI.getDebugLoc(); 9878 Register DstReg = MI.getOperand(0).getReg(); 9879 Register Src1Reg = MI.getOperand(1).getReg(); 9880 Register Src2Reg = MI.getOperand(2).getReg(); 9881 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9882 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9883 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9884 9885 // Save the current FFLAGS. 9886 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9887 9888 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9889 .addReg(Src1Reg) 9890 .addReg(Src2Reg); 9891 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9892 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9893 9894 // Restore the FFLAGS. 9895 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9896 .addReg(SavedFFlags, RegState::Kill); 9897 9898 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9899 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9900 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9901 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9902 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9903 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9904 9905 // Erase the pseudoinstruction. 9906 MI.eraseFromParent(); 9907 return BB; 9908 } 9909 9910 static MachineBasicBlock * 9911 EmitLoweredCascadedSelect(MachineInstr &First, MachineInstr &Second, 9912 MachineBasicBlock *ThisMBB, 9913 const RISCVSubtarget &Subtarget) { 9914 // Select_FPRX_ (rs1, rs2, imm, rs4, (Select_FPRX_ rs1, rs2, imm, rs4, rs5) 9915 // Without this, custom-inserter would have generated: 9916 // 9917 // A 9918 // | \ 9919 // | B 9920 // | / 9921 // C 9922 // | \ 9923 // | D 9924 // | / 9925 // E 9926 // 9927 // A: X = ...; Y = ... 9928 // B: empty 9929 // C: Z = PHI [X, A], [Y, B] 9930 // D: empty 9931 // E: PHI [X, C], [Z, D] 9932 // 9933 // If we lower both Select_FPRX_ in a single step, we can instead generate: 9934 // 9935 // A 9936 // | \ 9937 // | C 9938 // | /| 9939 // |/ | 9940 // | | 9941 // | D 9942 // | / 9943 // E 9944 // 9945 // A: X = ...; Y = ... 9946 // D: empty 9947 // E: PHI [X, A], [X, C], [Y, D] 9948 9949 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9950 const DebugLoc &DL = First.getDebugLoc(); 9951 const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock(); 9952 MachineFunction *F = ThisMBB->getParent(); 9953 MachineBasicBlock *FirstMBB = F->CreateMachineBasicBlock(LLVM_BB); 9954 MachineBasicBlock *SecondMBB = F->CreateMachineBasicBlock(LLVM_BB); 9955 MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB); 9956 MachineFunction::iterator It = ++ThisMBB->getIterator(); 9957 F->insert(It, FirstMBB); 9958 F->insert(It, SecondMBB); 9959 F->insert(It, SinkMBB); 9960 9961 // Transfer the remainder of ThisMBB and its successor edges to SinkMBB. 9962 SinkMBB->splice(SinkMBB->begin(), ThisMBB, 9963 std::next(MachineBasicBlock::iterator(First)), 9964 ThisMBB->end()); 9965 SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB); 9966 9967 // Fallthrough block for ThisMBB. 9968 ThisMBB->addSuccessor(FirstMBB); 9969 // Fallthrough block for FirstMBB. 9970 FirstMBB->addSuccessor(SecondMBB); 9971 ThisMBB->addSuccessor(SinkMBB); 9972 FirstMBB->addSuccessor(SinkMBB); 9973 // This is fallthrough. 9974 SecondMBB->addSuccessor(SinkMBB); 9975 9976 auto FirstCC = static_cast<RISCVCC::CondCode>(First.getOperand(3).getImm()); 9977 Register FLHS = First.getOperand(1).getReg(); 9978 Register FRHS = First.getOperand(2).getReg(); 9979 // Insert appropriate branch. 9980 BuildMI(FirstMBB, DL, TII.getBrCond(FirstCC)) 9981 .addReg(FLHS) 9982 .addReg(FRHS) 9983 .addMBB(SinkMBB); 9984 9985 Register SLHS = Second.getOperand(1).getReg(); 9986 Register SRHS = Second.getOperand(2).getReg(); 9987 Register Op1Reg4 = First.getOperand(4).getReg(); 9988 Register Op1Reg5 = First.getOperand(5).getReg(); 9989 9990 auto SecondCC = static_cast<RISCVCC::CondCode>(Second.getOperand(3).getImm()); 9991 // Insert appropriate branch. 9992 BuildMI(ThisMBB, DL, TII.getBrCond(SecondCC)) 9993 .addReg(SLHS) 9994 .addReg(SRHS) 9995 .addMBB(SinkMBB); 9996 9997 Register DestReg = Second.getOperand(0).getReg(); 9998 Register Op2Reg4 = Second.getOperand(4).getReg(); 9999 BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII.get(RISCV::PHI), DestReg) 10000 .addReg(Op2Reg4) 10001 .addMBB(ThisMBB) 10002 .addReg(Op1Reg4) 10003 .addMBB(FirstMBB) 10004 .addReg(Op1Reg5) 10005 .addMBB(SecondMBB); 10006 10007 // Now remove the Select_FPRX_s. 10008 First.eraseFromParent(); 10009 Second.eraseFromParent(); 10010 return SinkMBB; 10011 } 10012 10013 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 10014 MachineBasicBlock *BB, 10015 const RISCVSubtarget &Subtarget) { 10016 // To "insert" Select_* instructions, we actually have to insert the triangle 10017 // control-flow pattern. The incoming instructions know the destination vreg 10018 // to set, the condition code register to branch on, the true/false values to 10019 // select between, and the condcode to use to select the appropriate branch. 10020 // 10021 // We produce the following control flow: 10022 // HeadMBB 10023 // | \ 10024 // | IfFalseMBB 10025 // | / 10026 // TailMBB 10027 // 10028 // When we find a sequence of selects we attempt to optimize their emission 10029 // by sharing the control flow. Currently we only handle cases where we have 10030 // multiple selects with the exact same condition (same LHS, RHS and CC). 10031 // The selects may be interleaved with other instructions if the other 10032 // instructions meet some requirements we deem safe: 10033 // - They are debug instructions. Otherwise, 10034 // - They do not have side-effects, do not access memory and their inputs do 10035 // not depend on the results of the select pseudo-instructions. 10036 // The TrueV/FalseV operands of the selects cannot depend on the result of 10037 // previous selects in the sequence. 10038 // These conditions could be further relaxed. See the X86 target for a 10039 // related approach and more information. 10040 // 10041 // Select_FPRX_ (rs1, rs2, imm, rs4, (Select_FPRX_ rs1, rs2, imm, rs4, rs5)) 10042 // is checked here and handled by a separate function - 10043 // EmitLoweredCascadedSelect. 10044 Register LHS = MI.getOperand(1).getReg(); 10045 Register RHS = MI.getOperand(2).getReg(); 10046 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 10047 10048 SmallVector<MachineInstr *, 4> SelectDebugValues; 10049 SmallSet<Register, 4> SelectDests; 10050 SelectDests.insert(MI.getOperand(0).getReg()); 10051 10052 MachineInstr *LastSelectPseudo = &MI; 10053 auto Next = next_nodbg(MI.getIterator(), BB->instr_end()); 10054 if (MI.getOpcode() != RISCV::Select_GPR_Using_CC_GPR && Next != BB->end() && 10055 Next->getOpcode() == MI.getOpcode() && 10056 Next->getOperand(5).getReg() == MI.getOperand(0).getReg() && 10057 Next->getOperand(5).isKill()) { 10058 return EmitLoweredCascadedSelect(MI, *Next, BB, Subtarget); 10059 } 10060 10061 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 10062 SequenceMBBI != E; ++SequenceMBBI) { 10063 if (SequenceMBBI->isDebugInstr()) 10064 continue; 10065 if (isSelectPseudo(*SequenceMBBI)) { 10066 if (SequenceMBBI->getOperand(1).getReg() != LHS || 10067 SequenceMBBI->getOperand(2).getReg() != RHS || 10068 SequenceMBBI->getOperand(3).getImm() != CC || 10069 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 10070 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 10071 break; 10072 LastSelectPseudo = &*SequenceMBBI; 10073 SequenceMBBI->collectDebugValues(SelectDebugValues); 10074 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 10075 continue; 10076 } 10077 if (SequenceMBBI->hasUnmodeledSideEffects() || 10078 SequenceMBBI->mayLoadOrStore()) 10079 break; 10080 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 10081 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 10082 })) 10083 break; 10084 } 10085 10086 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 10087 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 10088 DebugLoc DL = MI.getDebugLoc(); 10089 MachineFunction::iterator I = ++BB->getIterator(); 10090 10091 MachineBasicBlock *HeadMBB = BB; 10092 MachineFunction *F = BB->getParent(); 10093 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 10094 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 10095 10096 F->insert(I, IfFalseMBB); 10097 F->insert(I, TailMBB); 10098 10099 // Transfer debug instructions associated with the selects to TailMBB. 10100 for (MachineInstr *DebugInstr : SelectDebugValues) { 10101 TailMBB->push_back(DebugInstr->removeFromParent()); 10102 } 10103 10104 // Move all instructions after the sequence to TailMBB. 10105 TailMBB->splice(TailMBB->end(), HeadMBB, 10106 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 10107 // Update machine-CFG edges by transferring all successors of the current 10108 // block to the new block which will contain the Phi nodes for the selects. 10109 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 10110 // Set the successors for HeadMBB. 10111 HeadMBB->addSuccessor(IfFalseMBB); 10112 HeadMBB->addSuccessor(TailMBB); 10113 10114 // Insert appropriate branch. 10115 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 10116 .addReg(LHS) 10117 .addReg(RHS) 10118 .addMBB(TailMBB); 10119 10120 // IfFalseMBB just falls through to TailMBB. 10121 IfFalseMBB->addSuccessor(TailMBB); 10122 10123 // Create PHIs for all of the select pseudo-instructions. 10124 auto SelectMBBI = MI.getIterator(); 10125 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 10126 auto InsertionPoint = TailMBB->begin(); 10127 while (SelectMBBI != SelectEnd) { 10128 auto Next = std::next(SelectMBBI); 10129 if (isSelectPseudo(*SelectMBBI)) { 10130 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 10131 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 10132 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 10133 .addReg(SelectMBBI->getOperand(4).getReg()) 10134 .addMBB(HeadMBB) 10135 .addReg(SelectMBBI->getOperand(5).getReg()) 10136 .addMBB(IfFalseMBB); 10137 SelectMBBI->eraseFromParent(); 10138 } 10139 SelectMBBI = Next; 10140 } 10141 10142 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 10143 return TailMBB; 10144 } 10145 10146 MachineBasicBlock * 10147 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 10148 MachineBasicBlock *BB) const { 10149 switch (MI.getOpcode()) { 10150 default: 10151 llvm_unreachable("Unexpected instr type to insert"); 10152 case RISCV::ReadCycleWide: 10153 assert(!Subtarget.is64Bit() && 10154 "ReadCycleWrite is only to be used on riscv32"); 10155 return emitReadCycleWidePseudo(MI, BB); 10156 case RISCV::Select_GPR_Using_CC_GPR: 10157 case RISCV::Select_FPR16_Using_CC_GPR: 10158 case RISCV::Select_FPR32_Using_CC_GPR: 10159 case RISCV::Select_FPR64_Using_CC_GPR: 10160 return emitSelectPseudo(MI, BB, Subtarget); 10161 case RISCV::BuildPairF64Pseudo: 10162 return emitBuildPairF64Pseudo(MI, BB); 10163 case RISCV::SplitF64Pseudo: 10164 return emitSplitF64Pseudo(MI, BB); 10165 case RISCV::PseudoQuietFLE_H: 10166 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 10167 case RISCV::PseudoQuietFLT_H: 10168 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 10169 case RISCV::PseudoQuietFLE_S: 10170 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 10171 case RISCV::PseudoQuietFLT_S: 10172 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 10173 case RISCV::PseudoQuietFLE_D: 10174 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 10175 case RISCV::PseudoQuietFLT_D: 10176 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 10177 } 10178 } 10179 10180 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 10181 SDNode *Node) const { 10182 // Add FRM dependency to any instructions with dynamic rounding mode. 10183 unsigned Opc = MI.getOpcode(); 10184 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 10185 if (Idx < 0) 10186 return; 10187 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 10188 return; 10189 // If the instruction already reads FRM, don't add another read. 10190 if (MI.readsRegister(RISCV::FRM)) 10191 return; 10192 MI.addOperand( 10193 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 10194 } 10195 10196 // Calling Convention Implementation. 10197 // The expectations for frontend ABI lowering vary from target to target. 10198 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 10199 // details, but this is a longer term goal. For now, we simply try to keep the 10200 // role of the frontend as simple and well-defined as possible. The rules can 10201 // be summarised as: 10202 // * Never split up large scalar arguments. We handle them here. 10203 // * If a hardfloat calling convention is being used, and the struct may be 10204 // passed in a pair of registers (fp+fp, int+fp), and both registers are 10205 // available, then pass as two separate arguments. If either the GPRs or FPRs 10206 // are exhausted, then pass according to the rule below. 10207 // * If a struct could never be passed in registers or directly in a stack 10208 // slot (as it is larger than 2*XLEN and the floating point rules don't 10209 // apply), then pass it using a pointer with the byval attribute. 10210 // * If a struct is less than 2*XLEN, then coerce to either a two-element 10211 // word-sized array or a 2*XLEN scalar (depending on alignment). 10212 // * The frontend can determine whether a struct is returned by reference or 10213 // not based on its size and fields. If it will be returned by reference, the 10214 // frontend must modify the prototype so a pointer with the sret annotation is 10215 // passed as the first argument. This is not necessary for large scalar 10216 // returns. 10217 // * Struct return values and varargs should be coerced to structs containing 10218 // register-size fields in the same situations they would be for fixed 10219 // arguments. 10220 10221 static const MCPhysReg ArgGPRs[] = { 10222 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 10223 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 10224 }; 10225 static const MCPhysReg ArgFPR16s[] = { 10226 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 10227 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 10228 }; 10229 static const MCPhysReg ArgFPR32s[] = { 10230 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 10231 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 10232 }; 10233 static const MCPhysReg ArgFPR64s[] = { 10234 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 10235 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 10236 }; 10237 // This is an interim calling convention and it may be changed in the future. 10238 static const MCPhysReg ArgVRs[] = { 10239 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 10240 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 10241 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 10242 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 10243 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 10244 RISCV::V20M2, RISCV::V22M2}; 10245 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 10246 RISCV::V20M4}; 10247 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 10248 10249 // Pass a 2*XLEN argument that has been split into two XLEN values through 10250 // registers or the stack as necessary. 10251 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 10252 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 10253 MVT ValVT2, MVT LocVT2, 10254 ISD::ArgFlagsTy ArgFlags2) { 10255 unsigned XLenInBytes = XLen / 8; 10256 if (Register Reg = State.AllocateReg(ArgGPRs)) { 10257 // At least one half can be passed via register. 10258 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 10259 VA1.getLocVT(), CCValAssign::Full)); 10260 } else { 10261 // Both halves must be passed on the stack, with proper alignment. 10262 Align StackAlign = 10263 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 10264 State.addLoc( 10265 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 10266 State.AllocateStack(XLenInBytes, StackAlign), 10267 VA1.getLocVT(), CCValAssign::Full)); 10268 State.addLoc(CCValAssign::getMem( 10269 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 10270 LocVT2, CCValAssign::Full)); 10271 return false; 10272 } 10273 10274 if (Register Reg = State.AllocateReg(ArgGPRs)) { 10275 // The second half can also be passed via register. 10276 State.addLoc( 10277 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 10278 } else { 10279 // The second half is passed via the stack, without additional alignment. 10280 State.addLoc(CCValAssign::getMem( 10281 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 10282 LocVT2, CCValAssign::Full)); 10283 } 10284 10285 return false; 10286 } 10287 10288 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 10289 Optional<unsigned> FirstMaskArgument, 10290 CCState &State, const RISCVTargetLowering &TLI) { 10291 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 10292 if (RC == &RISCV::VRRegClass) { 10293 // Assign the first mask argument to V0. 10294 // This is an interim calling convention and it may be changed in the 10295 // future. 10296 if (FirstMaskArgument && ValNo == *FirstMaskArgument) 10297 return State.AllocateReg(RISCV::V0); 10298 return State.AllocateReg(ArgVRs); 10299 } 10300 if (RC == &RISCV::VRM2RegClass) 10301 return State.AllocateReg(ArgVRM2s); 10302 if (RC == &RISCV::VRM4RegClass) 10303 return State.AllocateReg(ArgVRM4s); 10304 if (RC == &RISCV::VRM8RegClass) 10305 return State.AllocateReg(ArgVRM8s); 10306 llvm_unreachable("Unhandled register class for ValueType"); 10307 } 10308 10309 // Implements the RISC-V calling convention. Returns true upon failure. 10310 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 10311 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 10312 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 10313 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 10314 Optional<unsigned> FirstMaskArgument) { 10315 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 10316 assert(XLen == 32 || XLen == 64); 10317 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 10318 10319 // Any return value split in to more than two values can't be returned 10320 // directly. Vectors are returned via the available vector registers. 10321 if (!LocVT.isVector() && IsRet && ValNo > 1) 10322 return true; 10323 10324 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 10325 // variadic argument, or if no F16/F32 argument registers are available. 10326 bool UseGPRForF16_F32 = true; 10327 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 10328 // variadic argument, or if no F64 argument registers are available. 10329 bool UseGPRForF64 = true; 10330 10331 switch (ABI) { 10332 default: 10333 llvm_unreachable("Unexpected ABI"); 10334 case RISCVABI::ABI_ILP32: 10335 case RISCVABI::ABI_LP64: 10336 break; 10337 case RISCVABI::ABI_ILP32F: 10338 case RISCVABI::ABI_LP64F: 10339 UseGPRForF16_F32 = !IsFixed; 10340 break; 10341 case RISCVABI::ABI_ILP32D: 10342 case RISCVABI::ABI_LP64D: 10343 UseGPRForF16_F32 = !IsFixed; 10344 UseGPRForF64 = !IsFixed; 10345 break; 10346 } 10347 10348 // FPR16, FPR32, and FPR64 alias each other. 10349 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 10350 UseGPRForF16_F32 = true; 10351 UseGPRForF64 = true; 10352 } 10353 10354 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 10355 // similar local variables rather than directly checking against the target 10356 // ABI. 10357 10358 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 10359 LocVT = XLenVT; 10360 LocInfo = CCValAssign::BCvt; 10361 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 10362 LocVT = MVT::i64; 10363 LocInfo = CCValAssign::BCvt; 10364 } 10365 10366 // If this is a variadic argument, the RISC-V calling convention requires 10367 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 10368 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 10369 // be used regardless of whether the original argument was split during 10370 // legalisation or not. The argument will not be passed by registers if the 10371 // original type is larger than 2*XLEN, so the register alignment rule does 10372 // not apply. 10373 unsigned TwoXLenInBytes = (2 * XLen) / 8; 10374 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 10375 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 10376 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 10377 // Skip 'odd' register if necessary. 10378 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 10379 State.AllocateReg(ArgGPRs); 10380 } 10381 10382 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 10383 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 10384 State.getPendingArgFlags(); 10385 10386 assert(PendingLocs.size() == PendingArgFlags.size() && 10387 "PendingLocs and PendingArgFlags out of sync"); 10388 10389 // Handle passing f64 on RV32D with a soft float ABI or when floating point 10390 // registers are exhausted. 10391 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 10392 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 10393 "Can't lower f64 if it is split"); 10394 // Depending on available argument GPRS, f64 may be passed in a pair of 10395 // GPRs, split between a GPR and the stack, or passed completely on the 10396 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 10397 // cases. 10398 Register Reg = State.AllocateReg(ArgGPRs); 10399 LocVT = MVT::i32; 10400 if (!Reg) { 10401 unsigned StackOffset = State.AllocateStack(8, Align(8)); 10402 State.addLoc( 10403 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10404 return false; 10405 } 10406 if (!State.AllocateReg(ArgGPRs)) 10407 State.AllocateStack(4, Align(4)); 10408 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10409 return false; 10410 } 10411 10412 // Fixed-length vectors are located in the corresponding scalable-vector 10413 // container types. 10414 if (ValVT.isFixedLengthVector()) 10415 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10416 10417 // Split arguments might be passed indirectly, so keep track of the pending 10418 // values. Split vectors are passed via a mix of registers and indirectly, so 10419 // treat them as we would any other argument. 10420 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 10421 LocVT = XLenVT; 10422 LocInfo = CCValAssign::Indirect; 10423 PendingLocs.push_back( 10424 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 10425 PendingArgFlags.push_back(ArgFlags); 10426 if (!ArgFlags.isSplitEnd()) { 10427 return false; 10428 } 10429 } 10430 10431 // If the split argument only had two elements, it should be passed directly 10432 // in registers or on the stack. 10433 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 10434 PendingLocs.size() <= 2) { 10435 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 10436 // Apply the normal calling convention rules to the first half of the 10437 // split argument. 10438 CCValAssign VA = PendingLocs[0]; 10439 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 10440 PendingLocs.clear(); 10441 PendingArgFlags.clear(); 10442 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 10443 ArgFlags); 10444 } 10445 10446 // Allocate to a register if possible, or else a stack slot. 10447 Register Reg; 10448 unsigned StoreSizeBytes = XLen / 8; 10449 Align StackAlign = Align(XLen / 8); 10450 10451 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 10452 Reg = State.AllocateReg(ArgFPR16s); 10453 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 10454 Reg = State.AllocateReg(ArgFPR32s); 10455 else if (ValVT == MVT::f64 && !UseGPRForF64) 10456 Reg = State.AllocateReg(ArgFPR64s); 10457 else if (ValVT.isVector()) { 10458 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 10459 if (!Reg) { 10460 // For return values, the vector must be passed fully via registers or 10461 // via the stack. 10462 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 10463 // but we're using all of them. 10464 if (IsRet) 10465 return true; 10466 // Try using a GPR to pass the address 10467 if ((Reg = State.AllocateReg(ArgGPRs))) { 10468 LocVT = XLenVT; 10469 LocInfo = CCValAssign::Indirect; 10470 } else if (ValVT.isScalableVector()) { 10471 LocVT = XLenVT; 10472 LocInfo = CCValAssign::Indirect; 10473 } else { 10474 // Pass fixed-length vectors on the stack. 10475 LocVT = ValVT; 10476 StoreSizeBytes = ValVT.getStoreSize(); 10477 // Align vectors to their element sizes, being careful for vXi1 10478 // vectors. 10479 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10480 } 10481 } 10482 } else { 10483 Reg = State.AllocateReg(ArgGPRs); 10484 } 10485 10486 unsigned StackOffset = 10487 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 10488 10489 // If we reach this point and PendingLocs is non-empty, we must be at the 10490 // end of a split argument that must be passed indirectly. 10491 if (!PendingLocs.empty()) { 10492 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 10493 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 10494 10495 for (auto &It : PendingLocs) { 10496 if (Reg) 10497 It.convertToReg(Reg); 10498 else 10499 It.convertToMem(StackOffset); 10500 State.addLoc(It); 10501 } 10502 PendingLocs.clear(); 10503 PendingArgFlags.clear(); 10504 return false; 10505 } 10506 10507 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 10508 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 10509 "Expected an XLenVT or vector types at this stage"); 10510 10511 if (Reg) { 10512 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10513 return false; 10514 } 10515 10516 // When a floating-point value is passed on the stack, no bit-conversion is 10517 // needed. 10518 if (ValVT.isFloatingPoint()) { 10519 LocVT = ValVT; 10520 LocInfo = CCValAssign::Full; 10521 } 10522 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10523 return false; 10524 } 10525 10526 template <typename ArgTy> 10527 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 10528 for (const auto &ArgIdx : enumerate(Args)) { 10529 MVT ArgVT = ArgIdx.value().VT; 10530 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 10531 return ArgIdx.index(); 10532 } 10533 return None; 10534 } 10535 10536 void RISCVTargetLowering::analyzeInputArgs( 10537 MachineFunction &MF, CCState &CCInfo, 10538 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 10539 RISCVCCAssignFn Fn) const { 10540 unsigned NumArgs = Ins.size(); 10541 FunctionType *FType = MF.getFunction().getFunctionType(); 10542 10543 Optional<unsigned> FirstMaskArgument; 10544 if (Subtarget.hasVInstructions()) 10545 FirstMaskArgument = preAssignMask(Ins); 10546 10547 for (unsigned i = 0; i != NumArgs; ++i) { 10548 MVT ArgVT = Ins[i].VT; 10549 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 10550 10551 Type *ArgTy = nullptr; 10552 if (IsRet) 10553 ArgTy = FType->getReturnType(); 10554 else if (Ins[i].isOrigArg()) 10555 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 10556 10557 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10558 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10559 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 10560 FirstMaskArgument)) { 10561 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 10562 << EVT(ArgVT).getEVTString() << '\n'); 10563 llvm_unreachable(nullptr); 10564 } 10565 } 10566 } 10567 10568 void RISCVTargetLowering::analyzeOutputArgs( 10569 MachineFunction &MF, CCState &CCInfo, 10570 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 10571 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 10572 unsigned NumArgs = Outs.size(); 10573 10574 Optional<unsigned> FirstMaskArgument; 10575 if (Subtarget.hasVInstructions()) 10576 FirstMaskArgument = preAssignMask(Outs); 10577 10578 for (unsigned i = 0; i != NumArgs; i++) { 10579 MVT ArgVT = Outs[i].VT; 10580 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10581 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 10582 10583 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10584 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10585 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 10586 FirstMaskArgument)) { 10587 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 10588 << EVT(ArgVT).getEVTString() << "\n"); 10589 llvm_unreachable(nullptr); 10590 } 10591 } 10592 } 10593 10594 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 10595 // values. 10596 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 10597 const CCValAssign &VA, const SDLoc &DL, 10598 const RISCVSubtarget &Subtarget) { 10599 switch (VA.getLocInfo()) { 10600 default: 10601 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10602 case CCValAssign::Full: 10603 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 10604 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 10605 break; 10606 case CCValAssign::BCvt: 10607 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10608 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 10609 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10610 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 10611 else 10612 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 10613 break; 10614 } 10615 return Val; 10616 } 10617 10618 // The caller is responsible for loading the full value if the argument is 10619 // passed with CCValAssign::Indirect. 10620 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 10621 const CCValAssign &VA, const SDLoc &DL, 10622 const RISCVTargetLowering &TLI) { 10623 MachineFunction &MF = DAG.getMachineFunction(); 10624 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10625 EVT LocVT = VA.getLocVT(); 10626 SDValue Val; 10627 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 10628 Register VReg = RegInfo.createVirtualRegister(RC); 10629 RegInfo.addLiveIn(VA.getLocReg(), VReg); 10630 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 10631 10632 if (VA.getLocInfo() == CCValAssign::Indirect) 10633 return Val; 10634 10635 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 10636 } 10637 10638 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 10639 const CCValAssign &VA, const SDLoc &DL, 10640 const RISCVSubtarget &Subtarget) { 10641 EVT LocVT = VA.getLocVT(); 10642 10643 switch (VA.getLocInfo()) { 10644 default: 10645 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10646 case CCValAssign::Full: 10647 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 10648 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 10649 break; 10650 case CCValAssign::BCvt: 10651 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10652 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 10653 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10654 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 10655 else 10656 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 10657 break; 10658 } 10659 return Val; 10660 } 10661 10662 // The caller is responsible for loading the full value if the argument is 10663 // passed with CCValAssign::Indirect. 10664 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 10665 const CCValAssign &VA, const SDLoc &DL) { 10666 MachineFunction &MF = DAG.getMachineFunction(); 10667 MachineFrameInfo &MFI = MF.getFrameInfo(); 10668 EVT LocVT = VA.getLocVT(); 10669 EVT ValVT = VA.getValVT(); 10670 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 10671 if (ValVT.isScalableVector()) { 10672 // When the value is a scalable vector, we save the pointer which points to 10673 // the scalable vector value in the stack. The ValVT will be the pointer 10674 // type, instead of the scalable vector type. 10675 ValVT = LocVT; 10676 } 10677 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 10678 /*IsImmutable=*/true); 10679 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 10680 SDValue Val; 10681 10682 ISD::LoadExtType ExtType; 10683 switch (VA.getLocInfo()) { 10684 default: 10685 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10686 case CCValAssign::Full: 10687 case CCValAssign::Indirect: 10688 case CCValAssign::BCvt: 10689 ExtType = ISD::NON_EXTLOAD; 10690 break; 10691 } 10692 Val = DAG.getExtLoad( 10693 ExtType, DL, LocVT, Chain, FIN, 10694 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 10695 return Val; 10696 } 10697 10698 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 10699 const CCValAssign &VA, const SDLoc &DL) { 10700 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 10701 "Unexpected VA"); 10702 MachineFunction &MF = DAG.getMachineFunction(); 10703 MachineFrameInfo &MFI = MF.getFrameInfo(); 10704 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10705 10706 if (VA.isMemLoc()) { 10707 // f64 is passed on the stack. 10708 int FI = 10709 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 10710 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10711 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 10712 MachinePointerInfo::getFixedStack(MF, FI)); 10713 } 10714 10715 assert(VA.isRegLoc() && "Expected register VA assignment"); 10716 10717 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10718 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 10719 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 10720 SDValue Hi; 10721 if (VA.getLocReg() == RISCV::X17) { 10722 // Second half of f64 is passed on the stack. 10723 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 10724 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10725 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 10726 MachinePointerInfo::getFixedStack(MF, FI)); 10727 } else { 10728 // Second half of f64 is passed in another GPR. 10729 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10730 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 10731 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 10732 } 10733 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 10734 } 10735 10736 // FastCC has less than 1% performance improvement for some particular 10737 // benchmark. But theoretically, it may has benenfit for some cases. 10738 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 10739 unsigned ValNo, MVT ValVT, MVT LocVT, 10740 CCValAssign::LocInfo LocInfo, 10741 ISD::ArgFlagsTy ArgFlags, CCState &State, 10742 bool IsFixed, bool IsRet, Type *OrigTy, 10743 const RISCVTargetLowering &TLI, 10744 Optional<unsigned> FirstMaskArgument) { 10745 10746 // X5 and X6 might be used for save-restore libcall. 10747 static const MCPhysReg GPRList[] = { 10748 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 10749 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 10750 RISCV::X29, RISCV::X30, RISCV::X31}; 10751 10752 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10753 if (unsigned Reg = State.AllocateReg(GPRList)) { 10754 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10755 return false; 10756 } 10757 } 10758 10759 if (LocVT == MVT::f16) { 10760 static const MCPhysReg FPR16List[] = { 10761 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 10762 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 10763 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 10764 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 10765 if (unsigned Reg = State.AllocateReg(FPR16List)) { 10766 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10767 return false; 10768 } 10769 } 10770 10771 if (LocVT == MVT::f32) { 10772 static const MCPhysReg FPR32List[] = { 10773 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 10774 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 10775 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 10776 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 10777 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10778 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10779 return false; 10780 } 10781 } 10782 10783 if (LocVT == MVT::f64) { 10784 static const MCPhysReg FPR64List[] = { 10785 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 10786 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 10787 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 10788 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 10789 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10790 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10791 return false; 10792 } 10793 } 10794 10795 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 10796 unsigned Offset4 = State.AllocateStack(4, Align(4)); 10797 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 10798 return false; 10799 } 10800 10801 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 10802 unsigned Offset5 = State.AllocateStack(8, Align(8)); 10803 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 10804 return false; 10805 } 10806 10807 if (LocVT.isVector()) { 10808 if (unsigned Reg = 10809 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 10810 // Fixed-length vectors are located in the corresponding scalable-vector 10811 // container types. 10812 if (ValVT.isFixedLengthVector()) 10813 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10814 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10815 } else { 10816 // Try and pass the address via a "fast" GPR. 10817 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 10818 LocInfo = CCValAssign::Indirect; 10819 LocVT = TLI.getSubtarget().getXLenVT(); 10820 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 10821 } else if (ValVT.isFixedLengthVector()) { 10822 auto StackAlign = 10823 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10824 unsigned StackOffset = 10825 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 10826 State.addLoc( 10827 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10828 } else { 10829 // Can't pass scalable vectors on the stack. 10830 return true; 10831 } 10832 } 10833 10834 return false; 10835 } 10836 10837 return true; // CC didn't match. 10838 } 10839 10840 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 10841 CCValAssign::LocInfo LocInfo, 10842 ISD::ArgFlagsTy ArgFlags, CCState &State) { 10843 10844 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10845 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 10846 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 10847 static const MCPhysReg GPRList[] = { 10848 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 10849 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 10850 if (unsigned Reg = State.AllocateReg(GPRList)) { 10851 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10852 return false; 10853 } 10854 } 10855 10856 if (LocVT == MVT::f32) { 10857 // Pass in STG registers: F1, ..., F6 10858 // fs0 ... fs5 10859 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 10860 RISCV::F18_F, RISCV::F19_F, 10861 RISCV::F20_F, RISCV::F21_F}; 10862 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10863 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10864 return false; 10865 } 10866 } 10867 10868 if (LocVT == MVT::f64) { 10869 // Pass in STG registers: D1, ..., D6 10870 // fs6 ... fs11 10871 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 10872 RISCV::F24_D, RISCV::F25_D, 10873 RISCV::F26_D, RISCV::F27_D}; 10874 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10875 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10876 return false; 10877 } 10878 } 10879 10880 report_fatal_error("No registers left in GHC calling convention"); 10881 return true; 10882 } 10883 10884 // Transform physical registers into virtual registers. 10885 SDValue RISCVTargetLowering::LowerFormalArguments( 10886 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 10887 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 10888 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 10889 10890 MachineFunction &MF = DAG.getMachineFunction(); 10891 10892 switch (CallConv) { 10893 default: 10894 report_fatal_error("Unsupported calling convention"); 10895 case CallingConv::C: 10896 case CallingConv::Fast: 10897 break; 10898 case CallingConv::GHC: 10899 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10900 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10901 report_fatal_error( 10902 "GHC calling convention requires the F and D instruction set extensions"); 10903 } 10904 10905 const Function &Func = MF.getFunction(); 10906 if (Func.hasFnAttribute("interrupt")) { 10907 if (!Func.arg_empty()) 10908 report_fatal_error( 10909 "Functions with the interrupt attribute cannot have arguments!"); 10910 10911 StringRef Kind = 10912 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10913 10914 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10915 report_fatal_error( 10916 "Function interrupt attribute argument not supported!"); 10917 } 10918 10919 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10920 MVT XLenVT = Subtarget.getXLenVT(); 10921 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10922 // Used with vargs to acumulate store chains. 10923 std::vector<SDValue> OutChains; 10924 10925 // Assign locations to all of the incoming arguments. 10926 SmallVector<CCValAssign, 16> ArgLocs; 10927 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10928 10929 if (CallConv == CallingConv::GHC) 10930 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10931 else 10932 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10933 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10934 : CC_RISCV); 10935 10936 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10937 CCValAssign &VA = ArgLocs[i]; 10938 SDValue ArgValue; 10939 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10940 // case. 10941 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10942 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10943 else if (VA.isRegLoc()) 10944 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10945 else 10946 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10947 10948 if (VA.getLocInfo() == CCValAssign::Indirect) { 10949 // If the original argument was split and passed by reference (e.g. i128 10950 // on RV32), we need to load all parts of it here (using the same 10951 // address). Vectors may be partly split to registers and partly to the 10952 // stack, in which case the base address is partly offset and subsequent 10953 // stores are relative to that. 10954 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10955 MachinePointerInfo())); 10956 unsigned ArgIndex = Ins[i].OrigArgIndex; 10957 unsigned ArgPartOffset = Ins[i].PartOffset; 10958 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10959 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10960 CCValAssign &PartVA = ArgLocs[i + 1]; 10961 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10962 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10963 if (PartVA.getValVT().isScalableVector()) 10964 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10965 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10966 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10967 MachinePointerInfo())); 10968 ++i; 10969 } 10970 continue; 10971 } 10972 InVals.push_back(ArgValue); 10973 } 10974 10975 if (IsVarArg) { 10976 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10977 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10978 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10979 MachineFrameInfo &MFI = MF.getFrameInfo(); 10980 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10981 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10982 10983 // Offset of the first variable argument from stack pointer, and size of 10984 // the vararg save area. For now, the varargs save area is either zero or 10985 // large enough to hold a0-a7. 10986 int VaArgOffset, VarArgsSaveSize; 10987 10988 // If all registers are allocated, then all varargs must be passed on the 10989 // stack and we don't need to save any argregs. 10990 if (ArgRegs.size() == Idx) { 10991 VaArgOffset = CCInfo.getNextStackOffset(); 10992 VarArgsSaveSize = 0; 10993 } else { 10994 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10995 VaArgOffset = -VarArgsSaveSize; 10996 } 10997 10998 // Record the frame index of the first variable argument 10999 // which is a value necessary to VASTART. 11000 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 11001 RVFI->setVarArgsFrameIndex(FI); 11002 11003 // If saving an odd number of registers then create an extra stack slot to 11004 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 11005 // offsets to even-numbered registered remain 2*XLEN-aligned. 11006 if (Idx % 2) { 11007 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 11008 VarArgsSaveSize += XLenInBytes; 11009 } 11010 11011 // Copy the integer registers that may have been used for passing varargs 11012 // to the vararg save area. 11013 for (unsigned I = Idx; I < ArgRegs.size(); 11014 ++I, VaArgOffset += XLenInBytes) { 11015 const Register Reg = RegInfo.createVirtualRegister(RC); 11016 RegInfo.addLiveIn(ArgRegs[I], Reg); 11017 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 11018 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 11019 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 11020 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 11021 MachinePointerInfo::getFixedStack(MF, FI)); 11022 cast<StoreSDNode>(Store.getNode()) 11023 ->getMemOperand() 11024 ->setValue((Value *)nullptr); 11025 OutChains.push_back(Store); 11026 } 11027 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 11028 } 11029 11030 // All stores are grouped in one node to allow the matching between 11031 // the size of Ins and InVals. This only happens for vararg functions. 11032 if (!OutChains.empty()) { 11033 OutChains.push_back(Chain); 11034 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 11035 } 11036 11037 return Chain; 11038 } 11039 11040 /// isEligibleForTailCallOptimization - Check whether the call is eligible 11041 /// for tail call optimization. 11042 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 11043 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 11044 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 11045 const SmallVector<CCValAssign, 16> &ArgLocs) const { 11046 11047 auto &Callee = CLI.Callee; 11048 auto CalleeCC = CLI.CallConv; 11049 auto &Outs = CLI.Outs; 11050 auto &Caller = MF.getFunction(); 11051 auto CallerCC = Caller.getCallingConv(); 11052 11053 // Exception-handling functions need a special set of instructions to 11054 // indicate a return to the hardware. Tail-calling another function would 11055 // probably break this. 11056 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 11057 // should be expanded as new function attributes are introduced. 11058 if (Caller.hasFnAttribute("interrupt")) 11059 return false; 11060 11061 // Do not tail call opt if the stack is used to pass parameters. 11062 if (CCInfo.getNextStackOffset() != 0) 11063 return false; 11064 11065 // Do not tail call opt if any parameters need to be passed indirectly. 11066 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 11067 // passed indirectly. So the address of the value will be passed in a 11068 // register, or if not available, then the address is put on the stack. In 11069 // order to pass indirectly, space on the stack often needs to be allocated 11070 // in order to store the value. In this case the CCInfo.getNextStackOffset() 11071 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 11072 // are passed CCValAssign::Indirect. 11073 for (auto &VA : ArgLocs) 11074 if (VA.getLocInfo() == CCValAssign::Indirect) 11075 return false; 11076 11077 // Do not tail call opt if either caller or callee uses struct return 11078 // semantics. 11079 auto IsCallerStructRet = Caller.hasStructRetAttr(); 11080 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 11081 if (IsCallerStructRet || IsCalleeStructRet) 11082 return false; 11083 11084 // Externally-defined functions with weak linkage should not be 11085 // tail-called. The behaviour of branch instructions in this situation (as 11086 // used for tail calls) is implementation-defined, so we cannot rely on the 11087 // linker replacing the tail call with a return. 11088 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 11089 const GlobalValue *GV = G->getGlobal(); 11090 if (GV->hasExternalWeakLinkage()) 11091 return false; 11092 } 11093 11094 // The callee has to preserve all registers the caller needs to preserve. 11095 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11096 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 11097 if (CalleeCC != CallerCC) { 11098 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 11099 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 11100 return false; 11101 } 11102 11103 // Byval parameters hand the function a pointer directly into the stack area 11104 // we want to reuse during a tail call. Working around this *is* possible 11105 // but less efficient and uglier in LowerCall. 11106 for (auto &Arg : Outs) 11107 if (Arg.Flags.isByVal()) 11108 return false; 11109 11110 return true; 11111 } 11112 11113 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 11114 return DAG.getDataLayout().getPrefTypeAlign( 11115 VT.getTypeForEVT(*DAG.getContext())); 11116 } 11117 11118 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 11119 // and output parameter nodes. 11120 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 11121 SmallVectorImpl<SDValue> &InVals) const { 11122 SelectionDAG &DAG = CLI.DAG; 11123 SDLoc &DL = CLI.DL; 11124 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 11125 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 11126 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 11127 SDValue Chain = CLI.Chain; 11128 SDValue Callee = CLI.Callee; 11129 bool &IsTailCall = CLI.IsTailCall; 11130 CallingConv::ID CallConv = CLI.CallConv; 11131 bool IsVarArg = CLI.IsVarArg; 11132 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 11133 MVT XLenVT = Subtarget.getXLenVT(); 11134 11135 MachineFunction &MF = DAG.getMachineFunction(); 11136 11137 // Analyze the operands of the call, assigning locations to each operand. 11138 SmallVector<CCValAssign, 16> ArgLocs; 11139 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 11140 11141 if (CallConv == CallingConv::GHC) 11142 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 11143 else 11144 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 11145 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 11146 : CC_RISCV); 11147 11148 // Check if it's really possible to do a tail call. 11149 if (IsTailCall) 11150 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 11151 11152 if (IsTailCall) 11153 ++NumTailCalls; 11154 else if (CLI.CB && CLI.CB->isMustTailCall()) 11155 report_fatal_error("failed to perform tail call elimination on a call " 11156 "site marked musttail"); 11157 11158 // Get a count of how many bytes are to be pushed on the stack. 11159 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 11160 11161 // Create local copies for byval args 11162 SmallVector<SDValue, 8> ByValArgs; 11163 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 11164 ISD::ArgFlagsTy Flags = Outs[i].Flags; 11165 if (!Flags.isByVal()) 11166 continue; 11167 11168 SDValue Arg = OutVals[i]; 11169 unsigned Size = Flags.getByValSize(); 11170 Align Alignment = Flags.getNonZeroByValAlign(); 11171 11172 int FI = 11173 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 11174 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 11175 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 11176 11177 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 11178 /*IsVolatile=*/false, 11179 /*AlwaysInline=*/false, IsTailCall, 11180 MachinePointerInfo(), MachinePointerInfo()); 11181 ByValArgs.push_back(FIPtr); 11182 } 11183 11184 if (!IsTailCall) 11185 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 11186 11187 // Copy argument values to their designated locations. 11188 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 11189 SmallVector<SDValue, 8> MemOpChains; 11190 SDValue StackPtr; 11191 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 11192 CCValAssign &VA = ArgLocs[i]; 11193 SDValue ArgValue = OutVals[i]; 11194 ISD::ArgFlagsTy Flags = Outs[i].Flags; 11195 11196 // Handle passing f64 on RV32D with a soft float ABI as a special case. 11197 bool IsF64OnRV32DSoftABI = 11198 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 11199 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 11200 SDValue SplitF64 = DAG.getNode( 11201 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 11202 SDValue Lo = SplitF64.getValue(0); 11203 SDValue Hi = SplitF64.getValue(1); 11204 11205 Register RegLo = VA.getLocReg(); 11206 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 11207 11208 if (RegLo == RISCV::X17) { 11209 // Second half of f64 is passed on the stack. 11210 // Work out the address of the stack slot. 11211 if (!StackPtr.getNode()) 11212 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 11213 // Emit the store. 11214 MemOpChains.push_back( 11215 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 11216 } else { 11217 // Second half of f64 is passed in another GPR. 11218 assert(RegLo < RISCV::X31 && "Invalid register pair"); 11219 Register RegHigh = RegLo + 1; 11220 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 11221 } 11222 continue; 11223 } 11224 11225 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 11226 // as any other MemLoc. 11227 11228 // Promote the value if needed. 11229 // For now, only handle fully promoted and indirect arguments. 11230 if (VA.getLocInfo() == CCValAssign::Indirect) { 11231 // Store the argument in a stack slot and pass its address. 11232 Align StackAlign = 11233 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 11234 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 11235 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 11236 // If the original argument was split (e.g. i128), we need 11237 // to store the required parts of it here (and pass just one address). 11238 // Vectors may be partly split to registers and partly to the stack, in 11239 // which case the base address is partly offset and subsequent stores are 11240 // relative to that. 11241 unsigned ArgIndex = Outs[i].OrigArgIndex; 11242 unsigned ArgPartOffset = Outs[i].PartOffset; 11243 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 11244 // Calculate the total size to store. We don't have access to what we're 11245 // actually storing other than performing the loop and collecting the 11246 // info. 11247 SmallVector<std::pair<SDValue, SDValue>> Parts; 11248 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 11249 SDValue PartValue = OutVals[i + 1]; 11250 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 11251 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 11252 EVT PartVT = PartValue.getValueType(); 11253 if (PartVT.isScalableVector()) 11254 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 11255 StoredSize += PartVT.getStoreSize(); 11256 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 11257 Parts.push_back(std::make_pair(PartValue, Offset)); 11258 ++i; 11259 } 11260 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 11261 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 11262 MemOpChains.push_back( 11263 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 11264 MachinePointerInfo::getFixedStack(MF, FI))); 11265 for (const auto &Part : Parts) { 11266 SDValue PartValue = Part.first; 11267 SDValue PartOffset = Part.second; 11268 SDValue Address = 11269 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 11270 MemOpChains.push_back( 11271 DAG.getStore(Chain, DL, PartValue, Address, 11272 MachinePointerInfo::getFixedStack(MF, FI))); 11273 } 11274 ArgValue = SpillSlot; 11275 } else { 11276 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 11277 } 11278 11279 // Use local copy if it is a byval arg. 11280 if (Flags.isByVal()) 11281 ArgValue = ByValArgs[j++]; 11282 11283 if (VA.isRegLoc()) { 11284 // Queue up the argument copies and emit them at the end. 11285 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 11286 } else { 11287 assert(VA.isMemLoc() && "Argument not register or memory"); 11288 assert(!IsTailCall && "Tail call not allowed if stack is used " 11289 "for passing parameters"); 11290 11291 // Work out the address of the stack slot. 11292 if (!StackPtr.getNode()) 11293 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 11294 SDValue Address = 11295 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 11296 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 11297 11298 // Emit the store. 11299 MemOpChains.push_back( 11300 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 11301 } 11302 } 11303 11304 // Join the stores, which are independent of one another. 11305 if (!MemOpChains.empty()) 11306 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 11307 11308 SDValue Glue; 11309 11310 // Build a sequence of copy-to-reg nodes, chained and glued together. 11311 for (auto &Reg : RegsToPass) { 11312 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 11313 Glue = Chain.getValue(1); 11314 } 11315 11316 // Validate that none of the argument registers have been marked as 11317 // reserved, if so report an error. Do the same for the return address if this 11318 // is not a tailcall. 11319 validateCCReservedRegs(RegsToPass, MF); 11320 if (!IsTailCall && 11321 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 11322 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11323 MF.getFunction(), 11324 "Return address register required, but has been reserved."}); 11325 11326 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 11327 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 11328 // split it and then direct call can be matched by PseudoCALL. 11329 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 11330 const GlobalValue *GV = S->getGlobal(); 11331 11332 unsigned OpFlags = RISCVII::MO_CALL; 11333 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 11334 OpFlags = RISCVII::MO_PLT; 11335 11336 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 11337 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 11338 unsigned OpFlags = RISCVII::MO_CALL; 11339 11340 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 11341 nullptr)) 11342 OpFlags = RISCVII::MO_PLT; 11343 11344 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 11345 } 11346 11347 // The first call operand is the chain and the second is the target address. 11348 SmallVector<SDValue, 8> Ops; 11349 Ops.push_back(Chain); 11350 Ops.push_back(Callee); 11351 11352 // Add argument registers to the end of the list so that they are 11353 // known live into the call. 11354 for (auto &Reg : RegsToPass) 11355 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 11356 11357 if (!IsTailCall) { 11358 // Add a register mask operand representing the call-preserved registers. 11359 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 11360 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 11361 assert(Mask && "Missing call preserved mask for calling convention"); 11362 Ops.push_back(DAG.getRegisterMask(Mask)); 11363 } 11364 11365 // Glue the call to the argument copies, if any. 11366 if (Glue.getNode()) 11367 Ops.push_back(Glue); 11368 11369 // Emit the call. 11370 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 11371 11372 if (IsTailCall) { 11373 MF.getFrameInfo().setHasTailCall(); 11374 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 11375 } 11376 11377 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 11378 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 11379 Glue = Chain.getValue(1); 11380 11381 // Mark the end of the call, which is glued to the call itself. 11382 Chain = DAG.getCALLSEQ_END(Chain, 11383 DAG.getConstant(NumBytes, DL, PtrVT, true), 11384 DAG.getConstant(0, DL, PtrVT, true), 11385 Glue, DL); 11386 Glue = Chain.getValue(1); 11387 11388 // Assign locations to each value returned by this call. 11389 SmallVector<CCValAssign, 16> RVLocs; 11390 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 11391 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 11392 11393 // Copy all of the result registers out of their specified physreg. 11394 for (auto &VA : RVLocs) { 11395 // Copy the value out 11396 SDValue RetValue = 11397 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 11398 // Glue the RetValue to the end of the call sequence 11399 Chain = RetValue.getValue(1); 11400 Glue = RetValue.getValue(2); 11401 11402 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 11403 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 11404 SDValue RetValue2 = 11405 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 11406 Chain = RetValue2.getValue(1); 11407 Glue = RetValue2.getValue(2); 11408 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 11409 RetValue2); 11410 } 11411 11412 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 11413 11414 InVals.push_back(RetValue); 11415 } 11416 11417 return Chain; 11418 } 11419 11420 bool RISCVTargetLowering::CanLowerReturn( 11421 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 11422 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 11423 SmallVector<CCValAssign, 16> RVLocs; 11424 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 11425 11426 Optional<unsigned> FirstMaskArgument; 11427 if (Subtarget.hasVInstructions()) 11428 FirstMaskArgument = preAssignMask(Outs); 11429 11430 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 11431 MVT VT = Outs[i].VT; 11432 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 11433 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 11434 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 11435 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 11436 *this, FirstMaskArgument)) 11437 return false; 11438 } 11439 return true; 11440 } 11441 11442 SDValue 11443 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 11444 bool IsVarArg, 11445 const SmallVectorImpl<ISD::OutputArg> &Outs, 11446 const SmallVectorImpl<SDValue> &OutVals, 11447 const SDLoc &DL, SelectionDAG &DAG) const { 11448 const MachineFunction &MF = DAG.getMachineFunction(); 11449 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 11450 11451 // Stores the assignment of the return value to a location. 11452 SmallVector<CCValAssign, 16> RVLocs; 11453 11454 // Info about the registers and stack slot. 11455 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 11456 *DAG.getContext()); 11457 11458 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 11459 nullptr, CC_RISCV); 11460 11461 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 11462 report_fatal_error("GHC functions return void only"); 11463 11464 SDValue Glue; 11465 SmallVector<SDValue, 4> RetOps(1, Chain); 11466 11467 // Copy the result values into the output registers. 11468 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 11469 SDValue Val = OutVals[i]; 11470 CCValAssign &VA = RVLocs[i]; 11471 assert(VA.isRegLoc() && "Can only return in registers!"); 11472 11473 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 11474 // Handle returning f64 on RV32D with a soft float ABI. 11475 assert(VA.isRegLoc() && "Expected return via registers"); 11476 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 11477 DAG.getVTList(MVT::i32, MVT::i32), Val); 11478 SDValue Lo = SplitF64.getValue(0); 11479 SDValue Hi = SplitF64.getValue(1); 11480 Register RegLo = VA.getLocReg(); 11481 assert(RegLo < RISCV::X31 && "Invalid register pair"); 11482 Register RegHi = RegLo + 1; 11483 11484 if (STI.isRegisterReservedByUser(RegLo) || 11485 STI.isRegisterReservedByUser(RegHi)) 11486 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11487 MF.getFunction(), 11488 "Return value register required, but has been reserved."}); 11489 11490 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 11491 Glue = Chain.getValue(1); 11492 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 11493 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 11494 Glue = Chain.getValue(1); 11495 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 11496 } else { 11497 // Handle a 'normal' return. 11498 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 11499 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 11500 11501 if (STI.isRegisterReservedByUser(VA.getLocReg())) 11502 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 11503 MF.getFunction(), 11504 "Return value register required, but has been reserved."}); 11505 11506 // Guarantee that all emitted copies are stuck together. 11507 Glue = Chain.getValue(1); 11508 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 11509 } 11510 } 11511 11512 RetOps[0] = Chain; // Update chain. 11513 11514 // Add the glue node if we have it. 11515 if (Glue.getNode()) { 11516 RetOps.push_back(Glue); 11517 } 11518 11519 unsigned RetOpc = RISCVISD::RET_FLAG; 11520 // Interrupt service routines use different return instructions. 11521 const Function &Func = DAG.getMachineFunction().getFunction(); 11522 if (Func.hasFnAttribute("interrupt")) { 11523 if (!Func.getReturnType()->isVoidTy()) 11524 report_fatal_error( 11525 "Functions with the interrupt attribute must have void return type!"); 11526 11527 MachineFunction &MF = DAG.getMachineFunction(); 11528 StringRef Kind = 11529 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 11530 11531 if (Kind == "user") 11532 RetOpc = RISCVISD::URET_FLAG; 11533 else if (Kind == "supervisor") 11534 RetOpc = RISCVISD::SRET_FLAG; 11535 else 11536 RetOpc = RISCVISD::MRET_FLAG; 11537 } 11538 11539 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 11540 } 11541 11542 void RISCVTargetLowering::validateCCReservedRegs( 11543 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 11544 MachineFunction &MF) const { 11545 const Function &F = MF.getFunction(); 11546 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 11547 11548 if (llvm::any_of(Regs, [&STI](auto Reg) { 11549 return STI.isRegisterReservedByUser(Reg.first); 11550 })) 11551 F.getContext().diagnose(DiagnosticInfoUnsupported{ 11552 F, "Argument register required, but has been reserved."}); 11553 } 11554 11555 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 11556 return CI->isTailCall(); 11557 } 11558 11559 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 11560 #define NODE_NAME_CASE(NODE) \ 11561 case RISCVISD::NODE: \ 11562 return "RISCVISD::" #NODE; 11563 // clang-format off 11564 switch ((RISCVISD::NodeType)Opcode) { 11565 case RISCVISD::FIRST_NUMBER: 11566 break; 11567 NODE_NAME_CASE(RET_FLAG) 11568 NODE_NAME_CASE(URET_FLAG) 11569 NODE_NAME_CASE(SRET_FLAG) 11570 NODE_NAME_CASE(MRET_FLAG) 11571 NODE_NAME_CASE(CALL) 11572 NODE_NAME_CASE(SELECT_CC) 11573 NODE_NAME_CASE(BR_CC) 11574 NODE_NAME_CASE(BuildPairF64) 11575 NODE_NAME_CASE(SplitF64) 11576 NODE_NAME_CASE(TAIL) 11577 NODE_NAME_CASE(ADD_LO) 11578 NODE_NAME_CASE(HI) 11579 NODE_NAME_CASE(LLA) 11580 NODE_NAME_CASE(ADD_TPREL) 11581 NODE_NAME_CASE(LA) 11582 NODE_NAME_CASE(LA_TLS_IE) 11583 NODE_NAME_CASE(LA_TLS_GD) 11584 NODE_NAME_CASE(MULHSU) 11585 NODE_NAME_CASE(SLLW) 11586 NODE_NAME_CASE(SRAW) 11587 NODE_NAME_CASE(SRLW) 11588 NODE_NAME_CASE(DIVW) 11589 NODE_NAME_CASE(DIVUW) 11590 NODE_NAME_CASE(REMUW) 11591 NODE_NAME_CASE(ROLW) 11592 NODE_NAME_CASE(RORW) 11593 NODE_NAME_CASE(CLZW) 11594 NODE_NAME_CASE(CTZW) 11595 NODE_NAME_CASE(FSLW) 11596 NODE_NAME_CASE(FSRW) 11597 NODE_NAME_CASE(FSL) 11598 NODE_NAME_CASE(FSR) 11599 NODE_NAME_CASE(FMV_H_X) 11600 NODE_NAME_CASE(FMV_X_ANYEXTH) 11601 NODE_NAME_CASE(FMV_X_SIGNEXTH) 11602 NODE_NAME_CASE(FMV_W_X_RV64) 11603 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 11604 NODE_NAME_CASE(FCVT_X) 11605 NODE_NAME_CASE(FCVT_XU) 11606 NODE_NAME_CASE(FCVT_W_RV64) 11607 NODE_NAME_CASE(FCVT_WU_RV64) 11608 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 11609 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 11610 NODE_NAME_CASE(READ_CYCLE_WIDE) 11611 NODE_NAME_CASE(GREV) 11612 NODE_NAME_CASE(GREVW) 11613 NODE_NAME_CASE(GORC) 11614 NODE_NAME_CASE(GORCW) 11615 NODE_NAME_CASE(SHFL) 11616 NODE_NAME_CASE(SHFLW) 11617 NODE_NAME_CASE(UNSHFL) 11618 NODE_NAME_CASE(UNSHFLW) 11619 NODE_NAME_CASE(BFP) 11620 NODE_NAME_CASE(BFPW) 11621 NODE_NAME_CASE(BCOMPRESS) 11622 NODE_NAME_CASE(BCOMPRESSW) 11623 NODE_NAME_CASE(BDECOMPRESS) 11624 NODE_NAME_CASE(BDECOMPRESSW) 11625 NODE_NAME_CASE(VMV_V_X_VL) 11626 NODE_NAME_CASE(VFMV_V_F_VL) 11627 NODE_NAME_CASE(VMV_X_S) 11628 NODE_NAME_CASE(VMV_S_X_VL) 11629 NODE_NAME_CASE(VFMV_S_F_VL) 11630 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 11631 NODE_NAME_CASE(READ_VLENB) 11632 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 11633 NODE_NAME_CASE(VSLIDEUP_VL) 11634 NODE_NAME_CASE(VSLIDE1UP_VL) 11635 NODE_NAME_CASE(VSLIDEDOWN_VL) 11636 NODE_NAME_CASE(VSLIDE1DOWN_VL) 11637 NODE_NAME_CASE(VID_VL) 11638 NODE_NAME_CASE(VFNCVT_ROD_VL) 11639 NODE_NAME_CASE(VECREDUCE_ADD_VL) 11640 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 11641 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 11642 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 11643 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 11644 NODE_NAME_CASE(VECREDUCE_AND_VL) 11645 NODE_NAME_CASE(VECREDUCE_OR_VL) 11646 NODE_NAME_CASE(VECREDUCE_XOR_VL) 11647 NODE_NAME_CASE(VECREDUCE_FADD_VL) 11648 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 11649 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 11650 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 11651 NODE_NAME_CASE(ADD_VL) 11652 NODE_NAME_CASE(AND_VL) 11653 NODE_NAME_CASE(MUL_VL) 11654 NODE_NAME_CASE(OR_VL) 11655 NODE_NAME_CASE(SDIV_VL) 11656 NODE_NAME_CASE(SHL_VL) 11657 NODE_NAME_CASE(SREM_VL) 11658 NODE_NAME_CASE(SRA_VL) 11659 NODE_NAME_CASE(SRL_VL) 11660 NODE_NAME_CASE(SUB_VL) 11661 NODE_NAME_CASE(UDIV_VL) 11662 NODE_NAME_CASE(UREM_VL) 11663 NODE_NAME_CASE(XOR_VL) 11664 NODE_NAME_CASE(SADDSAT_VL) 11665 NODE_NAME_CASE(UADDSAT_VL) 11666 NODE_NAME_CASE(SSUBSAT_VL) 11667 NODE_NAME_CASE(USUBSAT_VL) 11668 NODE_NAME_CASE(FADD_VL) 11669 NODE_NAME_CASE(FSUB_VL) 11670 NODE_NAME_CASE(FMUL_VL) 11671 NODE_NAME_CASE(FDIV_VL) 11672 NODE_NAME_CASE(FNEG_VL) 11673 NODE_NAME_CASE(FABS_VL) 11674 NODE_NAME_CASE(FSQRT_VL) 11675 NODE_NAME_CASE(VFMADD_VL) 11676 NODE_NAME_CASE(VFNMADD_VL) 11677 NODE_NAME_CASE(VFMSUB_VL) 11678 NODE_NAME_CASE(VFNMSUB_VL) 11679 NODE_NAME_CASE(FCOPYSIGN_VL) 11680 NODE_NAME_CASE(SMIN_VL) 11681 NODE_NAME_CASE(SMAX_VL) 11682 NODE_NAME_CASE(UMIN_VL) 11683 NODE_NAME_CASE(UMAX_VL) 11684 NODE_NAME_CASE(FMINNUM_VL) 11685 NODE_NAME_CASE(FMAXNUM_VL) 11686 NODE_NAME_CASE(MULHS_VL) 11687 NODE_NAME_CASE(MULHU_VL) 11688 NODE_NAME_CASE(FP_TO_SINT_VL) 11689 NODE_NAME_CASE(FP_TO_UINT_VL) 11690 NODE_NAME_CASE(SINT_TO_FP_VL) 11691 NODE_NAME_CASE(UINT_TO_FP_VL) 11692 NODE_NAME_CASE(FP_EXTEND_VL) 11693 NODE_NAME_CASE(FP_ROUND_VL) 11694 NODE_NAME_CASE(VWMUL_VL) 11695 NODE_NAME_CASE(VWMULU_VL) 11696 NODE_NAME_CASE(VWMULSU_VL) 11697 NODE_NAME_CASE(VWADD_VL) 11698 NODE_NAME_CASE(VWADDU_VL) 11699 NODE_NAME_CASE(VWSUB_VL) 11700 NODE_NAME_CASE(VWSUBU_VL) 11701 NODE_NAME_CASE(VWADD_W_VL) 11702 NODE_NAME_CASE(VWADDU_W_VL) 11703 NODE_NAME_CASE(VWSUB_W_VL) 11704 NODE_NAME_CASE(VWSUBU_W_VL) 11705 NODE_NAME_CASE(SETCC_VL) 11706 NODE_NAME_CASE(VSELECT_VL) 11707 NODE_NAME_CASE(VP_MERGE_VL) 11708 NODE_NAME_CASE(VMAND_VL) 11709 NODE_NAME_CASE(VMOR_VL) 11710 NODE_NAME_CASE(VMXOR_VL) 11711 NODE_NAME_CASE(VMCLR_VL) 11712 NODE_NAME_CASE(VMSET_VL) 11713 NODE_NAME_CASE(VRGATHER_VX_VL) 11714 NODE_NAME_CASE(VRGATHER_VV_VL) 11715 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 11716 NODE_NAME_CASE(VSEXT_VL) 11717 NODE_NAME_CASE(VZEXT_VL) 11718 NODE_NAME_CASE(VCPOP_VL) 11719 NODE_NAME_CASE(READ_CSR) 11720 NODE_NAME_CASE(WRITE_CSR) 11721 NODE_NAME_CASE(SWAP_CSR) 11722 } 11723 // clang-format on 11724 return nullptr; 11725 #undef NODE_NAME_CASE 11726 } 11727 11728 /// getConstraintType - Given a constraint letter, return the type of 11729 /// constraint it is for this target. 11730 RISCVTargetLowering::ConstraintType 11731 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 11732 if (Constraint.size() == 1) { 11733 switch (Constraint[0]) { 11734 default: 11735 break; 11736 case 'f': 11737 return C_RegisterClass; 11738 case 'I': 11739 case 'J': 11740 case 'K': 11741 return C_Immediate; 11742 case 'A': 11743 return C_Memory; 11744 case 'S': // A symbolic address 11745 return C_Other; 11746 } 11747 } else { 11748 if (Constraint == "vr" || Constraint == "vm") 11749 return C_RegisterClass; 11750 } 11751 return TargetLowering::getConstraintType(Constraint); 11752 } 11753 11754 std::pair<unsigned, const TargetRegisterClass *> 11755 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11756 StringRef Constraint, 11757 MVT VT) const { 11758 // First, see if this is a constraint that directly corresponds to a 11759 // RISCV register class. 11760 if (Constraint.size() == 1) { 11761 switch (Constraint[0]) { 11762 case 'r': 11763 // TODO: Support fixed vectors up to XLen for P extension? 11764 if (VT.isVector()) 11765 break; 11766 return std::make_pair(0U, &RISCV::GPRRegClass); 11767 case 'f': 11768 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 11769 return std::make_pair(0U, &RISCV::FPR16RegClass); 11770 if (Subtarget.hasStdExtF() && VT == MVT::f32) 11771 return std::make_pair(0U, &RISCV::FPR32RegClass); 11772 if (Subtarget.hasStdExtD() && VT == MVT::f64) 11773 return std::make_pair(0U, &RISCV::FPR64RegClass); 11774 break; 11775 default: 11776 break; 11777 } 11778 } else if (Constraint == "vr") { 11779 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 11780 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11781 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 11782 return std::make_pair(0U, RC); 11783 } 11784 } else if (Constraint == "vm") { 11785 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 11786 return std::make_pair(0U, &RISCV::VMV0RegClass); 11787 } 11788 11789 // Clang will correctly decode the usage of register name aliases into their 11790 // official names. However, other frontends like `rustc` do not. This allows 11791 // users of these frontends to use the ABI names for registers in LLVM-style 11792 // register constraints. 11793 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 11794 .Case("{zero}", RISCV::X0) 11795 .Case("{ra}", RISCV::X1) 11796 .Case("{sp}", RISCV::X2) 11797 .Case("{gp}", RISCV::X3) 11798 .Case("{tp}", RISCV::X4) 11799 .Case("{t0}", RISCV::X5) 11800 .Case("{t1}", RISCV::X6) 11801 .Case("{t2}", RISCV::X7) 11802 .Cases("{s0}", "{fp}", RISCV::X8) 11803 .Case("{s1}", RISCV::X9) 11804 .Case("{a0}", RISCV::X10) 11805 .Case("{a1}", RISCV::X11) 11806 .Case("{a2}", RISCV::X12) 11807 .Case("{a3}", RISCV::X13) 11808 .Case("{a4}", RISCV::X14) 11809 .Case("{a5}", RISCV::X15) 11810 .Case("{a6}", RISCV::X16) 11811 .Case("{a7}", RISCV::X17) 11812 .Case("{s2}", RISCV::X18) 11813 .Case("{s3}", RISCV::X19) 11814 .Case("{s4}", RISCV::X20) 11815 .Case("{s5}", RISCV::X21) 11816 .Case("{s6}", RISCV::X22) 11817 .Case("{s7}", RISCV::X23) 11818 .Case("{s8}", RISCV::X24) 11819 .Case("{s9}", RISCV::X25) 11820 .Case("{s10}", RISCV::X26) 11821 .Case("{s11}", RISCV::X27) 11822 .Case("{t3}", RISCV::X28) 11823 .Case("{t4}", RISCV::X29) 11824 .Case("{t5}", RISCV::X30) 11825 .Case("{t6}", RISCV::X31) 11826 .Default(RISCV::NoRegister); 11827 if (XRegFromAlias != RISCV::NoRegister) 11828 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 11829 11830 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 11831 // TableGen record rather than the AsmName to choose registers for InlineAsm 11832 // constraints, plus we want to match those names to the widest floating point 11833 // register type available, manually select floating point registers here. 11834 // 11835 // The second case is the ABI name of the register, so that frontends can also 11836 // use the ABI names in register constraint lists. 11837 if (Subtarget.hasStdExtF()) { 11838 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 11839 .Cases("{f0}", "{ft0}", RISCV::F0_F) 11840 .Cases("{f1}", "{ft1}", RISCV::F1_F) 11841 .Cases("{f2}", "{ft2}", RISCV::F2_F) 11842 .Cases("{f3}", "{ft3}", RISCV::F3_F) 11843 .Cases("{f4}", "{ft4}", RISCV::F4_F) 11844 .Cases("{f5}", "{ft5}", RISCV::F5_F) 11845 .Cases("{f6}", "{ft6}", RISCV::F6_F) 11846 .Cases("{f7}", "{ft7}", RISCV::F7_F) 11847 .Cases("{f8}", "{fs0}", RISCV::F8_F) 11848 .Cases("{f9}", "{fs1}", RISCV::F9_F) 11849 .Cases("{f10}", "{fa0}", RISCV::F10_F) 11850 .Cases("{f11}", "{fa1}", RISCV::F11_F) 11851 .Cases("{f12}", "{fa2}", RISCV::F12_F) 11852 .Cases("{f13}", "{fa3}", RISCV::F13_F) 11853 .Cases("{f14}", "{fa4}", RISCV::F14_F) 11854 .Cases("{f15}", "{fa5}", RISCV::F15_F) 11855 .Cases("{f16}", "{fa6}", RISCV::F16_F) 11856 .Cases("{f17}", "{fa7}", RISCV::F17_F) 11857 .Cases("{f18}", "{fs2}", RISCV::F18_F) 11858 .Cases("{f19}", "{fs3}", RISCV::F19_F) 11859 .Cases("{f20}", "{fs4}", RISCV::F20_F) 11860 .Cases("{f21}", "{fs5}", RISCV::F21_F) 11861 .Cases("{f22}", "{fs6}", RISCV::F22_F) 11862 .Cases("{f23}", "{fs7}", RISCV::F23_F) 11863 .Cases("{f24}", "{fs8}", RISCV::F24_F) 11864 .Cases("{f25}", "{fs9}", RISCV::F25_F) 11865 .Cases("{f26}", "{fs10}", RISCV::F26_F) 11866 .Cases("{f27}", "{fs11}", RISCV::F27_F) 11867 .Cases("{f28}", "{ft8}", RISCV::F28_F) 11868 .Cases("{f29}", "{ft9}", RISCV::F29_F) 11869 .Cases("{f30}", "{ft10}", RISCV::F30_F) 11870 .Cases("{f31}", "{ft11}", RISCV::F31_F) 11871 .Default(RISCV::NoRegister); 11872 if (FReg != RISCV::NoRegister) { 11873 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 11874 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 11875 unsigned RegNo = FReg - RISCV::F0_F; 11876 unsigned DReg = RISCV::F0_D + RegNo; 11877 return std::make_pair(DReg, &RISCV::FPR64RegClass); 11878 } 11879 if (VT == MVT::f32 || VT == MVT::Other) 11880 return std::make_pair(FReg, &RISCV::FPR32RegClass); 11881 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 11882 unsigned RegNo = FReg - RISCV::F0_F; 11883 unsigned HReg = RISCV::F0_H + RegNo; 11884 return std::make_pair(HReg, &RISCV::FPR16RegClass); 11885 } 11886 } 11887 } 11888 11889 if (Subtarget.hasVInstructions()) { 11890 Register VReg = StringSwitch<Register>(Constraint.lower()) 11891 .Case("{v0}", RISCV::V0) 11892 .Case("{v1}", RISCV::V1) 11893 .Case("{v2}", RISCV::V2) 11894 .Case("{v3}", RISCV::V3) 11895 .Case("{v4}", RISCV::V4) 11896 .Case("{v5}", RISCV::V5) 11897 .Case("{v6}", RISCV::V6) 11898 .Case("{v7}", RISCV::V7) 11899 .Case("{v8}", RISCV::V8) 11900 .Case("{v9}", RISCV::V9) 11901 .Case("{v10}", RISCV::V10) 11902 .Case("{v11}", RISCV::V11) 11903 .Case("{v12}", RISCV::V12) 11904 .Case("{v13}", RISCV::V13) 11905 .Case("{v14}", RISCV::V14) 11906 .Case("{v15}", RISCV::V15) 11907 .Case("{v16}", RISCV::V16) 11908 .Case("{v17}", RISCV::V17) 11909 .Case("{v18}", RISCV::V18) 11910 .Case("{v19}", RISCV::V19) 11911 .Case("{v20}", RISCV::V20) 11912 .Case("{v21}", RISCV::V21) 11913 .Case("{v22}", RISCV::V22) 11914 .Case("{v23}", RISCV::V23) 11915 .Case("{v24}", RISCV::V24) 11916 .Case("{v25}", RISCV::V25) 11917 .Case("{v26}", RISCV::V26) 11918 .Case("{v27}", RISCV::V27) 11919 .Case("{v28}", RISCV::V28) 11920 .Case("{v29}", RISCV::V29) 11921 .Case("{v30}", RISCV::V30) 11922 .Case("{v31}", RISCV::V31) 11923 .Default(RISCV::NoRegister); 11924 if (VReg != RISCV::NoRegister) { 11925 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11926 return std::make_pair(VReg, &RISCV::VMRegClass); 11927 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11928 return std::make_pair(VReg, &RISCV::VRRegClass); 11929 for (const auto *RC : 11930 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11931 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11932 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11933 return std::make_pair(VReg, RC); 11934 } 11935 } 11936 } 11937 } 11938 11939 std::pair<Register, const TargetRegisterClass *> Res = 11940 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11941 11942 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11943 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11944 // Subtarget into account. 11945 if (Res.second == &RISCV::GPRF16RegClass || 11946 Res.second == &RISCV::GPRF32RegClass || 11947 Res.second == &RISCV::GPRF64RegClass) 11948 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11949 11950 return Res; 11951 } 11952 11953 unsigned 11954 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11955 // Currently only support length 1 constraints. 11956 if (ConstraintCode.size() == 1) { 11957 switch (ConstraintCode[0]) { 11958 case 'A': 11959 return InlineAsm::Constraint_A; 11960 default: 11961 break; 11962 } 11963 } 11964 11965 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11966 } 11967 11968 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11969 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11970 SelectionDAG &DAG) const { 11971 // Currently only support length 1 constraints. 11972 if (Constraint.length() == 1) { 11973 switch (Constraint[0]) { 11974 case 'I': 11975 // Validate & create a 12-bit signed immediate operand. 11976 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11977 uint64_t CVal = C->getSExtValue(); 11978 if (isInt<12>(CVal)) 11979 Ops.push_back( 11980 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11981 } 11982 return; 11983 case 'J': 11984 // Validate & create an integer zero operand. 11985 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11986 if (C->getZExtValue() == 0) 11987 Ops.push_back( 11988 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11989 return; 11990 case 'K': 11991 // Validate & create a 5-bit unsigned immediate operand. 11992 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11993 uint64_t CVal = C->getZExtValue(); 11994 if (isUInt<5>(CVal)) 11995 Ops.push_back( 11996 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11997 } 11998 return; 11999 case 'S': 12000 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 12001 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 12002 GA->getValueType(0))); 12003 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 12004 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 12005 BA->getValueType(0))); 12006 } 12007 return; 12008 default: 12009 break; 12010 } 12011 } 12012 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 12013 } 12014 12015 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 12016 Instruction *Inst, 12017 AtomicOrdering Ord) const { 12018 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 12019 return Builder.CreateFence(Ord); 12020 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 12021 return Builder.CreateFence(AtomicOrdering::Release); 12022 return nullptr; 12023 } 12024 12025 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 12026 Instruction *Inst, 12027 AtomicOrdering Ord) const { 12028 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 12029 return Builder.CreateFence(AtomicOrdering::Acquire); 12030 return nullptr; 12031 } 12032 12033 TargetLowering::AtomicExpansionKind 12034 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 12035 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 12036 // point operations can't be used in an lr/sc sequence without breaking the 12037 // forward-progress guarantee. 12038 if (AI->isFloatingPointOperation()) 12039 return AtomicExpansionKind::CmpXChg; 12040 12041 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 12042 if (Size == 8 || Size == 16) 12043 return AtomicExpansionKind::MaskedIntrinsic; 12044 return AtomicExpansionKind::None; 12045 } 12046 12047 static Intrinsic::ID 12048 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 12049 if (XLen == 32) { 12050 switch (BinOp) { 12051 default: 12052 llvm_unreachable("Unexpected AtomicRMW BinOp"); 12053 case AtomicRMWInst::Xchg: 12054 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 12055 case AtomicRMWInst::Add: 12056 return Intrinsic::riscv_masked_atomicrmw_add_i32; 12057 case AtomicRMWInst::Sub: 12058 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 12059 case AtomicRMWInst::Nand: 12060 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 12061 case AtomicRMWInst::Max: 12062 return Intrinsic::riscv_masked_atomicrmw_max_i32; 12063 case AtomicRMWInst::Min: 12064 return Intrinsic::riscv_masked_atomicrmw_min_i32; 12065 case AtomicRMWInst::UMax: 12066 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 12067 case AtomicRMWInst::UMin: 12068 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 12069 } 12070 } 12071 12072 if (XLen == 64) { 12073 switch (BinOp) { 12074 default: 12075 llvm_unreachable("Unexpected AtomicRMW BinOp"); 12076 case AtomicRMWInst::Xchg: 12077 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 12078 case AtomicRMWInst::Add: 12079 return Intrinsic::riscv_masked_atomicrmw_add_i64; 12080 case AtomicRMWInst::Sub: 12081 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 12082 case AtomicRMWInst::Nand: 12083 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 12084 case AtomicRMWInst::Max: 12085 return Intrinsic::riscv_masked_atomicrmw_max_i64; 12086 case AtomicRMWInst::Min: 12087 return Intrinsic::riscv_masked_atomicrmw_min_i64; 12088 case AtomicRMWInst::UMax: 12089 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 12090 case AtomicRMWInst::UMin: 12091 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 12092 } 12093 } 12094 12095 llvm_unreachable("Unexpected XLen\n"); 12096 } 12097 12098 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 12099 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 12100 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 12101 unsigned XLen = Subtarget.getXLen(); 12102 Value *Ordering = 12103 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 12104 Type *Tys[] = {AlignedAddr->getType()}; 12105 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 12106 AI->getModule(), 12107 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 12108 12109 if (XLen == 64) { 12110 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 12111 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 12112 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 12113 } 12114 12115 Value *Result; 12116 12117 // Must pass the shift amount needed to sign extend the loaded value prior 12118 // to performing a signed comparison for min/max. ShiftAmt is the number of 12119 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 12120 // is the number of bits to left+right shift the value in order to 12121 // sign-extend. 12122 if (AI->getOperation() == AtomicRMWInst::Min || 12123 AI->getOperation() == AtomicRMWInst::Max) { 12124 const DataLayout &DL = AI->getModule()->getDataLayout(); 12125 unsigned ValWidth = 12126 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 12127 Value *SextShamt = 12128 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 12129 Result = Builder.CreateCall(LrwOpScwLoop, 12130 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 12131 } else { 12132 Result = 12133 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 12134 } 12135 12136 if (XLen == 64) 12137 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 12138 return Result; 12139 } 12140 12141 TargetLowering::AtomicExpansionKind 12142 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 12143 AtomicCmpXchgInst *CI) const { 12144 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 12145 if (Size == 8 || Size == 16) 12146 return AtomicExpansionKind::MaskedIntrinsic; 12147 return AtomicExpansionKind::None; 12148 } 12149 12150 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 12151 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 12152 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 12153 unsigned XLen = Subtarget.getXLen(); 12154 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 12155 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 12156 if (XLen == 64) { 12157 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 12158 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 12159 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 12160 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 12161 } 12162 Type *Tys[] = {AlignedAddr->getType()}; 12163 Function *MaskedCmpXchg = 12164 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 12165 Value *Result = Builder.CreateCall( 12166 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 12167 if (XLen == 64) 12168 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 12169 return Result; 12170 } 12171 12172 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT, 12173 EVT DataVT) const { 12174 return false; 12175 } 12176 12177 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 12178 EVT VT) const { 12179 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 12180 return false; 12181 12182 switch (FPVT.getSimpleVT().SimpleTy) { 12183 case MVT::f16: 12184 return Subtarget.hasStdExtZfh(); 12185 case MVT::f32: 12186 return Subtarget.hasStdExtF(); 12187 case MVT::f64: 12188 return Subtarget.hasStdExtD(); 12189 default: 12190 return false; 12191 } 12192 } 12193 12194 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 12195 // If we are using the small code model, we can reduce size of jump table 12196 // entry to 4 bytes. 12197 if (Subtarget.is64Bit() && !isPositionIndependent() && 12198 getTargetMachine().getCodeModel() == CodeModel::Small) { 12199 return MachineJumpTableInfo::EK_Custom32; 12200 } 12201 return TargetLowering::getJumpTableEncoding(); 12202 } 12203 12204 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 12205 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 12206 unsigned uid, MCContext &Ctx) const { 12207 assert(Subtarget.is64Bit() && !isPositionIndependent() && 12208 getTargetMachine().getCodeModel() == CodeModel::Small); 12209 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 12210 } 12211 12212 bool RISCVTargetLowering::isVScaleKnownToBeAPowerOfTwo() const { 12213 // We define vscale to be VLEN/RVVBitsPerBlock. VLEN is always a power 12214 // of two >= 64, and RVVBitsPerBlock is 64. Thus, vscale must be 12215 // a power of two as well. 12216 // FIXME: This doesn't work for zve32, but that's already broken 12217 // elsewhere for the same reason. 12218 assert(Subtarget.getRealMinVLen() >= 64 && "zve32* unsupported"); 12219 static_assert(RISCV::RVVBitsPerBlock == 64, 12220 "RVVBitsPerBlock changed, audit needed"); 12221 return true; 12222 } 12223 12224 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 12225 EVT VT) const { 12226 VT = VT.getScalarType(); 12227 12228 if (!VT.isSimple()) 12229 return false; 12230 12231 switch (VT.getSimpleVT().SimpleTy) { 12232 case MVT::f16: 12233 return Subtarget.hasStdExtZfh(); 12234 case MVT::f32: 12235 return Subtarget.hasStdExtF(); 12236 case MVT::f64: 12237 return Subtarget.hasStdExtD(); 12238 default: 12239 break; 12240 } 12241 12242 return false; 12243 } 12244 12245 Register RISCVTargetLowering::getExceptionPointerRegister( 12246 const Constant *PersonalityFn) const { 12247 return RISCV::X10; 12248 } 12249 12250 Register RISCVTargetLowering::getExceptionSelectorRegister( 12251 const Constant *PersonalityFn) const { 12252 return RISCV::X11; 12253 } 12254 12255 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 12256 // Return false to suppress the unnecessary extensions if the LibCall 12257 // arguments or return value is f32 type for LP64 ABI. 12258 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 12259 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 12260 return false; 12261 12262 return true; 12263 } 12264 12265 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 12266 if (Subtarget.is64Bit() && Type == MVT::i32) 12267 return true; 12268 12269 return IsSigned; 12270 } 12271 12272 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 12273 SDValue C) const { 12274 // Check integral scalar types. 12275 const bool HasExtMOrZmmul = 12276 Subtarget.hasStdExtM() || Subtarget.hasStdExtZmmul(); 12277 if (VT.isScalarInteger()) { 12278 // Omit the optimization if the sub target has the M extension and the data 12279 // size exceeds XLen. 12280 if (HasExtMOrZmmul && VT.getSizeInBits() > Subtarget.getXLen()) 12281 return false; 12282 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 12283 // Break the MUL to a SLLI and an ADD/SUB. 12284 const APInt &Imm = ConstNode->getAPIntValue(); 12285 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 12286 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 12287 return true; 12288 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 12289 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 12290 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 12291 (Imm - 8).isPowerOf2())) 12292 return true; 12293 // Omit the following optimization if the sub target has the M extension 12294 // and the data size >= XLen. 12295 if (HasExtMOrZmmul && VT.getSizeInBits() >= Subtarget.getXLen()) 12296 return false; 12297 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 12298 // a pair of LUI/ADDI. 12299 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 12300 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 12301 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 12302 (1 - ImmS).isPowerOf2()) 12303 return true; 12304 } 12305 } 12306 } 12307 12308 return false; 12309 } 12310 12311 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 12312 SDValue ConstNode) const { 12313 // Let the DAGCombiner decide for vectors. 12314 EVT VT = AddNode.getValueType(); 12315 if (VT.isVector()) 12316 return true; 12317 12318 // Let the DAGCombiner decide for larger types. 12319 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 12320 return true; 12321 12322 // It is worse if c1 is simm12 while c1*c2 is not. 12323 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 12324 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 12325 const APInt &C1 = C1Node->getAPIntValue(); 12326 const APInt &C2 = C2Node->getAPIntValue(); 12327 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 12328 return false; 12329 12330 // Default to true and let the DAGCombiner decide. 12331 return true; 12332 } 12333 12334 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 12335 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 12336 bool *Fast) const { 12337 if (!VT.isVector()) { 12338 if (Fast) 12339 *Fast = false; 12340 return Subtarget.enableUnalignedScalarMem(); 12341 } 12342 12343 // All vector implementations must support element alignment 12344 EVT ElemVT = VT.getVectorElementType(); 12345 if (Alignment >= ElemVT.getStoreSize()) { 12346 if (Fast) 12347 *Fast = true; 12348 return true; 12349 } 12350 12351 return false; 12352 } 12353 12354 bool RISCVTargetLowering::splitValueIntoRegisterParts( 12355 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 12356 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 12357 bool IsABIRegCopy = CC.has_value(); 12358 EVT ValueVT = Val.getValueType(); 12359 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 12360 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 12361 // and cast to f32. 12362 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 12363 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 12364 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 12365 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 12366 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 12367 Parts[0] = Val; 12368 return true; 12369 } 12370 12371 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 12372 LLVMContext &Context = *DAG.getContext(); 12373 EVT ValueEltVT = ValueVT.getVectorElementType(); 12374 EVT PartEltVT = PartVT.getVectorElementType(); 12375 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 12376 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 12377 if (PartVTBitSize % ValueVTBitSize == 0) { 12378 assert(PartVTBitSize >= ValueVTBitSize); 12379 // If the element types are different, bitcast to the same element type of 12380 // PartVT first. 12381 // Give an example here, we want copy a <vscale x 1 x i8> value to 12382 // <vscale x 4 x i16>. 12383 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 12384 // subvector, then we can bitcast to <vscale x 4 x i16>. 12385 if (ValueEltVT != PartEltVT) { 12386 if (PartVTBitSize > ValueVTBitSize) { 12387 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 12388 assert(Count != 0 && "The number of element should not be zero."); 12389 EVT SameEltTypeVT = 12390 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 12391 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 12392 DAG.getUNDEF(SameEltTypeVT), Val, 12393 DAG.getVectorIdxConstant(0, DL)); 12394 } 12395 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 12396 } else { 12397 Val = 12398 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 12399 Val, DAG.getVectorIdxConstant(0, DL)); 12400 } 12401 Parts[0] = Val; 12402 return true; 12403 } 12404 } 12405 return false; 12406 } 12407 12408 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 12409 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 12410 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 12411 bool IsABIRegCopy = CC.has_value(); 12412 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 12413 SDValue Val = Parts[0]; 12414 12415 // Cast the f32 to i32, truncate to i16, and cast back to f16. 12416 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 12417 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 12418 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 12419 return Val; 12420 } 12421 12422 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 12423 LLVMContext &Context = *DAG.getContext(); 12424 SDValue Val = Parts[0]; 12425 EVT ValueEltVT = ValueVT.getVectorElementType(); 12426 EVT PartEltVT = PartVT.getVectorElementType(); 12427 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 12428 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 12429 if (PartVTBitSize % ValueVTBitSize == 0) { 12430 assert(PartVTBitSize >= ValueVTBitSize); 12431 EVT SameEltTypeVT = ValueVT; 12432 // If the element types are different, convert it to the same element type 12433 // of PartVT. 12434 // Give an example here, we want copy a <vscale x 1 x i8> value from 12435 // <vscale x 4 x i16>. 12436 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 12437 // then we can extract <vscale x 1 x i8>. 12438 if (ValueEltVT != PartEltVT) { 12439 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 12440 assert(Count != 0 && "The number of element should not be zero."); 12441 SameEltTypeVT = 12442 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 12443 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 12444 } 12445 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 12446 DAG.getVectorIdxConstant(0, DL)); 12447 return Val; 12448 } 12449 } 12450 return SDValue(); 12451 } 12452 12453 SDValue 12454 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 12455 SelectionDAG &DAG, 12456 SmallVectorImpl<SDNode *> &Created) const { 12457 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 12458 if (isIntDivCheap(N->getValueType(0), Attr)) 12459 return SDValue(N, 0); // Lower SDIV as SDIV 12460 12461 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 12462 "Unexpected divisor!"); 12463 12464 // Conditional move is needed, so do the transformation iff Zbt is enabled. 12465 if (!Subtarget.hasStdExtZbt()) 12466 return SDValue(); 12467 12468 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 12469 // Besides, more critical path instructions will be generated when dividing 12470 // by 2. So we keep using the original DAGs for these cases. 12471 unsigned Lg2 = Divisor.countTrailingZeros(); 12472 if (Lg2 == 1 || Lg2 >= 12) 12473 return SDValue(); 12474 12475 // fold (sdiv X, pow2) 12476 EVT VT = N->getValueType(0); 12477 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 12478 return SDValue(); 12479 12480 SDLoc DL(N); 12481 SDValue N0 = N->getOperand(0); 12482 SDValue Zero = DAG.getConstant(0, DL, VT); 12483 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 12484 12485 // Add (N0 < 0) ? Pow2 - 1 : 0; 12486 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 12487 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 12488 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 12489 12490 Created.push_back(Cmp.getNode()); 12491 Created.push_back(Add.getNode()); 12492 Created.push_back(Sel.getNode()); 12493 12494 // Divide by pow2. 12495 SDValue SRA = 12496 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 12497 12498 // If we're dividing by a positive value, we're done. Otherwise, we must 12499 // negate the result. 12500 if (Divisor.isNonNegative()) 12501 return SRA; 12502 12503 Created.push_back(SRA.getNode()); 12504 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 12505 } 12506 12507 #define GET_REGISTER_MATCHER 12508 #include "RISCVGenAsmMatcher.inc" 12509 12510 Register 12511 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 12512 const MachineFunction &MF) const { 12513 Register Reg = MatchRegisterAltName(RegName); 12514 if (Reg == RISCV::NoRegister) 12515 Reg = MatchRegisterName(RegName); 12516 if (Reg == RISCV::NoRegister) 12517 report_fatal_error( 12518 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 12519 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 12520 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 12521 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 12522 StringRef(RegName) + "\".")); 12523 return Reg; 12524 } 12525 12526 namespace llvm { 12527 namespace RISCVVIntrinsicsTable { 12528 12529 #define GET_RISCVVIntrinsicsTable_IMPL 12530 #include "RISCVGenSearchableTables.inc" 12531 12532 } // namespace RISCVVIntrinsicsTable 12533 12534 } // namespace llvm 12535