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 unsigned Size = VT.getSizeInBits().getKnownMinValue(); 116 assert(Size <= 512 && isPowerOf2_32(Size)); 117 const TargetRegisterClass *RC; 118 if (Size <= 64) 119 RC = &RISCV::VRRegClass; 120 else if (Size == 128) 121 RC = &RISCV::VRM2RegClass; 122 else if (Size == 256) 123 RC = &RISCV::VRM4RegClass; 124 else 125 RC = &RISCV::VRM8RegClass; 126 127 addRegisterClass(VT, RC); 128 }; 129 130 for (MVT VT : BoolVecVTs) 131 addRegClassForRVV(VT); 132 for (MVT VT : IntVecVTs) { 133 if (VT.getVectorElementType() == MVT::i64 && 134 !Subtarget.hasVInstructionsI64()) 135 continue; 136 addRegClassForRVV(VT); 137 } 138 139 if (Subtarget.hasVInstructionsF16()) 140 for (MVT VT : F16VecVTs) 141 addRegClassForRVV(VT); 142 143 if (Subtarget.hasVInstructionsF32()) 144 for (MVT VT : F32VecVTs) 145 addRegClassForRVV(VT); 146 147 if (Subtarget.hasVInstructionsF64()) 148 for (MVT VT : F64VecVTs) 149 addRegClassForRVV(VT); 150 151 if (Subtarget.useRVVForFixedLengthVectors()) { 152 auto addRegClassForFixedVectors = [this](MVT VT) { 153 MVT ContainerVT = getContainerForFixedLengthVector(VT); 154 unsigned RCID = getRegClassIDForVecVT(ContainerVT); 155 const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo(); 156 addRegisterClass(VT, TRI.getRegClass(RCID)); 157 }; 158 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) 159 if (useRVVForFixedLengthVectorVT(VT)) 160 addRegClassForFixedVectors(VT); 161 162 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) 163 if (useRVVForFixedLengthVectorVT(VT)) 164 addRegClassForFixedVectors(VT); 165 } 166 } 167 168 // Compute derived properties from the register classes. 169 computeRegisterProperties(STI.getRegisterInfo()); 170 171 setStackPointerRegisterToSaveRestore(RISCV::X2); 172 173 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, XLenVT, 174 MVT::i1, Promote); 175 176 // TODO: add all necessary setOperationAction calls. 177 setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand); 178 179 setOperationAction(ISD::BR_JT, MVT::Other, Expand); 180 setOperationAction(ISD::BR_CC, XLenVT, Expand); 181 setOperationAction(ISD::BRCOND, MVT::Other, Custom); 182 setOperationAction(ISD::SELECT_CC, XLenVT, Expand); 183 184 setOperationAction({ISD::STACKSAVE, ISD::STACKRESTORE}, MVT::Other, Expand); 185 186 setOperationAction(ISD::VASTART, MVT::Other, Custom); 187 setOperationAction({ISD::VAARG, ISD::VACOPY, ISD::VAEND}, MVT::Other, Expand); 188 189 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand); 190 191 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom); 192 193 if (!Subtarget.hasStdExtZbb()) 194 setOperationAction(ISD::SIGN_EXTEND_INREG, {MVT::i8, MVT::i16}, Expand); 195 196 if (Subtarget.is64Bit()) { 197 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom); 198 199 setOperationAction({ISD::ADD, ISD::SUB, ISD::SHL, ISD::SRA, ISD::SRL}, 200 MVT::i32, Custom); 201 202 setOperationAction({ISD::UADDO, ISD::USUBO, ISD::UADDSAT, ISD::USUBSAT}, 203 MVT::i32, Custom); 204 } else { 205 setLibcallName( 206 {RTLIB::SHL_I128, RTLIB::SRL_I128, RTLIB::SRA_I128, RTLIB::MUL_I128}, 207 nullptr); 208 setLibcallName(RTLIB::MULO_I64, nullptr); 209 } 210 211 if (!Subtarget.hasStdExtM()) { 212 setOperationAction({ISD::MUL, ISD::MULHS, ISD::MULHU, ISD::SDIV, ISD::UDIV, 213 ISD::SREM, ISD::UREM}, 214 XLenVT, Expand); 215 } else { 216 if (Subtarget.is64Bit()) { 217 setOperationAction(ISD::MUL, {MVT::i32, MVT::i128}, Custom); 218 219 setOperationAction({ISD::SDIV, ISD::UDIV, ISD::UREM}, 220 {MVT::i8, MVT::i16, MVT::i32}, Custom); 221 } else { 222 setOperationAction(ISD::MUL, MVT::i64, Custom); 223 } 224 } 225 226 setOperationAction( 227 {ISD::SDIVREM, ISD::UDIVREM, ISD::SMUL_LOHI, ISD::UMUL_LOHI}, XLenVT, 228 Expand); 229 230 setOperationAction({ISD::SHL_PARTS, ISD::SRL_PARTS, ISD::SRA_PARTS}, XLenVT, 231 Custom); 232 233 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 234 Subtarget.hasStdExtZbkb()) { 235 if (Subtarget.is64Bit()) 236 setOperationAction({ISD::ROTL, ISD::ROTR}, MVT::i32, Custom); 237 } else { 238 setOperationAction({ISD::ROTL, ISD::ROTR}, XLenVT, Expand); 239 } 240 241 if (Subtarget.hasStdExtZbp()) { 242 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 243 // more combining. 244 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, XLenVT, Custom); 245 246 // BSWAP i8 doesn't exist. 247 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 248 249 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i16, Custom); 250 251 if (Subtarget.is64Bit()) 252 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i32, Custom); 253 } else { 254 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 255 // pattern match it directly in isel. 256 setOperationAction(ISD::BSWAP, XLenVT, 257 (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) 258 ? Legal 259 : Expand); 260 // Zbkb can use rev8+brev8 to implement bitreverse. 261 setOperationAction(ISD::BITREVERSE, XLenVT, 262 Subtarget.hasStdExtZbkb() ? Custom : Expand); 263 } 264 265 if (Subtarget.hasStdExtZbb()) { 266 setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, XLenVT, 267 Legal); 268 269 if (Subtarget.is64Bit()) 270 setOperationAction( 271 {ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF}, 272 MVT::i32, Custom); 273 } else { 274 setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP}, XLenVT, Expand); 275 276 if (Subtarget.is64Bit()) 277 setOperationAction(ISD::ABS, MVT::i32, Custom); 278 } 279 280 if (Subtarget.hasStdExtZbt()) { 281 setOperationAction({ISD::FSHL, ISD::FSHR}, XLenVT, Custom); 282 setOperationAction(ISD::SELECT, XLenVT, Legal); 283 284 if (Subtarget.is64Bit()) 285 setOperationAction({ISD::FSHL, ISD::FSHR}, MVT::i32, Custom); 286 } else { 287 setOperationAction(ISD::SELECT, XLenVT, Custom); 288 } 289 290 static constexpr ISD::NodeType FPLegalNodeTypes[] = { 291 ISD::FMINNUM, ISD::FMAXNUM, ISD::LRINT, 292 ISD::LLRINT, ISD::LROUND, ISD::LLROUND, 293 ISD::STRICT_LRINT, ISD::STRICT_LLRINT, ISD::STRICT_LROUND, 294 ISD::STRICT_LLROUND, ISD::STRICT_FMA, ISD::STRICT_FADD, 295 ISD::STRICT_FSUB, ISD::STRICT_FMUL, ISD::STRICT_FDIV, 296 ISD::STRICT_FSQRT, ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS}; 297 298 static const ISD::CondCode FPCCToExpand[] = { 299 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 300 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 301 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 302 303 static const ISD::NodeType FPOpToExpand[] = { 304 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 305 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 306 307 if (Subtarget.hasStdExtZfh()) 308 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 309 310 if (Subtarget.hasStdExtZfh()) { 311 for (auto NT : FPLegalNodeTypes) 312 setOperationAction(NT, MVT::f16, Legal); 313 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 314 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 315 setCondCodeAction(FPCCToExpand, MVT::f16, Expand); 316 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 317 setOperationAction(ISD::SELECT, MVT::f16, Custom); 318 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 319 320 setOperationAction({ISD::FREM, ISD::FCEIL, ISD::FFLOOR, ISD::FNEARBYINT, 321 ISD::FRINT, ISD::FROUND, ISD::FROUNDEVEN, ISD::FTRUNC, 322 ISD::FPOW, ISD::FPOWI, ISD::FCOS, ISD::FSIN, 323 ISD::FSINCOS, ISD::FEXP, ISD::FEXP2, ISD::FLOG, 324 ISD::FLOG2, ISD::FLOG10}, 325 MVT::f16, Promote); 326 327 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 328 // complete support for all operations in LegalizeDAG. 329 330 // We need to custom promote this. 331 if (Subtarget.is64Bit()) 332 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 333 } 334 335 if (Subtarget.hasStdExtF()) { 336 for (auto NT : FPLegalNodeTypes) 337 setOperationAction(NT, MVT::f32, Legal); 338 setCondCodeAction(FPCCToExpand, MVT::f32, Expand); 339 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 340 setOperationAction(ISD::SELECT, MVT::f32, Custom); 341 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 342 for (auto Op : FPOpToExpand) 343 setOperationAction(Op, MVT::f32, Expand); 344 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 345 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 346 } 347 348 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 349 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 350 351 if (Subtarget.hasStdExtD()) { 352 for (auto NT : FPLegalNodeTypes) 353 setOperationAction(NT, MVT::f64, Legal); 354 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 355 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 356 setCondCodeAction(FPCCToExpand, MVT::f64, Expand); 357 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 358 setOperationAction(ISD::SELECT, MVT::f64, Custom); 359 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 360 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 361 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 362 for (auto Op : FPOpToExpand) 363 setOperationAction(Op, MVT::f64, Expand); 364 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 365 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 366 } 367 368 if (Subtarget.is64Bit()) 369 setOperationAction({ISD::FP_TO_UINT, ISD::FP_TO_SINT, 370 ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT}, 371 MVT::i32, Custom); 372 373 if (Subtarget.hasStdExtF()) { 374 setOperationAction({ISD::FP_TO_UINT_SAT, ISD::FP_TO_SINT_SAT}, XLenVT, 375 Custom); 376 377 setOperationAction({ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT, 378 ISD::STRICT_UINT_TO_FP, ISD::STRICT_SINT_TO_FP}, 379 XLenVT, Legal); 380 381 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 382 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 383 } 384 385 setOperationAction({ISD::GlobalAddress, ISD::BlockAddress, ISD::ConstantPool, 386 ISD::JumpTable}, 387 XLenVT, Custom); 388 389 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 390 391 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 392 // Unfortunately this can't be determined just from the ISA naming string. 393 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 394 Subtarget.is64Bit() ? Legal : Custom); 395 396 setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Legal); 397 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 398 if (Subtarget.is64Bit()) 399 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 400 401 if (Subtarget.hasStdExtA()) { 402 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 403 setMinCmpXchgSizeInBits(32); 404 } else { 405 setMaxAtomicSizeInBitsSupported(0); 406 } 407 408 setBooleanContents(ZeroOrOneBooleanContent); 409 410 if (Subtarget.hasVInstructions()) { 411 setBooleanVectorContents(ZeroOrOneBooleanContent); 412 413 setOperationAction(ISD::VSCALE, XLenVT, Custom); 414 415 // RVV intrinsics may have illegal operands. 416 // We also need to custom legalize vmv.x.s. 417 setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN}, 418 {MVT::i8, MVT::i16}, Custom); 419 if (Subtarget.is64Bit()) 420 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 421 else 422 setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN}, 423 MVT::i64, Custom); 424 425 setOperationAction({ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID}, 426 MVT::Other, Custom); 427 428 static const unsigned IntegerVPOps[] = { 429 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 430 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 431 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 432 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 433 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 434 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 435 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 436 ISD::VP_MERGE, ISD::VP_SELECT, ISD::VP_FPTOSI, 437 ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_SIGN_EXTEND, 438 ISD::VP_ZERO_EXTEND, ISD::VP_TRUNCATE}; 439 440 static const unsigned FloatingPointVPOps[] = { 441 ISD::VP_FADD, ISD::VP_FSUB, 442 ISD::VP_FMUL, ISD::VP_FDIV, 443 ISD::VP_FNEG, ISD::VP_FMA, 444 ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 445 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, 446 ISD::VP_MERGE, ISD::VP_SELECT, 447 ISD::VP_SITOFP, ISD::VP_UITOFP, 448 ISD::VP_SETCC, ISD::VP_FP_ROUND, 449 ISD::VP_FP_EXTEND}; 450 451 if (!Subtarget.is64Bit()) { 452 // We must custom-lower certain vXi64 operations on RV32 due to the vector 453 // element type being illegal. 454 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 455 MVT::i64, Custom); 456 457 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, 458 ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR, 459 ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 460 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}, 461 MVT::i64, Custom); 462 463 setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 464 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, 465 ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN, 466 ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN}, 467 MVT::i64, Custom); 468 } 469 470 for (MVT VT : BoolVecVTs) { 471 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 472 473 // Mask VTs are custom-expanded into a series of standard nodes 474 setOperationAction({ISD::TRUNCATE, ISD::CONCAT_VECTORS, 475 ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 476 VT, Custom); 477 478 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 479 Custom); 480 481 setOperationAction(ISD::SELECT, VT, Custom); 482 setOperationAction( 483 {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT, 484 Expand); 485 486 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom); 487 488 setOperationAction( 489 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 490 Custom); 491 492 setOperationAction( 493 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 494 Custom); 495 496 // RVV has native int->float & float->int conversions where the 497 // element type sizes are within one power-of-two of each other. Any 498 // wider distances between type sizes have to be lowered as sequences 499 // which progressively narrow the gap in stages. 500 setOperationAction( 501 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 502 VT, Custom); 503 504 // Expand all extending loads to types larger than this, and truncating 505 // stores from types larger than this. 506 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 507 setTruncStoreAction(OtherVT, VT, Expand); 508 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 509 VT, Expand); 510 } 511 512 setOperationAction( 513 {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_TRUNCATE, ISD::VP_SETCC}, VT, 514 Custom); 515 } 516 517 for (MVT VT : IntVecVTs) { 518 if (VT.getVectorElementType() == MVT::i64 && 519 !Subtarget.hasVInstructionsI64()) 520 continue; 521 522 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 523 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 524 525 // Vectors implement MULHS/MULHU. 526 setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand); 527 528 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 529 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) 530 setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand); 531 532 setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT, 533 Legal); 534 535 setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand); 536 537 setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP, ISD::BSWAP}, VT, 538 Expand); 539 540 setOperationAction(ISD::BSWAP, VT, Expand); 541 542 // Custom-lower extensions and truncations from/to mask types. 543 setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, 544 VT, Custom); 545 546 // RVV has native int->float & float->int conversions where the 547 // element type sizes are within one power-of-two of each other. Any 548 // wider distances between type sizes have to be lowered as sequences 549 // which progressively narrow the gap in stages. 550 setOperationAction( 551 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 552 VT, Custom); 553 554 setOperationAction( 555 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal); 556 557 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 558 // nodes which truncate by one power of two at a time. 559 setOperationAction(ISD::TRUNCATE, VT, Custom); 560 561 // Custom-lower insert/extract operations to simplify patterns. 562 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 563 Custom); 564 565 // Custom-lower reduction operations to set up the corresponding custom 566 // nodes' operands. 567 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, 568 ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR, 569 ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 570 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}, 571 VT, Custom); 572 573 setOperationAction(IntegerVPOps, VT, Custom); 574 575 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 576 577 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 578 VT, Custom); 579 580 setOperationAction( 581 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 582 Custom); 583 584 setOperationAction( 585 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 586 VT, Custom); 587 588 setOperationAction(ISD::SELECT, VT, Custom); 589 setOperationAction(ISD::SELECT_CC, VT, Expand); 590 591 setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom); 592 593 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 594 setTruncStoreAction(VT, OtherVT, Expand); 595 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 596 VT, Expand); 597 } 598 599 // Splice 600 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 601 602 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 603 // type that can represent the value exactly. 604 if (VT.getVectorElementType() != MVT::i64) { 605 MVT FloatEltVT = 606 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 607 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 608 if (isTypeLegal(FloatVT)) { 609 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 610 Custom); 611 } 612 } 613 } 614 615 // Expand various CCs to best match the RVV ISA, which natively supports UNE 616 // but no other unordered comparisons, and supports all ordered comparisons 617 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 618 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 619 // and we pattern-match those back to the "original", swapping operands once 620 // more. This way we catch both operations and both "vf" and "fv" forms with 621 // fewer patterns. 622 static const ISD::CondCode VFPCCToExpand[] = { 623 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 624 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 625 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 626 }; 627 628 // Sets common operation actions on RVV floating-point vector types. 629 const auto SetCommonVFPActions = [&](MVT VT) { 630 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 631 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 632 // sizes are within one power-of-two of each other. Therefore conversions 633 // between vXf16 and vXf64 must be lowered as sequences which convert via 634 // vXf32. 635 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 636 // Custom-lower insert/extract operations to simplify patterns. 637 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 638 Custom); 639 // Expand various condition codes (explained above). 640 setCondCodeAction(VFPCCToExpand, VT, Expand); 641 642 setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal); 643 644 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 645 VT, Custom); 646 647 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 648 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 649 VT, Custom); 650 651 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 652 653 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 654 655 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 656 VT, Custom); 657 658 setOperationAction( 659 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 660 Custom); 661 662 setOperationAction(ISD::SELECT, VT, Custom); 663 setOperationAction(ISD::SELECT_CC, VT, Expand); 664 665 setOperationAction( 666 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 667 VT, Custom); 668 669 setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom); 670 671 setOperationAction(FloatingPointVPOps, VT, Custom); 672 }; 673 674 // Sets common extload/truncstore actions on RVV floating-point vector 675 // types. 676 const auto SetCommonVFPExtLoadTruncStoreActions = 677 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 678 for (auto SmallVT : SmallerVTs) { 679 setTruncStoreAction(VT, SmallVT, Expand); 680 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 681 } 682 }; 683 684 if (Subtarget.hasVInstructionsF16()) 685 for (MVT VT : F16VecVTs) 686 SetCommonVFPActions(VT); 687 688 for (MVT VT : F32VecVTs) { 689 if (Subtarget.hasVInstructionsF32()) 690 SetCommonVFPActions(VT); 691 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 692 } 693 694 for (MVT VT : F64VecVTs) { 695 if (Subtarget.hasVInstructionsF64()) 696 SetCommonVFPActions(VT); 697 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 698 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 699 } 700 701 if (Subtarget.useRVVForFixedLengthVectors()) { 702 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 703 if (!useRVVForFixedLengthVectorVT(VT)) 704 continue; 705 706 // By default everything must be expanded. 707 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 708 setOperationAction(Op, VT, Expand); 709 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 710 setTruncStoreAction(VT, OtherVT, Expand); 711 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, 712 OtherVT, VT, Expand); 713 } 714 715 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 716 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 717 Custom); 718 719 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT, 720 Custom); 721 722 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 723 VT, Custom); 724 725 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 726 727 setOperationAction(ISD::SETCC, VT, Custom); 728 729 setOperationAction(ISD::SELECT, VT, Custom); 730 731 setOperationAction(ISD::TRUNCATE, VT, Custom); 732 733 setOperationAction(ISD::BITCAST, VT, Custom); 734 735 setOperationAction( 736 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 737 Custom); 738 739 setOperationAction( 740 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 741 Custom); 742 743 setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, 744 ISD::FP_TO_UINT}, 745 VT, Custom); 746 747 // Operations below are different for between masks and other vectors. 748 if (VT.getVectorElementType() == MVT::i1) { 749 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND, 750 ISD::OR, ISD::XOR}, 751 VT, Custom); 752 753 setOperationAction( 754 {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_TRUNCATE}, 755 VT, Custom); 756 continue; 757 } 758 759 // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to 760 // it before type legalization for i64 vectors on RV32. It will then be 761 // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle. 762 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 763 // improvements first. 764 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 765 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 766 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 767 } 768 769 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 770 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 771 772 setOperationAction( 773 {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom); 774 775 setOperationAction( 776 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 777 Custom); 778 779 setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR, 780 ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV, 781 ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL}, 782 VT, Custom); 783 784 setOperationAction( 785 {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom); 786 787 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 788 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) 789 setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom); 790 791 setOperationAction( 792 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, 793 Custom); 794 795 setOperationAction(ISD::VSELECT, VT, Custom); 796 setOperationAction(ISD::SELECT_CC, VT, Expand); 797 798 setOperationAction( 799 {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom); 800 801 // Custom-lower reduction operations to set up the corresponding custom 802 // nodes' operands. 803 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX, 804 ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX, 805 ISD::VECREDUCE_UMIN}, 806 VT, Custom); 807 808 setOperationAction(IntegerVPOps, VT, Custom); 809 810 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 811 // type that can represent the value exactly. 812 if (VT.getVectorElementType() != MVT::i64) { 813 MVT FloatEltVT = 814 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 815 EVT FloatVT = 816 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 817 if (isTypeLegal(FloatVT)) 818 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 819 Custom); 820 } 821 } 822 823 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 824 if (!useRVVForFixedLengthVectorVT(VT)) 825 continue; 826 827 // By default everything must be expanded. 828 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 829 setOperationAction(Op, VT, Expand); 830 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 831 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 832 setTruncStoreAction(VT, OtherVT, Expand); 833 } 834 835 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 836 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 837 Custom); 838 839 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS, 840 ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT, 841 ISD::EXTRACT_VECTOR_ELT}, 842 VT, Custom); 843 844 setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE, 845 ISD::MGATHER, ISD::MSCATTER}, 846 VT, Custom); 847 848 setOperationAction( 849 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 850 Custom); 851 852 setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV, 853 ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT, 854 ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM}, 855 VT, Custom); 856 857 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 858 859 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 860 VT, Custom); 861 862 for (auto CC : VFPCCToExpand) 863 setCondCodeAction(CC, VT, Expand); 864 865 setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom); 866 setOperationAction(ISD::SELECT_CC, VT, Expand); 867 868 setOperationAction(ISD::BITCAST, VT, Custom); 869 870 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 871 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 872 VT, Custom); 873 874 setOperationAction(FloatingPointVPOps, VT, Custom); 875 } 876 877 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 878 setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64}, 879 Custom); 880 if (Subtarget.hasStdExtZfh()) 881 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 882 if (Subtarget.hasStdExtF()) 883 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 884 if (Subtarget.hasStdExtD()) 885 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 886 } 887 } 888 889 // Function alignments. 890 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 891 setMinFunctionAlignment(FunctionAlignment); 892 setPrefFunctionAlignment(FunctionAlignment); 893 894 setMinimumJumpTableEntries(5); 895 896 // Jumps are expensive, compared to logic 897 setJumpIsExpensive(); 898 899 setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND, 900 ISD::OR, ISD::XOR}); 901 902 if (Subtarget.hasStdExtF()) 903 setTargetDAGCombine({ISD::FADD, ISD::FMAXNUM, ISD::FMINNUM}); 904 905 if (Subtarget.hasStdExtZbp()) 906 setTargetDAGCombine({ISD::ROTL, ISD::ROTR}); 907 908 if (Subtarget.hasStdExtZbb()) 909 setTargetDAGCombine({ISD::UMAX, ISD::UMIN, ISD::SMAX, ISD::SMIN}); 910 911 if (Subtarget.hasStdExtZbkb()) 912 setTargetDAGCombine(ISD::BITREVERSE); 913 if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb()) 914 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 915 if (Subtarget.hasStdExtF()) 916 setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT, 917 ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}); 918 if (Subtarget.hasVInstructions()) 919 setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER, 920 ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL, 921 ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR}); 922 923 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 924 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 925 } 926 927 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 928 LLVMContext &Context, 929 EVT VT) const { 930 if (!VT.isVector()) 931 return getPointerTy(DL); 932 if (Subtarget.hasVInstructions() && 933 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 934 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 935 return VT.changeVectorElementTypeToInteger(); 936 } 937 938 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 939 return Subtarget.getXLenVT(); 940 } 941 942 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 943 const CallInst &I, 944 MachineFunction &MF, 945 unsigned Intrinsic) const { 946 auto &DL = I.getModule()->getDataLayout(); 947 switch (Intrinsic) { 948 default: 949 return false; 950 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 951 case Intrinsic::riscv_masked_atomicrmw_add_i32: 952 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 953 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 954 case Intrinsic::riscv_masked_atomicrmw_max_i32: 955 case Intrinsic::riscv_masked_atomicrmw_min_i32: 956 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 957 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 958 case Intrinsic::riscv_masked_cmpxchg_i32: 959 Info.opc = ISD::INTRINSIC_W_CHAIN; 960 Info.memVT = MVT::i32; 961 Info.ptrVal = I.getArgOperand(0); 962 Info.offset = 0; 963 Info.align = Align(4); 964 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 965 MachineMemOperand::MOVolatile; 966 return true; 967 case Intrinsic::riscv_masked_strided_load: 968 Info.opc = ISD::INTRINSIC_W_CHAIN; 969 Info.ptrVal = I.getArgOperand(1); 970 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 971 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 972 Info.size = MemoryLocation::UnknownSize; 973 Info.flags |= MachineMemOperand::MOLoad; 974 return true; 975 case Intrinsic::riscv_masked_strided_store: 976 Info.opc = ISD::INTRINSIC_VOID; 977 Info.ptrVal = I.getArgOperand(1); 978 Info.memVT = 979 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 980 Info.align = Align( 981 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 982 8); 983 Info.size = MemoryLocation::UnknownSize; 984 Info.flags |= MachineMemOperand::MOStore; 985 return true; 986 case Intrinsic::riscv_seg2_load: 987 case Intrinsic::riscv_seg3_load: 988 case Intrinsic::riscv_seg4_load: 989 case Intrinsic::riscv_seg5_load: 990 case Intrinsic::riscv_seg6_load: 991 case Intrinsic::riscv_seg7_load: 992 case Intrinsic::riscv_seg8_load: 993 Info.opc = ISD::INTRINSIC_W_CHAIN; 994 Info.ptrVal = I.getArgOperand(0); 995 Info.memVT = 996 getValueType(DL, I.getType()->getStructElementType(0)->getScalarType()); 997 Info.align = 998 Align(DL.getTypeSizeInBits( 999 I.getType()->getStructElementType(0)->getScalarType()) / 1000 8); 1001 Info.size = MemoryLocation::UnknownSize; 1002 Info.flags |= MachineMemOperand::MOLoad; 1003 return true; 1004 } 1005 } 1006 1007 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1008 const AddrMode &AM, Type *Ty, 1009 unsigned AS, 1010 Instruction *I) const { 1011 // No global is ever allowed as a base. 1012 if (AM.BaseGV) 1013 return false; 1014 1015 // RVV instructions only support register addressing. 1016 if (Subtarget.hasVInstructions() && isa<VectorType>(Ty)) 1017 return AM.HasBaseReg && AM.Scale == 0 && !AM.BaseOffs; 1018 1019 // Require a 12-bit signed offset. 1020 if (!isInt<12>(AM.BaseOffs)) 1021 return false; 1022 1023 switch (AM.Scale) { 1024 case 0: // "r+i" or just "i", depending on HasBaseReg. 1025 break; 1026 case 1: 1027 if (!AM.HasBaseReg) // allow "r+i". 1028 break; 1029 return false; // disallow "r+r" or "r+r+i". 1030 default: 1031 return false; 1032 } 1033 1034 return true; 1035 } 1036 1037 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1038 return isInt<12>(Imm); 1039 } 1040 1041 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1042 return isInt<12>(Imm); 1043 } 1044 1045 // On RV32, 64-bit integers are split into their high and low parts and held 1046 // in two different registers, so the trunc is free since the low register can 1047 // just be used. 1048 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1049 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1050 return false; 1051 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1052 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1053 return (SrcBits == 64 && DestBits == 32); 1054 } 1055 1056 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1057 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1058 !SrcVT.isInteger() || !DstVT.isInteger()) 1059 return false; 1060 unsigned SrcBits = SrcVT.getSizeInBits(); 1061 unsigned DestBits = DstVT.getSizeInBits(); 1062 return (SrcBits == 64 && DestBits == 32); 1063 } 1064 1065 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1066 // Zexts are free if they can be combined with a load. 1067 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1068 // poorly with type legalization of compares preferring sext. 1069 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1070 EVT MemVT = LD->getMemoryVT(); 1071 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1072 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1073 LD->getExtensionType() == ISD::ZEXTLOAD)) 1074 return true; 1075 } 1076 1077 return TargetLowering::isZExtFree(Val, VT2); 1078 } 1079 1080 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1081 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1082 } 1083 1084 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const { 1085 return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32); 1086 } 1087 1088 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1089 return Subtarget.hasStdExtZbb(); 1090 } 1091 1092 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1093 return Subtarget.hasStdExtZbb(); 1094 } 1095 1096 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1097 EVT VT = Y.getValueType(); 1098 1099 // FIXME: Support vectors once we have tests. 1100 if (VT.isVector()) 1101 return false; 1102 1103 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1104 Subtarget.hasStdExtZbkb()) && 1105 !isa<ConstantSDNode>(Y); 1106 } 1107 1108 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const { 1109 // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position. 1110 auto *C = dyn_cast<ConstantSDNode>(Y); 1111 return C && C->getAPIntValue().ule(10); 1112 } 1113 1114 bool RISCVTargetLowering:: 1115 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 1116 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y, 1117 unsigned OldShiftOpcode, unsigned NewShiftOpcode, 1118 SelectionDAG &DAG) const { 1119 // One interesting pattern that we'd want to form is 'bit extract': 1120 // ((1 >> Y) & 1) ==/!= 0 1121 // But we also need to be careful not to try to reverse that fold. 1122 1123 // Is this '((1 >> Y) & 1)'? 1124 if (XC && OldShiftOpcode == ISD::SRL && XC->isOne()) 1125 return false; // Keep the 'bit extract' pattern. 1126 1127 // Will this be '((1 >> Y) & 1)' after the transform? 1128 if (NewShiftOpcode == ISD::SRL && CC->isOne()) 1129 return true; // Do form the 'bit extract' pattern. 1130 1131 // If 'X' is a constant, and we transform, then we will immediately 1132 // try to undo the fold, thus causing endless combine loop. 1133 // So only do the transform if X is not a constant. This matches the default 1134 // implementation of this function. 1135 return !XC; 1136 } 1137 1138 /// Check if sinking \p I's operands to I's basic block is profitable, because 1139 /// the operands can be folded into a target instruction, e.g. 1140 /// splats of scalars can fold into vector instructions. 1141 bool RISCVTargetLowering::shouldSinkOperands( 1142 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1143 using namespace llvm::PatternMatch; 1144 1145 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1146 return false; 1147 1148 auto IsSinker = [&](Instruction *I, int Operand) { 1149 switch (I->getOpcode()) { 1150 case Instruction::Add: 1151 case Instruction::Sub: 1152 case Instruction::Mul: 1153 case Instruction::And: 1154 case Instruction::Or: 1155 case Instruction::Xor: 1156 case Instruction::FAdd: 1157 case Instruction::FSub: 1158 case Instruction::FMul: 1159 case Instruction::FDiv: 1160 case Instruction::ICmp: 1161 case Instruction::FCmp: 1162 return true; 1163 case Instruction::Shl: 1164 case Instruction::LShr: 1165 case Instruction::AShr: 1166 case Instruction::UDiv: 1167 case Instruction::SDiv: 1168 case Instruction::URem: 1169 case Instruction::SRem: 1170 return Operand == 1; 1171 case Instruction::Call: 1172 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1173 switch (II->getIntrinsicID()) { 1174 case Intrinsic::fma: 1175 case Intrinsic::vp_fma: 1176 return Operand == 0 || Operand == 1; 1177 // FIXME: Our patterns can only match vx/vf instructions when the splat 1178 // it on the RHS, because TableGen doesn't recognize our VP operations 1179 // as commutative. 1180 case Intrinsic::vp_add: 1181 case Intrinsic::vp_mul: 1182 case Intrinsic::vp_and: 1183 case Intrinsic::vp_or: 1184 case Intrinsic::vp_xor: 1185 case Intrinsic::vp_fadd: 1186 case Intrinsic::vp_fmul: 1187 case Intrinsic::vp_shl: 1188 case Intrinsic::vp_lshr: 1189 case Intrinsic::vp_ashr: 1190 case Intrinsic::vp_udiv: 1191 case Intrinsic::vp_sdiv: 1192 case Intrinsic::vp_urem: 1193 case Intrinsic::vp_srem: 1194 return Operand == 1; 1195 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1196 // explicit patterns for both LHS and RHS (as 'vr' versions). 1197 case Intrinsic::vp_sub: 1198 case Intrinsic::vp_fsub: 1199 case Intrinsic::vp_fdiv: 1200 return Operand == 0 || Operand == 1; 1201 default: 1202 return false; 1203 } 1204 } 1205 return false; 1206 default: 1207 return false; 1208 } 1209 }; 1210 1211 for (auto OpIdx : enumerate(I->operands())) { 1212 if (!IsSinker(I, OpIdx.index())) 1213 continue; 1214 1215 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1216 // Make sure we are not already sinking this operand 1217 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1218 continue; 1219 1220 // We are looking for a splat that can be sunk. 1221 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1222 m_Undef(), m_ZeroMask()))) 1223 continue; 1224 1225 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1226 // and vector registers 1227 for (Use &U : Op->uses()) { 1228 Instruction *Insn = cast<Instruction>(U.getUser()); 1229 if (!IsSinker(Insn, U.getOperandNo())) 1230 return false; 1231 } 1232 1233 Ops.push_back(&Op->getOperandUse(0)); 1234 Ops.push_back(&OpIdx.value()); 1235 } 1236 return true; 1237 } 1238 1239 bool RISCVTargetLowering::isOffsetFoldingLegal( 1240 const GlobalAddressSDNode *GA) const { 1241 // In order to maximise the opportunity for common subexpression elimination, 1242 // keep a separate ADD node for the global address offset instead of folding 1243 // it in the global address node. Later peephole optimisations may choose to 1244 // fold it back in when profitable. 1245 return false; 1246 } 1247 1248 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1249 bool ForCodeSize) const { 1250 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1251 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1252 return false; 1253 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1254 return false; 1255 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1256 return false; 1257 return Imm.isZero(); 1258 } 1259 1260 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1261 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1262 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1263 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1264 } 1265 1266 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1267 CallingConv::ID CC, 1268 EVT VT) const { 1269 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1270 // We might still end up using a GPR but that will be decided based on ABI. 1271 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1272 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1273 return MVT::f32; 1274 1275 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1276 } 1277 1278 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1279 CallingConv::ID CC, 1280 EVT VT) const { 1281 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1282 // We might still end up using a GPR but that will be decided based on ABI. 1283 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1284 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1285 return 1; 1286 1287 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1288 } 1289 1290 // Changes the condition code and swaps operands if necessary, so the SetCC 1291 // operation matches one of the comparisons supported directly by branches 1292 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1293 // with 1/-1. 1294 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1295 ISD::CondCode &CC, SelectionDAG &DAG) { 1296 // Convert X > -1 to X >= 0. 1297 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1298 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1299 CC = ISD::SETGE; 1300 return; 1301 } 1302 // Convert X < 1 to 0 >= X. 1303 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1304 RHS = LHS; 1305 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1306 CC = ISD::SETGE; 1307 return; 1308 } 1309 1310 switch (CC) { 1311 default: 1312 break; 1313 case ISD::SETGT: 1314 case ISD::SETLE: 1315 case ISD::SETUGT: 1316 case ISD::SETULE: 1317 CC = ISD::getSetCCSwappedOperands(CC); 1318 std::swap(LHS, RHS); 1319 break; 1320 } 1321 } 1322 1323 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1324 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1325 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1326 if (VT.getVectorElementType() == MVT::i1) 1327 KnownSize *= 8; 1328 1329 switch (KnownSize) { 1330 default: 1331 llvm_unreachable("Invalid LMUL."); 1332 case 8: 1333 return RISCVII::VLMUL::LMUL_F8; 1334 case 16: 1335 return RISCVII::VLMUL::LMUL_F4; 1336 case 32: 1337 return RISCVII::VLMUL::LMUL_F2; 1338 case 64: 1339 return RISCVII::VLMUL::LMUL_1; 1340 case 128: 1341 return RISCVII::VLMUL::LMUL_2; 1342 case 256: 1343 return RISCVII::VLMUL::LMUL_4; 1344 case 512: 1345 return RISCVII::VLMUL::LMUL_8; 1346 } 1347 } 1348 1349 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1350 switch (LMul) { 1351 default: 1352 llvm_unreachable("Invalid LMUL."); 1353 case RISCVII::VLMUL::LMUL_F8: 1354 case RISCVII::VLMUL::LMUL_F4: 1355 case RISCVII::VLMUL::LMUL_F2: 1356 case RISCVII::VLMUL::LMUL_1: 1357 return RISCV::VRRegClassID; 1358 case RISCVII::VLMUL::LMUL_2: 1359 return RISCV::VRM2RegClassID; 1360 case RISCVII::VLMUL::LMUL_4: 1361 return RISCV::VRM4RegClassID; 1362 case RISCVII::VLMUL::LMUL_8: 1363 return RISCV::VRM8RegClassID; 1364 } 1365 } 1366 1367 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1368 RISCVII::VLMUL LMUL = getLMUL(VT); 1369 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1370 LMUL == RISCVII::VLMUL::LMUL_F4 || 1371 LMUL == RISCVII::VLMUL::LMUL_F2 || 1372 LMUL == RISCVII::VLMUL::LMUL_1) { 1373 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1374 "Unexpected subreg numbering"); 1375 return RISCV::sub_vrm1_0 + Index; 1376 } 1377 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1378 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1379 "Unexpected subreg numbering"); 1380 return RISCV::sub_vrm2_0 + Index; 1381 } 1382 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1383 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1384 "Unexpected subreg numbering"); 1385 return RISCV::sub_vrm4_0 + Index; 1386 } 1387 llvm_unreachable("Invalid vector type."); 1388 } 1389 1390 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1391 if (VT.getVectorElementType() == MVT::i1) 1392 return RISCV::VRRegClassID; 1393 return getRegClassIDForLMUL(getLMUL(VT)); 1394 } 1395 1396 // Attempt to decompose a subvector insert/extract between VecVT and 1397 // SubVecVT via subregister indices. Returns the subregister index that 1398 // can perform the subvector insert/extract with the given element index, as 1399 // well as the index corresponding to any leftover subvectors that must be 1400 // further inserted/extracted within the register class for SubVecVT. 1401 std::pair<unsigned, unsigned> 1402 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1403 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1404 const RISCVRegisterInfo *TRI) { 1405 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1406 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1407 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1408 "Register classes not ordered"); 1409 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1410 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1411 // Try to compose a subregister index that takes us from the incoming 1412 // LMUL>1 register class down to the outgoing one. At each step we half 1413 // the LMUL: 1414 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1415 // Note that this is not guaranteed to find a subregister index, such as 1416 // when we are extracting from one VR type to another. 1417 unsigned SubRegIdx = RISCV::NoSubRegister; 1418 for (const unsigned RCID : 1419 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1420 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1421 VecVT = VecVT.getHalfNumVectorElementsVT(); 1422 bool IsHi = 1423 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1424 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1425 getSubregIndexByMVT(VecVT, IsHi)); 1426 if (IsHi) 1427 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1428 } 1429 return {SubRegIdx, InsertExtractIdx}; 1430 } 1431 1432 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1433 // stores for those types. 1434 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1435 return !Subtarget.useRVVForFixedLengthVectors() || 1436 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1437 } 1438 1439 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1440 if (ScalarTy->isPointerTy()) 1441 return true; 1442 1443 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1444 ScalarTy->isIntegerTy(32)) 1445 return true; 1446 1447 if (ScalarTy->isIntegerTy(64)) 1448 return Subtarget.hasVInstructionsI64(); 1449 1450 if (ScalarTy->isHalfTy()) 1451 return Subtarget.hasVInstructionsF16(); 1452 if (ScalarTy->isFloatTy()) 1453 return Subtarget.hasVInstructionsF32(); 1454 if (ScalarTy->isDoubleTy()) 1455 return Subtarget.hasVInstructionsF64(); 1456 1457 return false; 1458 } 1459 1460 static SDValue getVLOperand(SDValue Op) { 1461 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1462 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1463 "Unexpected opcode"); 1464 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1465 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1466 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1467 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1468 if (!II) 1469 return SDValue(); 1470 return Op.getOperand(II->VLOperand + 1 + HasChain); 1471 } 1472 1473 static bool useRVVForFixedLengthVectorVT(MVT VT, 1474 const RISCVSubtarget &Subtarget) { 1475 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1476 if (!Subtarget.useRVVForFixedLengthVectors()) 1477 return false; 1478 1479 // We only support a set of vector types with a consistent maximum fixed size 1480 // across all supported vector element types to avoid legalization issues. 1481 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1482 // fixed-length vector type we support is 1024 bytes. 1483 if (VT.getFixedSizeInBits() > 1024 * 8) 1484 return false; 1485 1486 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1487 1488 MVT EltVT = VT.getVectorElementType(); 1489 1490 // Don't use RVV for vectors we cannot scalarize if required. 1491 switch (EltVT.SimpleTy) { 1492 // i1 is supported but has different rules. 1493 default: 1494 return false; 1495 case MVT::i1: 1496 // Masks can only use a single register. 1497 if (VT.getVectorNumElements() > MinVLen) 1498 return false; 1499 MinVLen /= 8; 1500 break; 1501 case MVT::i8: 1502 case MVT::i16: 1503 case MVT::i32: 1504 break; 1505 case MVT::i64: 1506 if (!Subtarget.hasVInstructionsI64()) 1507 return false; 1508 break; 1509 case MVT::f16: 1510 if (!Subtarget.hasVInstructionsF16()) 1511 return false; 1512 break; 1513 case MVT::f32: 1514 if (!Subtarget.hasVInstructionsF32()) 1515 return false; 1516 break; 1517 case MVT::f64: 1518 if (!Subtarget.hasVInstructionsF64()) 1519 return false; 1520 break; 1521 } 1522 1523 // Reject elements larger than ELEN. 1524 if (EltVT.getSizeInBits() > Subtarget.getELEN()) 1525 return false; 1526 1527 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1528 // Don't use RVV for types that don't fit. 1529 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1530 return false; 1531 1532 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1533 // the base fixed length RVV support in place. 1534 if (!VT.isPow2VectorType()) 1535 return false; 1536 1537 return true; 1538 } 1539 1540 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1541 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1542 } 1543 1544 // Return the largest legal scalable vector type that matches VT's element type. 1545 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1546 const RISCVSubtarget &Subtarget) { 1547 // This may be called before legal types are setup. 1548 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1549 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1550 "Expected legal fixed length vector!"); 1551 1552 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1553 unsigned MaxELen = Subtarget.getELEN(); 1554 1555 MVT EltVT = VT.getVectorElementType(); 1556 switch (EltVT.SimpleTy) { 1557 default: 1558 llvm_unreachable("unexpected element type for RVV container"); 1559 case MVT::i1: 1560 case MVT::i8: 1561 case MVT::i16: 1562 case MVT::i32: 1563 case MVT::i64: 1564 case MVT::f16: 1565 case MVT::f32: 1566 case MVT::f64: { 1567 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1568 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1569 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1570 unsigned NumElts = 1571 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1572 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1573 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1574 return MVT::getScalableVectorVT(EltVT, NumElts); 1575 } 1576 } 1577 } 1578 1579 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1580 const RISCVSubtarget &Subtarget) { 1581 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1582 Subtarget); 1583 } 1584 1585 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1586 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1587 } 1588 1589 // Grow V to consume an entire RVV register. 1590 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1591 const RISCVSubtarget &Subtarget) { 1592 assert(VT.isScalableVector() && 1593 "Expected to convert into a scalable vector!"); 1594 assert(V.getValueType().isFixedLengthVector() && 1595 "Expected a fixed length vector operand!"); 1596 SDLoc DL(V); 1597 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1598 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1599 } 1600 1601 // Shrink V so it's just big enough to maintain a VT's worth of data. 1602 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1603 const RISCVSubtarget &Subtarget) { 1604 assert(VT.isFixedLengthVector() && 1605 "Expected to convert into a fixed length vector!"); 1606 assert(V.getValueType().isScalableVector() && 1607 "Expected a scalable vector operand!"); 1608 SDLoc DL(V); 1609 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1610 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1611 } 1612 1613 /// Return the type of the mask type suitable for masking the provided 1614 /// vector type. This is simply an i1 element type vector of the same 1615 /// (possibly scalable) length. 1616 static MVT getMaskTypeFor(EVT VecVT) { 1617 assert(VecVT.isVector()); 1618 ElementCount EC = VecVT.getVectorElementCount(); 1619 return MVT::getVectorVT(MVT::i1, EC); 1620 } 1621 1622 /// Creates an all ones mask suitable for masking a vector of type VecTy with 1623 /// vector length VL. . 1624 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL, 1625 SelectionDAG &DAG) { 1626 MVT MaskVT = getMaskTypeFor(VecVT); 1627 return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1628 } 1629 1630 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1631 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1632 // the vector type that it is contained in. 1633 static std::pair<SDValue, SDValue> 1634 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1635 const RISCVSubtarget &Subtarget) { 1636 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1637 MVT XLenVT = Subtarget.getXLenVT(); 1638 SDValue VL = VecVT.isFixedLengthVector() 1639 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1640 : DAG.getRegister(RISCV::X0, XLenVT); 1641 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 1642 return {Mask, VL}; 1643 } 1644 1645 // As above but assuming the given type is a scalable vector type. 1646 static std::pair<SDValue, SDValue> 1647 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1648 const RISCVSubtarget &Subtarget) { 1649 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1650 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1651 } 1652 1653 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1654 // of either is (currently) supported. This can get us into an infinite loop 1655 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1656 // as a ..., etc. 1657 // Until either (or both) of these can reliably lower any node, reporting that 1658 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1659 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1660 // which is not desirable. 1661 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1662 EVT VT, unsigned DefinedValues) const { 1663 return false; 1664 } 1665 1666 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1667 const RISCVSubtarget &Subtarget) { 1668 // RISCV FP-to-int conversions saturate to the destination register size, but 1669 // don't produce 0 for nan. We can use a conversion instruction and fix the 1670 // nan case with a compare and a select. 1671 SDValue Src = Op.getOperand(0); 1672 1673 EVT DstVT = Op.getValueType(); 1674 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1675 1676 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1677 unsigned Opc; 1678 if (SatVT == DstVT) 1679 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1680 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1681 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1682 else 1683 return SDValue(); 1684 // FIXME: Support other SatVTs by clamping before or after the conversion. 1685 1686 SDLoc DL(Op); 1687 SDValue FpToInt = DAG.getNode( 1688 Opc, DL, DstVT, Src, 1689 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1690 1691 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1692 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1693 } 1694 1695 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1696 // and back. Taking care to avoid converting values that are nan or already 1697 // correct. 1698 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1699 // have FRM dependencies modeled yet. 1700 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1701 MVT VT = Op.getSimpleValueType(); 1702 assert(VT.isVector() && "Unexpected type"); 1703 1704 SDLoc DL(Op); 1705 1706 // Freeze the source since we are increasing the number of uses. 1707 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1708 1709 // Truncate to integer and convert back to FP. 1710 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1711 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1712 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1713 1714 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1715 1716 if (Op.getOpcode() == ISD::FCEIL) { 1717 // If the truncated value is the greater than or equal to the original 1718 // value, we've computed the ceil. Otherwise, we went the wrong way and 1719 // need to increase by 1. 1720 // FIXME: This should use a masked operation. Handle here or in isel? 1721 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1722 DAG.getConstantFP(1.0, DL, VT)); 1723 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1724 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1725 } else if (Op.getOpcode() == ISD::FFLOOR) { 1726 // If the truncated value is the less than or equal to the original value, 1727 // we've computed the floor. Otherwise, we went the wrong way and need to 1728 // decrease by 1. 1729 // FIXME: This should use a masked operation. Handle here or in isel? 1730 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1731 DAG.getConstantFP(1.0, DL, VT)); 1732 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1733 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1734 } 1735 1736 // Restore the original sign so that -0.0 is preserved. 1737 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1738 1739 // Determine the largest integer that can be represented exactly. This and 1740 // values larger than it don't have any fractional bits so don't need to 1741 // be converted. 1742 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1743 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1744 APFloat MaxVal = APFloat(FltSem); 1745 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1746 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1747 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1748 1749 // If abs(Src) was larger than MaxVal or nan, keep it. 1750 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1751 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1752 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1753 } 1754 1755 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1756 // This mode isn't supported in vector hardware on RISCV. But as long as we 1757 // aren't compiling with trapping math, we can emulate this with 1758 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1759 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1760 // dependencies modeled yet. 1761 // FIXME: Use masked operations to avoid final merge. 1762 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1763 MVT VT = Op.getSimpleValueType(); 1764 assert(VT.isVector() && "Unexpected type"); 1765 1766 SDLoc DL(Op); 1767 1768 // Freeze the source since we are increasing the number of uses. 1769 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1770 1771 // We do the conversion on the absolute value and fix the sign at the end. 1772 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1773 1774 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1775 bool Ignored; 1776 APFloat Point5Pred = APFloat(0.5f); 1777 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1778 Point5Pred.next(/*nextDown*/ true); 1779 1780 // Add the adjustment. 1781 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1782 DAG.getConstantFP(Point5Pred, DL, VT)); 1783 1784 // Truncate to integer and convert back to fp. 1785 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1786 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1787 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1788 1789 // Restore the original sign. 1790 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1791 1792 // Determine the largest integer that can be represented exactly. This and 1793 // values larger than it don't have any fractional bits so don't need to 1794 // be converted. 1795 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1796 APFloat MaxVal = APFloat(FltSem); 1797 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1798 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1799 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1800 1801 // If abs(Src) was larger than MaxVal or nan, keep it. 1802 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1803 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1804 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1805 } 1806 1807 struct VIDSequence { 1808 int64_t StepNumerator; 1809 unsigned StepDenominator; 1810 int64_t Addend; 1811 }; 1812 1813 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1814 // to the (non-zero) step S and start value X. This can be then lowered as the 1815 // RVV sequence (VID * S) + X, for example. 1816 // The step S is represented as an integer numerator divided by a positive 1817 // denominator. Note that the implementation currently only identifies 1818 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1819 // cannot detect 2/3, for example. 1820 // Note that this method will also match potentially unappealing index 1821 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1822 // determine whether this is worth generating code for. 1823 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1824 unsigned NumElts = Op.getNumOperands(); 1825 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1826 if (!Op.getValueType().isInteger()) 1827 return None; 1828 1829 Optional<unsigned> SeqStepDenom; 1830 Optional<int64_t> SeqStepNum, SeqAddend; 1831 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1832 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1833 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1834 // Assume undef elements match the sequence; we just have to be careful 1835 // when interpolating across them. 1836 if (Op.getOperand(Idx).isUndef()) 1837 continue; 1838 // The BUILD_VECTOR must be all constants. 1839 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1840 return None; 1841 1842 uint64_t Val = Op.getConstantOperandVal(Idx) & 1843 maskTrailingOnes<uint64_t>(EltSizeInBits); 1844 1845 if (PrevElt) { 1846 // Calculate the step since the last non-undef element, and ensure 1847 // it's consistent across the entire sequence. 1848 unsigned IdxDiff = Idx - PrevElt->second; 1849 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1850 1851 // A zero-value value difference means that we're somewhere in the middle 1852 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1853 // step change before evaluating the sequence. 1854 if (ValDiff == 0) 1855 continue; 1856 1857 int64_t Remainder = ValDiff % IdxDiff; 1858 // Normalize the step if it's greater than 1. 1859 if (Remainder != ValDiff) { 1860 // The difference must cleanly divide the element span. 1861 if (Remainder != 0) 1862 return None; 1863 ValDiff /= IdxDiff; 1864 IdxDiff = 1; 1865 } 1866 1867 if (!SeqStepNum) 1868 SeqStepNum = ValDiff; 1869 else if (ValDiff != SeqStepNum) 1870 return None; 1871 1872 if (!SeqStepDenom) 1873 SeqStepDenom = IdxDiff; 1874 else if (IdxDiff != *SeqStepDenom) 1875 return None; 1876 } 1877 1878 // Record this non-undef element for later. 1879 if (!PrevElt || PrevElt->first != Val) 1880 PrevElt = std::make_pair(Val, Idx); 1881 } 1882 1883 // We need to have logged a step for this to count as a legal index sequence. 1884 if (!SeqStepNum || !SeqStepDenom) 1885 return None; 1886 1887 // Loop back through the sequence and validate elements we might have skipped 1888 // while waiting for a valid step. While doing this, log any sequence addend. 1889 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1890 if (Op.getOperand(Idx).isUndef()) 1891 continue; 1892 uint64_t Val = Op.getConstantOperandVal(Idx) & 1893 maskTrailingOnes<uint64_t>(EltSizeInBits); 1894 uint64_t ExpectedVal = 1895 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1896 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1897 if (!SeqAddend) 1898 SeqAddend = Addend; 1899 else if (Addend != SeqAddend) 1900 return None; 1901 } 1902 1903 assert(SeqAddend && "Must have an addend if we have a step"); 1904 1905 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1906 } 1907 1908 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1909 // and lower it as a VRGATHER_VX_VL from the source vector. 1910 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 1911 SelectionDAG &DAG, 1912 const RISCVSubtarget &Subtarget) { 1913 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1914 return SDValue(); 1915 SDValue Vec = SplatVal.getOperand(0); 1916 // Only perform this optimization on vectors of the same size for simplicity. 1917 if (Vec.getValueType() != VT) 1918 return SDValue(); 1919 SDValue Idx = SplatVal.getOperand(1); 1920 // The index must be a legal type. 1921 if (Idx.getValueType() != Subtarget.getXLenVT()) 1922 return SDValue(); 1923 1924 MVT ContainerVT = VT; 1925 if (VT.isFixedLengthVector()) { 1926 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1927 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 1928 } 1929 1930 SDValue Mask, VL; 1931 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1932 1933 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 1934 Idx, Mask, VL); 1935 1936 if (!VT.isFixedLengthVector()) 1937 return Gather; 1938 1939 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 1940 } 1941 1942 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1943 const RISCVSubtarget &Subtarget) { 1944 MVT VT = Op.getSimpleValueType(); 1945 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1946 1947 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1948 1949 SDLoc DL(Op); 1950 SDValue Mask, VL; 1951 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1952 1953 MVT XLenVT = Subtarget.getXLenVT(); 1954 unsigned NumElts = Op.getNumOperands(); 1955 1956 if (VT.getVectorElementType() == MVT::i1) { 1957 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 1958 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 1959 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 1960 } 1961 1962 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 1963 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 1964 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 1965 } 1966 1967 // Lower constant mask BUILD_VECTORs via an integer vector type, in 1968 // scalar integer chunks whose bit-width depends on the number of mask 1969 // bits and XLEN. 1970 // First, determine the most appropriate scalar integer type to use. This 1971 // is at most XLenVT, but may be shrunk to a smaller vector element type 1972 // according to the size of the final vector - use i8 chunks rather than 1973 // XLenVT if we're producing a v8i1. This results in more consistent 1974 // codegen across RV32 and RV64. 1975 unsigned NumViaIntegerBits = 1976 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 1977 NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN()); 1978 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 1979 // If we have to use more than one INSERT_VECTOR_ELT then this 1980 // optimization is likely to increase code size; avoid peforming it in 1981 // such a case. We can use a load from a constant pool in this case. 1982 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 1983 return SDValue(); 1984 // Now we can create our integer vector type. Note that it may be larger 1985 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 1986 MVT IntegerViaVecVT = 1987 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 1988 divideCeil(NumElts, NumViaIntegerBits)); 1989 1990 uint64_t Bits = 0; 1991 unsigned BitPos = 0, IntegerEltIdx = 0; 1992 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 1993 1994 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 1995 // Once we accumulate enough bits to fill our scalar type, insert into 1996 // our vector and clear our accumulated data. 1997 if (I != 0 && I % NumViaIntegerBits == 0) { 1998 if (NumViaIntegerBits <= 32) 1999 Bits = SignExtend64<32>(Bits); 2000 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2001 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 2002 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2003 Bits = 0; 2004 BitPos = 0; 2005 IntegerEltIdx++; 2006 } 2007 SDValue V = Op.getOperand(I); 2008 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2009 Bits |= ((uint64_t)BitValue << BitPos); 2010 } 2011 2012 // Insert the (remaining) scalar value into position in our integer 2013 // vector type. 2014 if (NumViaIntegerBits <= 32) 2015 Bits = SignExtend64<32>(Bits); 2016 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2017 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2018 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2019 2020 if (NumElts < NumViaIntegerBits) { 2021 // If we're producing a smaller vector than our minimum legal integer 2022 // type, bitcast to the equivalent (known-legal) mask type, and extract 2023 // our final mask. 2024 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2025 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2026 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2027 DAG.getConstant(0, DL, XLenVT)); 2028 } else { 2029 // Else we must have produced an integer type with the same size as the 2030 // mask type; bitcast for the final result. 2031 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2032 Vec = DAG.getBitcast(VT, Vec); 2033 } 2034 2035 return Vec; 2036 } 2037 2038 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2039 // vector type, we have a legal equivalently-sized i8 type, so we can use 2040 // that. 2041 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2042 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2043 2044 SDValue WideVec; 2045 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2046 // For a splat, perform a scalar truncate before creating the wider 2047 // vector. 2048 assert(Splat.getValueType() == XLenVT && 2049 "Unexpected type for i1 splat value"); 2050 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2051 DAG.getConstant(1, DL, XLenVT)); 2052 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2053 } else { 2054 SmallVector<SDValue, 8> Ops(Op->op_values()); 2055 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2056 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2057 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2058 } 2059 2060 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2061 } 2062 2063 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2064 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2065 return Gather; 2066 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2067 : RISCVISD::VMV_V_X_VL; 2068 Splat = 2069 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2070 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2071 } 2072 2073 // Try and match index sequences, which we can lower to the vid instruction 2074 // with optional modifications. An all-undef vector is matched by 2075 // getSplatValue, above. 2076 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2077 int64_t StepNumerator = SimpleVID->StepNumerator; 2078 unsigned StepDenominator = SimpleVID->StepDenominator; 2079 int64_t Addend = SimpleVID->Addend; 2080 2081 assert(StepNumerator != 0 && "Invalid step"); 2082 bool Negate = false; 2083 int64_t SplatStepVal = StepNumerator; 2084 unsigned StepOpcode = ISD::MUL; 2085 if (StepNumerator != 1) { 2086 if (isPowerOf2_64(std::abs(StepNumerator))) { 2087 Negate = StepNumerator < 0; 2088 StepOpcode = ISD::SHL; 2089 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2090 } 2091 } 2092 2093 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2094 // threshold since it's the immediate value many RVV instructions accept. 2095 // There is no vmul.vi instruction so ensure multiply constant can fit in 2096 // a single addi instruction. 2097 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2098 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2099 isPowerOf2_32(StepDenominator) && 2100 (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) { 2101 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2102 // Convert right out of the scalable type so we can use standard ISD 2103 // nodes for the rest of the computation. If we used scalable types with 2104 // these, we'd lose the fixed-length vector info and generate worse 2105 // vsetvli code. 2106 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2107 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2108 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2109 SDValue SplatStep = DAG.getSplatBuildVector( 2110 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2111 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2112 } 2113 if (StepDenominator != 1) { 2114 SDValue SplatStep = DAG.getSplatBuildVector( 2115 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2116 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2117 } 2118 if (Addend != 0 || Negate) { 2119 SDValue SplatAddend = DAG.getSplatBuildVector( 2120 VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2121 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2122 } 2123 return VID; 2124 } 2125 } 2126 2127 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2128 // when re-interpreted as a vector with a larger element type. For example, 2129 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2130 // could be instead splat as 2131 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2132 // TODO: This optimization could also work on non-constant splats, but it 2133 // would require bit-manipulation instructions to construct the splat value. 2134 SmallVector<SDValue> Sequence; 2135 unsigned EltBitSize = VT.getScalarSizeInBits(); 2136 const auto *BV = cast<BuildVectorSDNode>(Op); 2137 if (VT.isInteger() && EltBitSize < 64 && 2138 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2139 BV->getRepeatedSequence(Sequence) && 2140 (Sequence.size() * EltBitSize) <= 64) { 2141 unsigned SeqLen = Sequence.size(); 2142 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2143 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2144 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2145 ViaIntVT == MVT::i64) && 2146 "Unexpected sequence type"); 2147 2148 unsigned EltIdx = 0; 2149 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2150 uint64_t SplatValue = 0; 2151 // Construct the amalgamated value which can be splatted as this larger 2152 // vector type. 2153 for (const auto &SeqV : Sequence) { 2154 if (!SeqV.isUndef()) 2155 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2156 << (EltIdx * EltBitSize)); 2157 EltIdx++; 2158 } 2159 2160 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2161 // achieve better constant materializion. 2162 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2163 SplatValue = SignExtend64<32>(SplatValue); 2164 2165 // Since we can't introduce illegal i64 types at this stage, we can only 2166 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2167 // way we can use RVV instructions to splat. 2168 assert((ViaIntVT.bitsLE(XLenVT) || 2169 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2170 "Unexpected bitcast sequence"); 2171 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2172 SDValue ViaVL = 2173 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2174 MVT ViaContainerVT = 2175 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2176 SDValue Splat = 2177 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2178 DAG.getUNDEF(ViaContainerVT), 2179 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2180 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2181 return DAG.getBitcast(VT, Splat); 2182 } 2183 } 2184 2185 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2186 // which constitute a large proportion of the elements. In such cases we can 2187 // splat a vector with the dominant element and make up the shortfall with 2188 // INSERT_VECTOR_ELTs. 2189 // Note that this includes vectors of 2 elements by association. The 2190 // upper-most element is the "dominant" one, allowing us to use a splat to 2191 // "insert" the upper element, and an insert of the lower element at position 2192 // 0, which improves codegen. 2193 SDValue DominantValue; 2194 unsigned MostCommonCount = 0; 2195 DenseMap<SDValue, unsigned> ValueCounts; 2196 unsigned NumUndefElts = 2197 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2198 2199 // Track the number of scalar loads we know we'd be inserting, estimated as 2200 // any non-zero floating-point constant. Other kinds of element are either 2201 // already in registers or are materialized on demand. The threshold at which 2202 // a vector load is more desirable than several scalar materializion and 2203 // vector-insertion instructions is not known. 2204 unsigned NumScalarLoads = 0; 2205 2206 for (SDValue V : Op->op_values()) { 2207 if (V.isUndef()) 2208 continue; 2209 2210 ValueCounts.insert(std::make_pair(V, 0)); 2211 unsigned &Count = ValueCounts[V]; 2212 2213 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2214 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2215 2216 // Is this value dominant? In case of a tie, prefer the highest element as 2217 // it's cheaper to insert near the beginning of a vector than it is at the 2218 // end. 2219 if (++Count >= MostCommonCount) { 2220 DominantValue = V; 2221 MostCommonCount = Count; 2222 } 2223 } 2224 2225 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2226 unsigned NumDefElts = NumElts - NumUndefElts; 2227 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2228 2229 // Don't perform this optimization when optimizing for size, since 2230 // materializing elements and inserting them tends to cause code bloat. 2231 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2232 ((MostCommonCount > DominantValueCountThreshold) || 2233 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2234 // Start by splatting the most common element. 2235 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2236 2237 DenseSet<SDValue> Processed{DominantValue}; 2238 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2239 for (const auto &OpIdx : enumerate(Op->ops())) { 2240 const SDValue &V = OpIdx.value(); 2241 if (V.isUndef() || !Processed.insert(V).second) 2242 continue; 2243 if (ValueCounts[V] == 1) { 2244 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2245 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2246 } else { 2247 // Blend in all instances of this value using a VSELECT, using a 2248 // mask where each bit signals whether that element is the one 2249 // we're after. 2250 SmallVector<SDValue> Ops; 2251 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2252 return DAG.getConstant(V == V1, DL, XLenVT); 2253 }); 2254 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2255 DAG.getBuildVector(SelMaskTy, DL, Ops), 2256 DAG.getSplatBuildVector(VT, DL, V), Vec); 2257 } 2258 } 2259 2260 return Vec; 2261 } 2262 2263 return SDValue(); 2264 } 2265 2266 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2267 SDValue Lo, SDValue Hi, SDValue VL, 2268 SelectionDAG &DAG) { 2269 if (!Passthru) 2270 Passthru = DAG.getUNDEF(VT); 2271 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2272 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2273 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2274 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2275 // node in order to try and match RVV vector/scalar instructions. 2276 if ((LoC >> 31) == HiC) 2277 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2278 2279 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2280 // vmv.v.x whose EEW = 32 to lower it. 2281 auto *Const = dyn_cast<ConstantSDNode>(VL); 2282 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2283 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2284 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2285 // access the subtarget here now. 2286 auto InterVec = DAG.getNode( 2287 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2288 DAG.getRegister(RISCV::X0, MVT::i32)); 2289 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2290 } 2291 } 2292 2293 // Fall back to a stack store and stride x0 vector load. 2294 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2295 Hi, VL); 2296 } 2297 2298 // Called by type legalization to handle splat of i64 on RV32. 2299 // FIXME: We can optimize this when the type has sign or zero bits in one 2300 // of the halves. 2301 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2302 SDValue Scalar, SDValue VL, 2303 SelectionDAG &DAG) { 2304 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2305 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2306 DAG.getConstant(0, DL, MVT::i32)); 2307 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2308 DAG.getConstant(1, DL, MVT::i32)); 2309 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2310 } 2311 2312 // This function lowers a splat of a scalar operand Splat with the vector 2313 // length VL. It ensures the final sequence is type legal, which is useful when 2314 // lowering a splat after type legalization. 2315 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2316 MVT VT, SDLoc DL, SelectionDAG &DAG, 2317 const RISCVSubtarget &Subtarget) { 2318 bool HasPassthru = Passthru && !Passthru.isUndef(); 2319 if (!HasPassthru && !Passthru) 2320 Passthru = DAG.getUNDEF(VT); 2321 if (VT.isFloatingPoint()) { 2322 // If VL is 1, we could use vfmv.s.f. 2323 if (isOneConstant(VL)) 2324 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2325 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2326 } 2327 2328 MVT XLenVT = Subtarget.getXLenVT(); 2329 2330 // Simplest case is that the operand needs to be promoted to XLenVT. 2331 if (Scalar.getValueType().bitsLE(XLenVT)) { 2332 // If the operand is a constant, sign extend to increase our chances 2333 // of being able to use a .vi instruction. ANY_EXTEND would become a 2334 // a zero extend and the simm5 check in isel would fail. 2335 // FIXME: Should we ignore the upper bits in isel instead? 2336 unsigned ExtOpc = 2337 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2338 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2339 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2340 // If VL is 1 and the scalar value won't benefit from immediate, we could 2341 // use vmv.s.x. 2342 if (isOneConstant(VL) && 2343 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2344 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2345 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2346 } 2347 2348 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2349 "Unexpected scalar for splat lowering!"); 2350 2351 if (isOneConstant(VL) && isNullConstant(Scalar)) 2352 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2353 DAG.getConstant(0, DL, XLenVT), VL); 2354 2355 // Otherwise use the more complicated splatting algorithm. 2356 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2357 } 2358 2359 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2360 const RISCVSubtarget &Subtarget) { 2361 // We need to be able to widen elements to the next larger integer type. 2362 if (VT.getScalarSizeInBits() >= Subtarget.getELEN()) 2363 return false; 2364 2365 int Size = Mask.size(); 2366 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2367 2368 int Srcs[] = {-1, -1}; 2369 for (int i = 0; i != Size; ++i) { 2370 // Ignore undef elements. 2371 if (Mask[i] < 0) 2372 continue; 2373 2374 // Is this an even or odd element. 2375 int Pol = i % 2; 2376 2377 // Ensure we consistently use the same source for this element polarity. 2378 int Src = Mask[i] / Size; 2379 if (Srcs[Pol] < 0) 2380 Srcs[Pol] = Src; 2381 if (Srcs[Pol] != Src) 2382 return false; 2383 2384 // Make sure the element within the source is appropriate for this element 2385 // in the destination. 2386 int Elt = Mask[i] % Size; 2387 if (Elt != i / 2) 2388 return false; 2389 } 2390 2391 // We need to find a source for each polarity and they can't be the same. 2392 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2393 return false; 2394 2395 // Swap the sources if the second source was in the even polarity. 2396 SwapSources = Srcs[0] > Srcs[1]; 2397 2398 return true; 2399 } 2400 2401 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2402 /// and then extract the original number of elements from the rotated result. 2403 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2404 /// returned rotation amount is for a rotate right, where elements move from 2405 /// higher elements to lower elements. \p LoSrc indicates the first source 2406 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2407 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2408 /// 0 or 1 if a rotation is found. 2409 /// 2410 /// NOTE: We talk about rotate to the right which matches how bit shift and 2411 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2412 /// and the table below write vectors with the lowest elements on the left. 2413 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2414 int Size = Mask.size(); 2415 2416 // We need to detect various ways of spelling a rotation: 2417 // [11, 12, 13, 14, 15, 0, 1, 2] 2418 // [-1, 12, 13, 14, -1, -1, 1, -1] 2419 // [-1, -1, -1, -1, -1, -1, 1, 2] 2420 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2421 // [-1, 4, 5, 6, -1, -1, 9, -1] 2422 // [-1, 4, 5, 6, -1, -1, -1, -1] 2423 int Rotation = 0; 2424 LoSrc = -1; 2425 HiSrc = -1; 2426 for (int i = 0; i != Size; ++i) { 2427 int M = Mask[i]; 2428 if (M < 0) 2429 continue; 2430 2431 // Determine where a rotate vector would have started. 2432 int StartIdx = i - (M % Size); 2433 // The identity rotation isn't interesting, stop. 2434 if (StartIdx == 0) 2435 return -1; 2436 2437 // If we found the tail of a vector the rotation must be the missing 2438 // front. If we found the head of a vector, it must be how much of the 2439 // head. 2440 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2441 2442 if (Rotation == 0) 2443 Rotation = CandidateRotation; 2444 else if (Rotation != CandidateRotation) 2445 // The rotations don't match, so we can't match this mask. 2446 return -1; 2447 2448 // Compute which value this mask is pointing at. 2449 int MaskSrc = M < Size ? 0 : 1; 2450 2451 // Compute which of the two target values this index should be assigned to. 2452 // This reflects whether the high elements are remaining or the low elemnts 2453 // are remaining. 2454 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2455 2456 // Either set up this value if we've not encountered it before, or check 2457 // that it remains consistent. 2458 if (TargetSrc < 0) 2459 TargetSrc = MaskSrc; 2460 else if (TargetSrc != MaskSrc) 2461 // This may be a rotation, but it pulls from the inputs in some 2462 // unsupported interleaving. 2463 return -1; 2464 } 2465 2466 // Check that we successfully analyzed the mask, and normalize the results. 2467 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2468 assert((LoSrc >= 0 || HiSrc >= 0) && 2469 "Failed to find a rotated input vector!"); 2470 2471 return Rotation; 2472 } 2473 2474 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2475 const RISCVSubtarget &Subtarget) { 2476 SDValue V1 = Op.getOperand(0); 2477 SDValue V2 = Op.getOperand(1); 2478 SDLoc DL(Op); 2479 MVT XLenVT = Subtarget.getXLenVT(); 2480 MVT VT = Op.getSimpleValueType(); 2481 unsigned NumElts = VT.getVectorNumElements(); 2482 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2483 2484 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2485 2486 SDValue TrueMask, VL; 2487 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2488 2489 if (SVN->isSplat()) { 2490 const int Lane = SVN->getSplatIndex(); 2491 if (Lane >= 0) { 2492 MVT SVT = VT.getVectorElementType(); 2493 2494 // Turn splatted vector load into a strided load with an X0 stride. 2495 SDValue V = V1; 2496 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2497 // with undef. 2498 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2499 int Offset = Lane; 2500 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2501 int OpElements = 2502 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2503 V = V.getOperand(Offset / OpElements); 2504 Offset %= OpElements; 2505 } 2506 2507 // We need to ensure the load isn't atomic or volatile. 2508 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2509 auto *Ld = cast<LoadSDNode>(V); 2510 Offset *= SVT.getStoreSize(); 2511 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2512 TypeSize::Fixed(Offset), DL); 2513 2514 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2515 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2516 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2517 SDValue IntID = 2518 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2519 SDValue Ops[] = {Ld->getChain(), 2520 IntID, 2521 DAG.getUNDEF(ContainerVT), 2522 NewAddr, 2523 DAG.getRegister(RISCV::X0, XLenVT), 2524 VL}; 2525 SDValue NewLoad = DAG.getMemIntrinsicNode( 2526 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2527 DAG.getMachineFunction().getMachineMemOperand( 2528 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2529 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2530 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2531 } 2532 2533 // Otherwise use a scalar load and splat. This will give the best 2534 // opportunity to fold a splat into the operation. ISel can turn it into 2535 // the x0 strided load if we aren't able to fold away the select. 2536 if (SVT.isFloatingPoint()) 2537 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2538 Ld->getPointerInfo().getWithOffset(Offset), 2539 Ld->getOriginalAlign(), 2540 Ld->getMemOperand()->getFlags()); 2541 else 2542 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2543 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2544 Ld->getOriginalAlign(), 2545 Ld->getMemOperand()->getFlags()); 2546 DAG.makeEquivalentMemoryOrdering(Ld, V); 2547 2548 unsigned Opc = 2549 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2550 SDValue Splat = 2551 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2552 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2553 } 2554 2555 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2556 assert(Lane < (int)NumElts && "Unexpected lane!"); 2557 SDValue Gather = 2558 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2559 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2560 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2561 } 2562 } 2563 2564 ArrayRef<int> Mask = SVN->getMask(); 2565 2566 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2567 // be undef which can be handled with a single SLIDEDOWN/UP. 2568 int LoSrc, HiSrc; 2569 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2570 if (Rotation > 0) { 2571 SDValue LoV, HiV; 2572 if (LoSrc >= 0) { 2573 LoV = LoSrc == 0 ? V1 : V2; 2574 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2575 } 2576 if (HiSrc >= 0) { 2577 HiV = HiSrc == 0 ? V1 : V2; 2578 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2579 } 2580 2581 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2582 // to slide LoV up by (NumElts - Rotation). 2583 unsigned InvRotate = NumElts - Rotation; 2584 2585 SDValue Res = DAG.getUNDEF(ContainerVT); 2586 if (HiV) { 2587 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2588 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2589 // causes multiple vsetvlis in some test cases such as lowering 2590 // reduce.mul 2591 SDValue DownVL = VL; 2592 if (LoV) 2593 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2594 Res = 2595 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2596 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2597 } 2598 if (LoV) 2599 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2600 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2601 2602 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2603 } 2604 2605 // Detect an interleave shuffle and lower to 2606 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2607 bool SwapSources; 2608 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2609 // Swap sources if needed. 2610 if (SwapSources) 2611 std::swap(V1, V2); 2612 2613 // Extract the lower half of the vectors. 2614 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2615 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2616 DAG.getConstant(0, DL, XLenVT)); 2617 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2618 DAG.getConstant(0, DL, XLenVT)); 2619 2620 // Double the element width and halve the number of elements in an int type. 2621 unsigned EltBits = VT.getScalarSizeInBits(); 2622 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2623 MVT WideIntVT = 2624 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2625 // Convert this to a scalable vector. We need to base this on the 2626 // destination size to ensure there's always a type with a smaller LMUL. 2627 MVT WideIntContainerVT = 2628 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2629 2630 // Convert sources to scalable vectors with the same element count as the 2631 // larger type. 2632 MVT HalfContainerVT = MVT::getVectorVT( 2633 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2634 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2635 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2636 2637 // Cast sources to integer. 2638 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2639 MVT IntHalfVT = 2640 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2641 V1 = DAG.getBitcast(IntHalfVT, V1); 2642 V2 = DAG.getBitcast(IntHalfVT, V2); 2643 2644 // Freeze V2 since we use it twice and we need to be sure that the add and 2645 // multiply see the same value. 2646 V2 = DAG.getFreeze(V2); 2647 2648 // Recreate TrueMask using the widened type's element count. 2649 TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG); 2650 2651 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2652 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2653 V2, TrueMask, VL); 2654 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2655 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2656 DAG.getUNDEF(IntHalfVT), 2657 DAG.getAllOnesConstant(DL, XLenVT)); 2658 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2659 V2, Multiplier, TrueMask, VL); 2660 // Add the new copies to our previous addition giving us 2^eltbits copies of 2661 // V2. This is equivalent to shifting V2 left by eltbits. This should 2662 // combine with the vwmulu.vv above to form vwmaccu.vv. 2663 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2664 TrueMask, VL); 2665 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2666 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2667 // vector VT. 2668 ContainerVT = 2669 MVT::getVectorVT(VT.getVectorElementType(), 2670 WideIntContainerVT.getVectorElementCount() * 2); 2671 Add = DAG.getBitcast(ContainerVT, Add); 2672 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2673 } 2674 2675 // Detect shuffles which can be re-expressed as vector selects; these are 2676 // shuffles in which each element in the destination is taken from an element 2677 // at the corresponding index in either source vectors. 2678 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2679 int MaskIndex = MaskIdx.value(); 2680 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2681 }); 2682 2683 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2684 2685 SmallVector<SDValue> MaskVals; 2686 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2687 // merged with a second vrgather. 2688 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2689 2690 // By default we preserve the original operand order, and use a mask to 2691 // select LHS as true and RHS as false. However, since RVV vector selects may 2692 // feature splats but only on the LHS, we may choose to invert our mask and 2693 // instead select between RHS and LHS. 2694 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2695 bool InvertMask = IsSelect == SwapOps; 2696 2697 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2698 // half. 2699 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2700 2701 // Now construct the mask that will be used by the vselect or blended 2702 // vrgather operation. For vrgathers, construct the appropriate indices into 2703 // each vector. 2704 for (int MaskIndex : Mask) { 2705 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2706 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2707 if (!IsSelect) { 2708 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2709 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2710 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2711 : DAG.getUNDEF(XLenVT)); 2712 GatherIndicesRHS.push_back( 2713 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2714 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2715 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2716 ++LHSIndexCounts[MaskIndex]; 2717 if (!IsLHSOrUndefIndex) 2718 ++RHSIndexCounts[MaskIndex - NumElts]; 2719 } 2720 } 2721 2722 if (SwapOps) { 2723 std::swap(V1, V2); 2724 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2725 } 2726 2727 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2728 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2729 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2730 2731 if (IsSelect) 2732 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2733 2734 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2735 // On such a large vector we're unable to use i8 as the index type. 2736 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2737 // may involve vector splitting if we're already at LMUL=8, or our 2738 // user-supplied maximum fixed-length LMUL. 2739 return SDValue(); 2740 } 2741 2742 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2743 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2744 MVT IndexVT = VT.changeTypeToInteger(); 2745 // Since we can't introduce illegal index types at this stage, use i16 and 2746 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2747 // than XLenVT. 2748 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2749 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2750 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2751 } 2752 2753 MVT IndexContainerVT = 2754 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2755 2756 SDValue Gather; 2757 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2758 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2759 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2760 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2761 Subtarget); 2762 } else { 2763 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2764 // If only one index is used, we can use a "splat" vrgather. 2765 // TODO: We can splat the most-common index and fix-up any stragglers, if 2766 // that's beneficial. 2767 if (LHSIndexCounts.size() == 1) { 2768 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2769 Gather = 2770 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2771 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2772 } else { 2773 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2774 LHSIndices = 2775 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2776 2777 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2778 TrueMask, VL); 2779 } 2780 } 2781 2782 // If a second vector operand is used by this shuffle, blend it in with an 2783 // additional vrgather. 2784 if (!V2.isUndef()) { 2785 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2786 // If only one index is used, we can use a "splat" vrgather. 2787 // TODO: We can splat the most-common index and fix-up any stragglers, if 2788 // that's beneficial. 2789 if (RHSIndexCounts.size() == 1) { 2790 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2791 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2792 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2793 } else { 2794 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2795 RHSIndices = 2796 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2797 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2798 VL); 2799 } 2800 2801 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2802 SelectMask = 2803 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2804 2805 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2806 Gather, VL); 2807 } 2808 2809 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2810 } 2811 2812 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2813 // Support splats for any type. These should type legalize well. 2814 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2815 return true; 2816 2817 // Only support legal VTs for other shuffles for now. 2818 if (!isTypeLegal(VT)) 2819 return false; 2820 2821 MVT SVT = VT.getSimpleVT(); 2822 2823 bool SwapSources; 2824 int LoSrc, HiSrc; 2825 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2826 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2827 } 2828 2829 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2830 // the exponent. 2831 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2832 MVT VT = Op.getSimpleValueType(); 2833 unsigned EltSize = VT.getScalarSizeInBits(); 2834 SDValue Src = Op.getOperand(0); 2835 SDLoc DL(Op); 2836 2837 // We need a FP type that can represent the value. 2838 // TODO: Use f16 for i8 when possible? 2839 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2840 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2841 2842 // Legal types should have been checked in the RISCVTargetLowering 2843 // constructor. 2844 // TODO: Splitting may make sense in some cases. 2845 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2846 "Expected legal float type!"); 2847 2848 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2849 // The trailing zero count is equal to log2 of this single bit value. 2850 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2851 SDValue Neg = 2852 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2853 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2854 } 2855 2856 // We have a legal FP type, convert to it. 2857 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2858 // Bitcast to integer and shift the exponent to the LSB. 2859 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2860 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2861 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2862 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2863 DAG.getConstant(ShiftAmt, DL, IntVT)); 2864 // Truncate back to original type to allow vnsrl. 2865 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2866 // The exponent contains log2 of the value in biased form. 2867 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2868 2869 // For trailing zeros, we just need to subtract the bias. 2870 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2871 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2872 DAG.getConstant(ExponentBias, DL, VT)); 2873 2874 // For leading zeros, we need to remove the bias and convert from log2 to 2875 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2876 unsigned Adjust = ExponentBias + (EltSize - 1); 2877 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2878 } 2879 2880 // While RVV has alignment restrictions, we should always be able to load as a 2881 // legal equivalently-sized byte-typed vector instead. This method is 2882 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2883 // the load is already correctly-aligned, it returns SDValue(). 2884 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2885 SelectionDAG &DAG) const { 2886 auto *Load = cast<LoadSDNode>(Op); 2887 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2888 2889 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2890 Load->getMemoryVT(), 2891 *Load->getMemOperand())) 2892 return SDValue(); 2893 2894 SDLoc DL(Op); 2895 MVT VT = Op.getSimpleValueType(); 2896 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2897 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2898 "Unexpected unaligned RVV load type"); 2899 MVT NewVT = 2900 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2901 assert(NewVT.isValid() && 2902 "Expecting equally-sized RVV vector types to be legal"); 2903 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2904 Load->getPointerInfo(), Load->getOriginalAlign(), 2905 Load->getMemOperand()->getFlags()); 2906 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2907 } 2908 2909 // While RVV has alignment restrictions, we should always be able to store as a 2910 // legal equivalently-sized byte-typed vector instead. This method is 2911 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2912 // returns SDValue() if the store is already correctly aligned. 2913 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2914 SelectionDAG &DAG) const { 2915 auto *Store = cast<StoreSDNode>(Op); 2916 assert(Store && Store->getValue().getValueType().isVector() && 2917 "Expected vector store"); 2918 2919 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2920 Store->getMemoryVT(), 2921 *Store->getMemOperand())) 2922 return SDValue(); 2923 2924 SDLoc DL(Op); 2925 SDValue StoredVal = Store->getValue(); 2926 MVT VT = StoredVal.getSimpleValueType(); 2927 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2928 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2929 "Unexpected unaligned RVV store type"); 2930 MVT NewVT = 2931 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2932 assert(NewVT.isValid() && 2933 "Expecting equally-sized RVV vector types to be legal"); 2934 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2935 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2936 Store->getPointerInfo(), Store->getOriginalAlign(), 2937 Store->getMemOperand()->getFlags()); 2938 } 2939 2940 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 2941 SelectionDAG &DAG) const { 2942 switch (Op.getOpcode()) { 2943 default: 2944 report_fatal_error("unimplemented operand"); 2945 case ISD::GlobalAddress: 2946 return lowerGlobalAddress(Op, DAG); 2947 case ISD::BlockAddress: 2948 return lowerBlockAddress(Op, DAG); 2949 case ISD::ConstantPool: 2950 return lowerConstantPool(Op, DAG); 2951 case ISD::JumpTable: 2952 return lowerJumpTable(Op, DAG); 2953 case ISD::GlobalTLSAddress: 2954 return lowerGlobalTLSAddress(Op, DAG); 2955 case ISD::SELECT: 2956 return lowerSELECT(Op, DAG); 2957 case ISD::BRCOND: 2958 return lowerBRCOND(Op, DAG); 2959 case ISD::VASTART: 2960 return lowerVASTART(Op, DAG); 2961 case ISD::FRAMEADDR: 2962 return lowerFRAMEADDR(Op, DAG); 2963 case ISD::RETURNADDR: 2964 return lowerRETURNADDR(Op, DAG); 2965 case ISD::SHL_PARTS: 2966 return lowerShiftLeftParts(Op, DAG); 2967 case ISD::SRA_PARTS: 2968 return lowerShiftRightParts(Op, DAG, true); 2969 case ISD::SRL_PARTS: 2970 return lowerShiftRightParts(Op, DAG, false); 2971 case ISD::BITCAST: { 2972 SDLoc DL(Op); 2973 EVT VT = Op.getValueType(); 2974 SDValue Op0 = Op.getOperand(0); 2975 EVT Op0VT = Op0.getValueType(); 2976 MVT XLenVT = Subtarget.getXLenVT(); 2977 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 2978 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 2979 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 2980 return FPConv; 2981 } 2982 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 2983 Subtarget.hasStdExtF()) { 2984 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 2985 SDValue FPConv = 2986 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 2987 return FPConv; 2988 } 2989 2990 // Consider other scalar<->scalar casts as legal if the types are legal. 2991 // Otherwise expand them. 2992 if (!VT.isVector() && !Op0VT.isVector()) { 2993 if (isTypeLegal(VT) && isTypeLegal(Op0VT)) 2994 return Op; 2995 return SDValue(); 2996 } 2997 2998 assert(!VT.isScalableVector() && !Op0VT.isScalableVector() && 2999 "Unexpected types"); 3000 3001 if (VT.isFixedLengthVector()) { 3002 // We can handle fixed length vector bitcasts with a simple replacement 3003 // in isel. 3004 if (Op0VT.isFixedLengthVector()) 3005 return Op; 3006 // When bitcasting from scalar to fixed-length vector, insert the scalar 3007 // into a one-element vector of the result type, and perform a vector 3008 // bitcast. 3009 if (!Op0VT.isVector()) { 3010 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 3011 if (!isTypeLegal(BVT)) 3012 return SDValue(); 3013 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 3014 DAG.getUNDEF(BVT), Op0, 3015 DAG.getConstant(0, DL, XLenVT))); 3016 } 3017 return SDValue(); 3018 } 3019 // Custom-legalize bitcasts from fixed-length vector types to scalar types 3020 // thus: bitcast the vector to a one-element vector type whose element type 3021 // is the same as the result type, and extract the first element. 3022 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 3023 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 3024 if (!isTypeLegal(BVT)) 3025 return SDValue(); 3026 SDValue BVec = DAG.getBitcast(BVT, Op0); 3027 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 3028 DAG.getConstant(0, DL, XLenVT)); 3029 } 3030 return SDValue(); 3031 } 3032 case ISD::INTRINSIC_WO_CHAIN: 3033 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3034 case ISD::INTRINSIC_W_CHAIN: 3035 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3036 case ISD::INTRINSIC_VOID: 3037 return LowerINTRINSIC_VOID(Op, DAG); 3038 case ISD::BSWAP: 3039 case ISD::BITREVERSE: { 3040 MVT VT = Op.getSimpleValueType(); 3041 SDLoc DL(Op); 3042 if (Subtarget.hasStdExtZbp()) { 3043 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3044 // Start with the maximum immediate value which is the bitwidth - 1. 3045 unsigned Imm = VT.getSizeInBits() - 1; 3046 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3047 if (Op.getOpcode() == ISD::BSWAP) 3048 Imm &= ~0x7U; 3049 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3050 DAG.getConstant(Imm, DL, VT)); 3051 } 3052 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3053 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3054 // Expand bitreverse to a bswap(rev8) followed by brev8. 3055 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3056 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3057 // as brev8 by an isel pattern. 3058 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3059 DAG.getConstant(7, DL, VT)); 3060 } 3061 case ISD::FSHL: 3062 case ISD::FSHR: { 3063 MVT VT = Op.getSimpleValueType(); 3064 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3065 SDLoc DL(Op); 3066 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3067 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3068 // accidentally setting the extra bit. 3069 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3070 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3071 DAG.getConstant(ShAmtWidth, DL, VT)); 3072 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3073 // instruction use different orders. fshl will return its first operand for 3074 // shift of zero, fshr will return its second operand. fsl and fsr both 3075 // return rs1 so the ISD nodes need to have different operand orders. 3076 // Shift amount is in rs2. 3077 SDValue Op0 = Op.getOperand(0); 3078 SDValue Op1 = Op.getOperand(1); 3079 unsigned Opc = RISCVISD::FSL; 3080 if (Op.getOpcode() == ISD::FSHR) { 3081 std::swap(Op0, Op1); 3082 Opc = RISCVISD::FSR; 3083 } 3084 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3085 } 3086 case ISD::TRUNCATE: 3087 // Only custom-lower vector truncates 3088 if (!Op.getSimpleValueType().isVector()) 3089 return Op; 3090 return lowerVectorTruncLike(Op, DAG); 3091 case ISD::ANY_EXTEND: 3092 case ISD::ZERO_EXTEND: 3093 if (Op.getOperand(0).getValueType().isVector() && 3094 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3095 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3096 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3097 case ISD::SIGN_EXTEND: 3098 if (Op.getOperand(0).getValueType().isVector() && 3099 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3100 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3101 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3102 case ISD::SPLAT_VECTOR_PARTS: 3103 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3104 case ISD::INSERT_VECTOR_ELT: 3105 return lowerINSERT_VECTOR_ELT(Op, DAG); 3106 case ISD::EXTRACT_VECTOR_ELT: 3107 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3108 case ISD::VSCALE: { 3109 MVT VT = Op.getSimpleValueType(); 3110 SDLoc DL(Op); 3111 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3112 // We define our scalable vector types for lmul=1 to use a 64 bit known 3113 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3114 // vscale as VLENB / 8. 3115 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3116 if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock) 3117 report_fatal_error("Support for VLEN==32 is incomplete."); 3118 // We assume VLENB is a multiple of 8. We manually choose the best shift 3119 // here because SimplifyDemandedBits isn't always able to simplify it. 3120 uint64_t Val = Op.getConstantOperandVal(0); 3121 if (isPowerOf2_64(Val)) { 3122 uint64_t Log2 = Log2_64(Val); 3123 if (Log2 < 3) 3124 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3125 DAG.getConstant(3 - Log2, DL, VT)); 3126 if (Log2 > 3) 3127 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3128 DAG.getConstant(Log2 - 3, DL, VT)); 3129 return VLENB; 3130 } 3131 // If the multiplier is a multiple of 8, scale it down to avoid needing 3132 // to shift the VLENB value. 3133 if ((Val % 8) == 0) 3134 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3135 DAG.getConstant(Val / 8, DL, VT)); 3136 3137 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3138 DAG.getConstant(3, DL, VT)); 3139 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3140 } 3141 case ISD::FPOWI: { 3142 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3143 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3144 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3145 Op.getOperand(1).getValueType() == MVT::i32) { 3146 SDLoc DL(Op); 3147 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3148 SDValue Powi = 3149 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3150 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3151 DAG.getIntPtrConstant(0, DL)); 3152 } 3153 return SDValue(); 3154 } 3155 case ISD::FP_EXTEND: 3156 case ISD::FP_ROUND: 3157 if (!Op.getValueType().isVector()) 3158 return Op; 3159 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3160 case ISD::FP_TO_SINT: 3161 case ISD::FP_TO_UINT: 3162 case ISD::SINT_TO_FP: 3163 case ISD::UINT_TO_FP: { 3164 // RVV can only do fp<->int conversions to types half/double the size as 3165 // the source. We custom-lower any conversions that do two hops into 3166 // sequences. 3167 MVT VT = Op.getSimpleValueType(); 3168 if (!VT.isVector()) 3169 return Op; 3170 SDLoc DL(Op); 3171 SDValue Src = Op.getOperand(0); 3172 MVT EltVT = VT.getVectorElementType(); 3173 MVT SrcVT = Src.getSimpleValueType(); 3174 MVT SrcEltVT = SrcVT.getVectorElementType(); 3175 unsigned EltSize = EltVT.getSizeInBits(); 3176 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3177 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3178 "Unexpected vector element types"); 3179 3180 bool IsInt2FP = SrcEltVT.isInteger(); 3181 // Widening conversions 3182 if (EltSize > (2 * SrcEltSize)) { 3183 if (IsInt2FP) { 3184 // Do a regular integer sign/zero extension then convert to float. 3185 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), 3186 VT.getVectorElementCount()); 3187 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3188 ? ISD::ZERO_EXTEND 3189 : ISD::SIGN_EXTEND; 3190 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3191 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3192 } 3193 // FP2Int 3194 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3195 // Do one doubling fp_extend then complete the operation by converting 3196 // to int. 3197 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3198 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3199 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3200 } 3201 3202 // Narrowing conversions 3203 if (SrcEltSize > (2 * EltSize)) { 3204 if (IsInt2FP) { 3205 // One narrowing int_to_fp, then an fp_round. 3206 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3207 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3208 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3209 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3210 } 3211 // FP2Int 3212 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3213 // representable by the integer, the result is poison. 3214 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 3215 VT.getVectorElementCount()); 3216 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3217 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3218 } 3219 3220 // Scalable vectors can exit here. Patterns will handle equally-sized 3221 // conversions halving/doubling ones. 3222 if (!VT.isFixedLengthVector()) 3223 return Op; 3224 3225 // For fixed-length vectors we lower to a custom "VL" node. 3226 unsigned RVVOpc = 0; 3227 switch (Op.getOpcode()) { 3228 default: 3229 llvm_unreachable("Impossible opcode"); 3230 case ISD::FP_TO_SINT: 3231 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3232 break; 3233 case ISD::FP_TO_UINT: 3234 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3235 break; 3236 case ISD::SINT_TO_FP: 3237 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3238 break; 3239 case ISD::UINT_TO_FP: 3240 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3241 break; 3242 } 3243 3244 MVT ContainerVT, SrcContainerVT; 3245 // Derive the reference container type from the larger vector type. 3246 if (SrcEltSize > EltSize) { 3247 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3248 ContainerVT = 3249 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3250 } else { 3251 ContainerVT = getContainerForFixedLengthVector(VT); 3252 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3253 } 3254 3255 SDValue Mask, VL; 3256 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3257 3258 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3259 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3260 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3261 } 3262 case ISD::FP_TO_SINT_SAT: 3263 case ISD::FP_TO_UINT_SAT: 3264 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3265 case ISD::FTRUNC: 3266 case ISD::FCEIL: 3267 case ISD::FFLOOR: 3268 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3269 case ISD::FROUND: 3270 return lowerFROUND(Op, DAG); 3271 case ISD::VECREDUCE_ADD: 3272 case ISD::VECREDUCE_UMAX: 3273 case ISD::VECREDUCE_SMAX: 3274 case ISD::VECREDUCE_UMIN: 3275 case ISD::VECREDUCE_SMIN: 3276 return lowerVECREDUCE(Op, DAG); 3277 case ISD::VECREDUCE_AND: 3278 case ISD::VECREDUCE_OR: 3279 case ISD::VECREDUCE_XOR: 3280 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3281 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3282 return lowerVECREDUCE(Op, DAG); 3283 case ISD::VECREDUCE_FADD: 3284 case ISD::VECREDUCE_SEQ_FADD: 3285 case ISD::VECREDUCE_FMIN: 3286 case ISD::VECREDUCE_FMAX: 3287 return lowerFPVECREDUCE(Op, DAG); 3288 case ISD::VP_REDUCE_ADD: 3289 case ISD::VP_REDUCE_UMAX: 3290 case ISD::VP_REDUCE_SMAX: 3291 case ISD::VP_REDUCE_UMIN: 3292 case ISD::VP_REDUCE_SMIN: 3293 case ISD::VP_REDUCE_FADD: 3294 case ISD::VP_REDUCE_SEQ_FADD: 3295 case ISD::VP_REDUCE_FMIN: 3296 case ISD::VP_REDUCE_FMAX: 3297 return lowerVPREDUCE(Op, DAG); 3298 case ISD::VP_REDUCE_AND: 3299 case ISD::VP_REDUCE_OR: 3300 case ISD::VP_REDUCE_XOR: 3301 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3302 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3303 return lowerVPREDUCE(Op, DAG); 3304 case ISD::INSERT_SUBVECTOR: 3305 return lowerINSERT_SUBVECTOR(Op, DAG); 3306 case ISD::EXTRACT_SUBVECTOR: 3307 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3308 case ISD::STEP_VECTOR: 3309 return lowerSTEP_VECTOR(Op, DAG); 3310 case ISD::VECTOR_REVERSE: 3311 return lowerVECTOR_REVERSE(Op, DAG); 3312 case ISD::VECTOR_SPLICE: 3313 return lowerVECTOR_SPLICE(Op, DAG); 3314 case ISD::BUILD_VECTOR: 3315 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3316 case ISD::SPLAT_VECTOR: 3317 if (Op.getValueType().getVectorElementType() == MVT::i1) 3318 return lowerVectorMaskSplat(Op, DAG); 3319 return SDValue(); 3320 case ISD::VECTOR_SHUFFLE: 3321 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3322 case ISD::CONCAT_VECTORS: { 3323 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3324 // better than going through the stack, as the default expansion does. 3325 SDLoc DL(Op); 3326 MVT VT = Op.getSimpleValueType(); 3327 unsigned NumOpElts = 3328 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3329 SDValue Vec = DAG.getUNDEF(VT); 3330 for (const auto &OpIdx : enumerate(Op->ops())) { 3331 SDValue SubVec = OpIdx.value(); 3332 // Don't insert undef subvectors. 3333 if (SubVec.isUndef()) 3334 continue; 3335 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3336 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3337 } 3338 return Vec; 3339 } 3340 case ISD::LOAD: 3341 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3342 return V; 3343 if (Op.getValueType().isFixedLengthVector()) 3344 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3345 return Op; 3346 case ISD::STORE: 3347 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3348 return V; 3349 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3350 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3351 return Op; 3352 case ISD::MLOAD: 3353 case ISD::VP_LOAD: 3354 return lowerMaskedLoad(Op, DAG); 3355 case ISD::MSTORE: 3356 case ISD::VP_STORE: 3357 return lowerMaskedStore(Op, DAG); 3358 case ISD::SETCC: 3359 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3360 case ISD::ADD: 3361 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3362 case ISD::SUB: 3363 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3364 case ISD::MUL: 3365 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3366 case ISD::MULHS: 3367 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3368 case ISD::MULHU: 3369 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3370 case ISD::AND: 3371 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3372 RISCVISD::AND_VL); 3373 case ISD::OR: 3374 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3375 RISCVISD::OR_VL); 3376 case ISD::XOR: 3377 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3378 RISCVISD::XOR_VL); 3379 case ISD::SDIV: 3380 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3381 case ISD::SREM: 3382 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3383 case ISD::UDIV: 3384 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3385 case ISD::UREM: 3386 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3387 case ISD::SHL: 3388 case ISD::SRA: 3389 case ISD::SRL: 3390 if (Op.getSimpleValueType().isFixedLengthVector()) 3391 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3392 // This can be called for an i32 shift amount that needs to be promoted. 3393 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3394 "Unexpected custom legalisation"); 3395 return SDValue(); 3396 case ISD::SADDSAT: 3397 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3398 case ISD::UADDSAT: 3399 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3400 case ISD::SSUBSAT: 3401 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3402 case ISD::USUBSAT: 3403 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3404 case ISD::FADD: 3405 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3406 case ISD::FSUB: 3407 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3408 case ISD::FMUL: 3409 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3410 case ISD::FDIV: 3411 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3412 case ISD::FNEG: 3413 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3414 case ISD::FABS: 3415 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3416 case ISD::FSQRT: 3417 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3418 case ISD::FMA: 3419 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3420 case ISD::SMIN: 3421 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3422 case ISD::SMAX: 3423 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3424 case ISD::UMIN: 3425 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3426 case ISD::UMAX: 3427 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3428 case ISD::FMINNUM: 3429 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3430 case ISD::FMAXNUM: 3431 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3432 case ISD::ABS: 3433 return lowerABS(Op, DAG); 3434 case ISD::CTLZ_ZERO_UNDEF: 3435 case ISD::CTTZ_ZERO_UNDEF: 3436 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3437 case ISD::VSELECT: 3438 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3439 case ISD::FCOPYSIGN: 3440 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3441 case ISD::MGATHER: 3442 case ISD::VP_GATHER: 3443 return lowerMaskedGather(Op, DAG); 3444 case ISD::MSCATTER: 3445 case ISD::VP_SCATTER: 3446 return lowerMaskedScatter(Op, DAG); 3447 case ISD::FLT_ROUNDS_: 3448 return lowerGET_ROUNDING(Op, DAG); 3449 case ISD::SET_ROUNDING: 3450 return lowerSET_ROUNDING(Op, DAG); 3451 case ISD::EH_DWARF_CFA: 3452 return lowerEH_DWARF_CFA(Op, DAG); 3453 case ISD::VP_SELECT: 3454 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3455 case ISD::VP_MERGE: 3456 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3457 case ISD::VP_ADD: 3458 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3459 case ISD::VP_SUB: 3460 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3461 case ISD::VP_MUL: 3462 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3463 case ISD::VP_SDIV: 3464 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3465 case ISD::VP_UDIV: 3466 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3467 case ISD::VP_SREM: 3468 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3469 case ISD::VP_UREM: 3470 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3471 case ISD::VP_AND: 3472 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3473 case ISD::VP_OR: 3474 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3475 case ISD::VP_XOR: 3476 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3477 case ISD::VP_ASHR: 3478 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3479 case ISD::VP_LSHR: 3480 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3481 case ISD::VP_SHL: 3482 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3483 case ISD::VP_FADD: 3484 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3485 case ISD::VP_FSUB: 3486 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3487 case ISD::VP_FMUL: 3488 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3489 case ISD::VP_FDIV: 3490 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3491 case ISD::VP_FNEG: 3492 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3493 case ISD::VP_FMA: 3494 return lowerVPOp(Op, DAG, RISCVISD::FMA_VL); 3495 case ISD::VP_SIGN_EXTEND: 3496 case ISD::VP_ZERO_EXTEND: 3497 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3498 return lowerVPExtMaskOp(Op, DAG); 3499 return lowerVPOp(Op, DAG, 3500 Op.getOpcode() == ISD::VP_SIGN_EXTEND 3501 ? RISCVISD::VSEXT_VL 3502 : RISCVISD::VZEXT_VL); 3503 case ISD::VP_TRUNCATE: 3504 return lowerVectorTruncLike(Op, DAG); 3505 case ISD::VP_FP_EXTEND: 3506 case ISD::VP_FP_ROUND: 3507 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3508 case ISD::VP_FPTOSI: 3509 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL); 3510 case ISD::VP_FPTOUI: 3511 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL); 3512 case ISD::VP_SITOFP: 3513 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL); 3514 case ISD::VP_UITOFP: 3515 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL); 3516 case ISD::VP_SETCC: 3517 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3518 return lowerVPSetCCMaskOp(Op, DAG); 3519 return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL); 3520 } 3521 } 3522 3523 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3524 SelectionDAG &DAG, unsigned Flags) { 3525 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3526 } 3527 3528 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3529 SelectionDAG &DAG, unsigned Flags) { 3530 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3531 Flags); 3532 } 3533 3534 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3535 SelectionDAG &DAG, unsigned Flags) { 3536 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3537 N->getOffset(), Flags); 3538 } 3539 3540 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3541 SelectionDAG &DAG, unsigned Flags) { 3542 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3543 } 3544 3545 template <class NodeTy> 3546 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3547 bool IsLocal) const { 3548 SDLoc DL(N); 3549 EVT Ty = getPointerTy(DAG.getDataLayout()); 3550 3551 if (isPositionIndependent()) { 3552 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3553 if (IsLocal) 3554 // Use PC-relative addressing to access the symbol. This generates the 3555 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3556 // %pcrel_lo(auipc)). 3557 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3558 3559 // Use PC-relative addressing to access the GOT for this symbol, then load 3560 // the address from the GOT. This generates the pattern (PseudoLA sym), 3561 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3562 SDValue Load = 3563 SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3564 MachineFunction &MF = DAG.getMachineFunction(); 3565 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3566 MachinePointerInfo::getGOT(MF), 3567 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3568 MachineMemOperand::MOInvariant, 3569 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3570 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3571 return Load; 3572 } 3573 3574 switch (getTargetMachine().getCodeModel()) { 3575 default: 3576 report_fatal_error("Unsupported code model for lowering"); 3577 case CodeModel::Small: { 3578 // Generate a sequence for accessing addresses within the first 2 GiB of 3579 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3580 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3581 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3582 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3583 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3584 } 3585 case CodeModel::Medium: { 3586 // Generate a sequence for accessing addresses within any 2GiB range within 3587 // the address space. This generates the pattern (PseudoLLA sym), which 3588 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3589 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3590 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3591 } 3592 } 3593 } 3594 3595 template SDValue RISCVTargetLowering::getAddr<GlobalAddressSDNode>( 3596 GlobalAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3597 template SDValue RISCVTargetLowering::getAddr<BlockAddressSDNode>( 3598 BlockAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3599 template SDValue RISCVTargetLowering::getAddr<ConstantPoolSDNode>( 3600 ConstantPoolSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3601 template SDValue RISCVTargetLowering::getAddr<JumpTableSDNode>( 3602 JumpTableSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3603 3604 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3605 SelectionDAG &DAG) const { 3606 SDLoc DL(Op); 3607 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3608 assert(N->getOffset() == 0 && "unexpected offset in global node"); 3609 3610 const GlobalValue *GV = N->getGlobal(); 3611 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3612 return getAddr(N, DAG, IsLocal); 3613 } 3614 3615 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3616 SelectionDAG &DAG) const { 3617 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3618 3619 return getAddr(N, DAG); 3620 } 3621 3622 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3623 SelectionDAG &DAG) const { 3624 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3625 3626 return getAddr(N, DAG); 3627 } 3628 3629 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3630 SelectionDAG &DAG) const { 3631 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3632 3633 return getAddr(N, DAG); 3634 } 3635 3636 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3637 SelectionDAG &DAG, 3638 bool UseGOT) const { 3639 SDLoc DL(N); 3640 EVT Ty = getPointerTy(DAG.getDataLayout()); 3641 const GlobalValue *GV = N->getGlobal(); 3642 MVT XLenVT = Subtarget.getXLenVT(); 3643 3644 if (UseGOT) { 3645 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3646 // load the address from the GOT and add the thread pointer. This generates 3647 // the pattern (PseudoLA_TLS_IE sym), which expands to 3648 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3649 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3650 SDValue Load = 3651 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3652 MachineFunction &MF = DAG.getMachineFunction(); 3653 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3654 MachinePointerInfo::getGOT(MF), 3655 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3656 MachineMemOperand::MOInvariant, 3657 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3658 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3659 3660 // Add the thread pointer. 3661 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3662 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3663 } 3664 3665 // Generate a sequence for accessing the address relative to the thread 3666 // pointer, with the appropriate adjustment for the thread pointer offset. 3667 // This generates the pattern 3668 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3669 SDValue AddrHi = 3670 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3671 SDValue AddrAdd = 3672 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3673 SDValue AddrLo = 3674 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3675 3676 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3677 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3678 SDValue MNAdd = SDValue( 3679 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3680 0); 3681 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3682 } 3683 3684 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3685 SelectionDAG &DAG) const { 3686 SDLoc DL(N); 3687 EVT Ty = getPointerTy(DAG.getDataLayout()); 3688 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3689 const GlobalValue *GV = N->getGlobal(); 3690 3691 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3692 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3693 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3694 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3695 SDValue Load = 3696 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3697 3698 // Prepare argument list to generate call. 3699 ArgListTy Args; 3700 ArgListEntry Entry; 3701 Entry.Node = Load; 3702 Entry.Ty = CallTy; 3703 Args.push_back(Entry); 3704 3705 // Setup call to __tls_get_addr. 3706 TargetLowering::CallLoweringInfo CLI(DAG); 3707 CLI.setDebugLoc(DL) 3708 .setChain(DAG.getEntryNode()) 3709 .setLibCallee(CallingConv::C, CallTy, 3710 DAG.getExternalSymbol("__tls_get_addr", Ty), 3711 std::move(Args)); 3712 3713 return LowerCallTo(CLI).first; 3714 } 3715 3716 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3717 SelectionDAG &DAG) const { 3718 SDLoc DL(Op); 3719 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3720 assert(N->getOffset() == 0 && "unexpected offset in global node"); 3721 3722 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3723 3724 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3725 CallingConv::GHC) 3726 report_fatal_error("In GHC calling convention TLS is not supported"); 3727 3728 SDValue Addr; 3729 switch (Model) { 3730 case TLSModel::LocalExec: 3731 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3732 break; 3733 case TLSModel::InitialExec: 3734 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3735 break; 3736 case TLSModel::LocalDynamic: 3737 case TLSModel::GeneralDynamic: 3738 Addr = getDynamicTLSAddr(N, DAG); 3739 break; 3740 } 3741 3742 return Addr; 3743 } 3744 3745 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3746 SDValue CondV = Op.getOperand(0); 3747 SDValue TrueV = Op.getOperand(1); 3748 SDValue FalseV = Op.getOperand(2); 3749 SDLoc DL(Op); 3750 MVT VT = Op.getSimpleValueType(); 3751 MVT XLenVT = Subtarget.getXLenVT(); 3752 3753 // Lower vector SELECTs to VSELECTs by splatting the condition. 3754 if (VT.isVector()) { 3755 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3756 SDValue CondSplat = VT.isScalableVector() 3757 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3758 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3759 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3760 } 3761 3762 // If the result type is XLenVT and CondV is the output of a SETCC node 3763 // which also operated on XLenVT inputs, then merge the SETCC node into the 3764 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3765 // compare+branch instructions. i.e.: 3766 // (select (setcc lhs, rhs, cc), truev, falsev) 3767 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3768 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3769 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3770 SDValue LHS = CondV.getOperand(0); 3771 SDValue RHS = CondV.getOperand(1); 3772 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3773 ISD::CondCode CCVal = CC->get(); 3774 3775 // Special case for a select of 2 constants that have a diffence of 1. 3776 // Normally this is done by DAGCombine, but if the select is introduced by 3777 // type legalization or op legalization, we miss it. Restricting to SETLT 3778 // case for now because that is what signed saturating add/sub need. 3779 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3780 // but we would probably want to swap the true/false values if the condition 3781 // is SETGE/SETLE to avoid an XORI. 3782 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3783 CCVal == ISD::SETLT) { 3784 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3785 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3786 if (TrueVal - 1 == FalseVal) 3787 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3788 if (TrueVal + 1 == FalseVal) 3789 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3790 } 3791 3792 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3793 3794 SDValue TargetCC = DAG.getCondCode(CCVal); 3795 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3796 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3797 } 3798 3799 // Otherwise: 3800 // (select condv, truev, falsev) 3801 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3802 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3803 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3804 3805 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3806 3807 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3808 } 3809 3810 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3811 SDValue CondV = Op.getOperand(1); 3812 SDLoc DL(Op); 3813 MVT XLenVT = Subtarget.getXLenVT(); 3814 3815 if (CondV.getOpcode() == ISD::SETCC && 3816 CondV.getOperand(0).getValueType() == XLenVT) { 3817 SDValue LHS = CondV.getOperand(0); 3818 SDValue RHS = CondV.getOperand(1); 3819 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3820 3821 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3822 3823 SDValue TargetCC = DAG.getCondCode(CCVal); 3824 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3825 LHS, RHS, TargetCC, Op.getOperand(2)); 3826 } 3827 3828 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3829 CondV, DAG.getConstant(0, DL, XLenVT), 3830 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3831 } 3832 3833 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3834 MachineFunction &MF = DAG.getMachineFunction(); 3835 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3836 3837 SDLoc DL(Op); 3838 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3839 getPointerTy(MF.getDataLayout())); 3840 3841 // vastart just stores the address of the VarArgsFrameIndex slot into the 3842 // memory location argument. 3843 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3844 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3845 MachinePointerInfo(SV)); 3846 } 3847 3848 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3849 SelectionDAG &DAG) const { 3850 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3851 MachineFunction &MF = DAG.getMachineFunction(); 3852 MachineFrameInfo &MFI = MF.getFrameInfo(); 3853 MFI.setFrameAddressIsTaken(true); 3854 Register FrameReg = RI.getFrameRegister(MF); 3855 int XLenInBytes = Subtarget.getXLen() / 8; 3856 3857 EVT VT = Op.getValueType(); 3858 SDLoc DL(Op); 3859 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3860 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3861 while (Depth--) { 3862 int Offset = -(XLenInBytes * 2); 3863 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3864 DAG.getIntPtrConstant(Offset, DL)); 3865 FrameAddr = 3866 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3867 } 3868 return FrameAddr; 3869 } 3870 3871 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3872 SelectionDAG &DAG) const { 3873 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3874 MachineFunction &MF = DAG.getMachineFunction(); 3875 MachineFrameInfo &MFI = MF.getFrameInfo(); 3876 MFI.setReturnAddressIsTaken(true); 3877 MVT XLenVT = Subtarget.getXLenVT(); 3878 int XLenInBytes = Subtarget.getXLen() / 8; 3879 3880 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3881 return SDValue(); 3882 3883 EVT VT = Op.getValueType(); 3884 SDLoc DL(Op); 3885 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3886 if (Depth) { 3887 int Off = -XLenInBytes; 3888 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3889 SDValue Offset = DAG.getConstant(Off, DL, VT); 3890 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3891 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3892 MachinePointerInfo()); 3893 } 3894 3895 // Return the value of the return address register, marking it an implicit 3896 // live-in. 3897 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3898 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3899 } 3900 3901 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3902 SelectionDAG &DAG) const { 3903 SDLoc DL(Op); 3904 SDValue Lo = Op.getOperand(0); 3905 SDValue Hi = Op.getOperand(1); 3906 SDValue Shamt = Op.getOperand(2); 3907 EVT VT = Lo.getValueType(); 3908 3909 // if Shamt-XLEN < 0: // Shamt < XLEN 3910 // Lo = Lo << Shamt 3911 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 3912 // else: 3913 // Lo = 0 3914 // Hi = Lo << (Shamt-XLEN) 3915 3916 SDValue Zero = DAG.getConstant(0, DL, VT); 3917 SDValue One = DAG.getConstant(1, DL, VT); 3918 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3919 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3920 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3921 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 3922 3923 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3924 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3925 SDValue ShiftRightLo = 3926 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3927 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3928 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3929 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3930 3931 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3932 3933 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3934 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3935 3936 SDValue Parts[2] = {Lo, Hi}; 3937 return DAG.getMergeValues(Parts, DL); 3938 } 3939 3940 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 3941 bool IsSRA) const { 3942 SDLoc DL(Op); 3943 SDValue Lo = Op.getOperand(0); 3944 SDValue Hi = Op.getOperand(1); 3945 SDValue Shamt = Op.getOperand(2); 3946 EVT VT = Lo.getValueType(); 3947 3948 // SRA expansion: 3949 // if Shamt-XLEN < 0: // Shamt < XLEN 3950 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 3951 // Hi = Hi >>s Shamt 3952 // else: 3953 // Lo = Hi >>s (Shamt-XLEN); 3954 // Hi = Hi >>s (XLEN-1) 3955 // 3956 // SRL expansion: 3957 // if Shamt-XLEN < 0: // Shamt < XLEN 3958 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 3959 // Hi = Hi >>u Shamt 3960 // else: 3961 // Lo = Hi >>u (Shamt-XLEN); 3962 // Hi = 0; 3963 3964 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 3965 3966 SDValue Zero = DAG.getConstant(0, DL, VT); 3967 SDValue One = DAG.getConstant(1, DL, VT); 3968 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3969 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3970 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3971 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 3972 3973 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 3974 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 3975 SDValue ShiftLeftHi = 3976 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 3977 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 3978 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 3979 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 3980 SDValue HiFalse = 3981 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 3982 3983 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3984 3985 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 3986 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3987 3988 SDValue Parts[2] = {Lo, Hi}; 3989 return DAG.getMergeValues(Parts, DL); 3990 } 3991 3992 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 3993 // legal equivalently-sized i8 type, so we can use that as a go-between. 3994 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 3995 SelectionDAG &DAG) const { 3996 SDLoc DL(Op); 3997 MVT VT = Op.getSimpleValueType(); 3998 SDValue SplatVal = Op.getOperand(0); 3999 // All-zeros or all-ones splats are handled specially. 4000 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4001 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4002 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4003 } 4004 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4005 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4006 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4007 } 4008 MVT XLenVT = Subtarget.getXLenVT(); 4009 assert(SplatVal.getValueType() == XLenVT && 4010 "Unexpected type for i1 splat value"); 4011 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4012 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4013 DAG.getConstant(1, DL, XLenVT)); 4014 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4015 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4016 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4017 } 4018 4019 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4020 // illegal (currently only vXi64 RV32). 4021 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4022 // them to VMV_V_X_VL. 4023 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4024 SelectionDAG &DAG) const { 4025 SDLoc DL(Op); 4026 MVT VecVT = Op.getSimpleValueType(); 4027 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4028 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4029 4030 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4031 SDValue Lo = Op.getOperand(0); 4032 SDValue Hi = Op.getOperand(1); 4033 4034 if (VecVT.isFixedLengthVector()) { 4035 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4036 SDLoc DL(Op); 4037 SDValue Mask, VL; 4038 std::tie(Mask, VL) = 4039 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4040 4041 SDValue Res = 4042 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4043 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4044 } 4045 4046 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4047 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4048 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4049 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4050 // node in order to try and match RVV vector/scalar instructions. 4051 if ((LoC >> 31) == HiC) 4052 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4053 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4054 } 4055 4056 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4057 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4058 isa<ConstantSDNode>(Hi.getOperand(1)) && 4059 Hi.getConstantOperandVal(1) == 31) 4060 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4061 DAG.getRegister(RISCV::X0, MVT::i32)); 4062 4063 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4064 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4065 DAG.getUNDEF(VecVT), Lo, Hi, 4066 DAG.getRegister(RISCV::X0, MVT::i32)); 4067 } 4068 4069 // Custom-lower extensions from mask vectors by using a vselect either with 1 4070 // for zero/any-extension or -1 for sign-extension: 4071 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4072 // Note that any-extension is lowered identically to zero-extension. 4073 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4074 int64_t ExtTrueVal) const { 4075 SDLoc DL(Op); 4076 MVT VecVT = Op.getSimpleValueType(); 4077 SDValue Src = Op.getOperand(0); 4078 // Only custom-lower extensions from mask types 4079 assert(Src.getValueType().isVector() && 4080 Src.getValueType().getVectorElementType() == MVT::i1); 4081 4082 if (VecVT.isScalableVector()) { 4083 SDValue SplatZero = DAG.getConstant(0, DL, VecVT); 4084 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT); 4085 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4086 } 4087 4088 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4089 MVT I1ContainerVT = 4090 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4091 4092 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4093 4094 SDValue Mask, VL; 4095 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4096 4097 MVT XLenVT = Subtarget.getXLenVT(); 4098 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4099 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4100 4101 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4102 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4103 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4104 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4105 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4106 SplatTrueVal, SplatZero, VL); 4107 4108 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4109 } 4110 4111 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4112 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4113 MVT ExtVT = Op.getSimpleValueType(); 4114 // Only custom-lower extensions from fixed-length vector types. 4115 if (!ExtVT.isFixedLengthVector()) 4116 return Op; 4117 MVT VT = Op.getOperand(0).getSimpleValueType(); 4118 // Grab the canonical container type for the extended type. Infer the smaller 4119 // type from that to ensure the same number of vector elements, as we know 4120 // the LMUL will be sufficient to hold the smaller type. 4121 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4122 // Get the extended container type manually to ensure the same number of 4123 // vector elements between source and dest. 4124 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4125 ContainerExtVT.getVectorElementCount()); 4126 4127 SDValue Op1 = 4128 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4129 4130 SDLoc DL(Op); 4131 SDValue Mask, VL; 4132 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4133 4134 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4135 4136 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4137 } 4138 4139 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4140 // setcc operation: 4141 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4142 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op, 4143 SelectionDAG &DAG) const { 4144 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4145 SDLoc DL(Op); 4146 EVT MaskVT = Op.getValueType(); 4147 // Only expect to custom-lower truncations to mask types 4148 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4149 "Unexpected type for vector mask lowering"); 4150 SDValue Src = Op.getOperand(0); 4151 MVT VecVT = Src.getSimpleValueType(); 4152 SDValue Mask, VL; 4153 if (IsVPTrunc) { 4154 Mask = Op.getOperand(1); 4155 VL = Op.getOperand(2); 4156 } 4157 // If this is a fixed vector, we need to convert it to a scalable vector. 4158 MVT ContainerVT = VecVT; 4159 4160 if (VecVT.isFixedLengthVector()) { 4161 ContainerVT = getContainerForFixedLengthVector(VecVT); 4162 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4163 if (IsVPTrunc) { 4164 MVT MaskContainerVT = 4165 getContainerForFixedLengthVector(Mask.getSimpleValueType()); 4166 Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget); 4167 } 4168 } 4169 4170 if (!IsVPTrunc) { 4171 std::tie(Mask, VL) = 4172 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4173 } 4174 4175 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4176 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4177 4178 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4179 DAG.getUNDEF(ContainerVT), SplatOne, VL); 4180 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4181 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4182 4183 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4184 SDValue Trunc = 4185 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4186 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4187 DAG.getCondCode(ISD::SETNE), Mask, VL); 4188 if (MaskVT.isFixedLengthVector()) 4189 Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4190 return Trunc; 4191 } 4192 4193 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op, 4194 SelectionDAG &DAG) const { 4195 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4196 SDLoc DL(Op); 4197 4198 MVT VT = Op.getSimpleValueType(); 4199 // Only custom-lower vector truncates 4200 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4201 4202 // Truncates to mask types are handled differently 4203 if (VT.getVectorElementType() == MVT::i1) 4204 return lowerVectorMaskTruncLike(Op, DAG); 4205 4206 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 4207 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 4208 // truncate by one power of two at a time. 4209 MVT DstEltVT = VT.getVectorElementType(); 4210 4211 SDValue Src = Op.getOperand(0); 4212 MVT SrcVT = Src.getSimpleValueType(); 4213 MVT SrcEltVT = SrcVT.getVectorElementType(); 4214 4215 assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) && 4216 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 4217 "Unexpected vector truncate lowering"); 4218 4219 MVT ContainerVT = SrcVT; 4220 SDValue Mask, VL; 4221 if (IsVPTrunc) { 4222 Mask = Op.getOperand(1); 4223 VL = Op.getOperand(2); 4224 } 4225 if (SrcVT.isFixedLengthVector()) { 4226 ContainerVT = getContainerForFixedLengthVector(SrcVT); 4227 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4228 if (IsVPTrunc) { 4229 MVT MaskVT = getMaskTypeFor(ContainerVT); 4230 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4231 } 4232 } 4233 4234 SDValue Result = Src; 4235 if (!IsVPTrunc) { 4236 std::tie(Mask, VL) = 4237 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4238 } 4239 4240 LLVMContext &Context = *DAG.getContext(); 4241 const ElementCount Count = ContainerVT.getVectorElementCount(); 4242 do { 4243 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 4244 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 4245 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 4246 Mask, VL); 4247 } while (SrcEltVT != DstEltVT); 4248 4249 if (SrcVT.isFixedLengthVector()) 4250 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4251 4252 return Result; 4253 } 4254 4255 SDValue 4256 RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op, 4257 SelectionDAG &DAG) const { 4258 bool IsVP = 4259 Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND; 4260 bool IsExtend = 4261 Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND; 4262 // RVV can only do truncate fp to types half the size as the source. We 4263 // custom-lower f64->f16 rounds via RVV's round-to-odd float 4264 // conversion instruction. 4265 SDLoc DL(Op); 4266 MVT VT = Op.getSimpleValueType(); 4267 4268 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4269 4270 SDValue Src = Op.getOperand(0); 4271 MVT SrcVT = Src.getSimpleValueType(); 4272 4273 bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 || 4274 SrcVT.getVectorElementType() != MVT::f16); 4275 bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 || 4276 SrcVT.getVectorElementType() != MVT::f64); 4277 4278 bool IsDirectConv = IsDirectExtend || IsDirectTrunc; 4279 4280 // Prepare any fixed-length vector operands. 4281 MVT ContainerVT = VT; 4282 SDValue Mask, VL; 4283 if (IsVP) { 4284 Mask = Op.getOperand(1); 4285 VL = Op.getOperand(2); 4286 } 4287 if (VT.isFixedLengthVector()) { 4288 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 4289 ContainerVT = 4290 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 4291 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 4292 if (IsVP) { 4293 MVT MaskVT = getMaskTypeFor(ContainerVT); 4294 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4295 } 4296 } 4297 4298 if (!IsVP) 4299 std::tie(Mask, VL) = 4300 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4301 4302 unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL; 4303 4304 if (IsDirectConv) { 4305 Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL); 4306 if (VT.isFixedLengthVector()) 4307 Src = convertFromScalableVector(VT, Src, DAG, Subtarget); 4308 return Src; 4309 } 4310 4311 unsigned InterConvOpc = 4312 IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL; 4313 4314 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 4315 SDValue IntermediateConv = 4316 DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL); 4317 SDValue Result = 4318 DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL); 4319 if (VT.isFixedLengthVector()) 4320 return convertFromScalableVector(VT, Result, DAG, Subtarget); 4321 return Result; 4322 } 4323 4324 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4325 // first position of a vector, and that vector is slid up to the insert index. 4326 // By limiting the active vector length to index+1 and merging with the 4327 // original vector (with an undisturbed tail policy for elements >= VL), we 4328 // achieve the desired result of leaving all elements untouched except the one 4329 // at VL-1, which is replaced with the desired value. 4330 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4331 SelectionDAG &DAG) const { 4332 SDLoc DL(Op); 4333 MVT VecVT = Op.getSimpleValueType(); 4334 SDValue Vec = Op.getOperand(0); 4335 SDValue Val = Op.getOperand(1); 4336 SDValue Idx = Op.getOperand(2); 4337 4338 if (VecVT.getVectorElementType() == MVT::i1) { 4339 // FIXME: For now we just promote to an i8 vector and insert into that, 4340 // but this is probably not optimal. 4341 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4342 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4343 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4344 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4345 } 4346 4347 MVT ContainerVT = VecVT; 4348 // If the operand is a fixed-length vector, convert to a scalable one. 4349 if (VecVT.isFixedLengthVector()) { 4350 ContainerVT = getContainerForFixedLengthVector(VecVT); 4351 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4352 } 4353 4354 MVT XLenVT = Subtarget.getXLenVT(); 4355 4356 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4357 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4358 // Even i64-element vectors on RV32 can be lowered without scalar 4359 // legalization if the most-significant 32 bits of the value are not affected 4360 // by the sign-extension of the lower 32 bits. 4361 // TODO: We could also catch sign extensions of a 32-bit value. 4362 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4363 const auto *CVal = cast<ConstantSDNode>(Val); 4364 if (isInt<32>(CVal->getSExtValue())) { 4365 IsLegalInsert = true; 4366 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4367 } 4368 } 4369 4370 SDValue Mask, VL; 4371 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4372 4373 SDValue ValInVec; 4374 4375 if (IsLegalInsert) { 4376 unsigned Opc = 4377 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4378 if (isNullConstant(Idx)) { 4379 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4380 if (!VecVT.isFixedLengthVector()) 4381 return Vec; 4382 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4383 } 4384 ValInVec = 4385 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4386 } else { 4387 // On RV32, i64-element vectors must be specially handled to place the 4388 // value at element 0, by using two vslide1up instructions in sequence on 4389 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4390 // this. 4391 SDValue One = DAG.getConstant(1, DL, XLenVT); 4392 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4393 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4394 MVT I32ContainerVT = 4395 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4396 SDValue I32Mask = 4397 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4398 // Limit the active VL to two. 4399 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4400 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4401 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4402 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4403 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4404 // First slide in the hi value, then the lo in underneath it. 4405 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4406 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4407 I32Mask, InsertI64VL); 4408 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4409 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4410 I32Mask, InsertI64VL); 4411 // Bitcast back to the right container type. 4412 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4413 } 4414 4415 // Now that the value is in a vector, slide it into position. 4416 SDValue InsertVL = 4417 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4418 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4419 ValInVec, Idx, Mask, InsertVL); 4420 if (!VecVT.isFixedLengthVector()) 4421 return Slideup; 4422 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4423 } 4424 4425 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4426 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4427 // types this is done using VMV_X_S to allow us to glean information about the 4428 // sign bits of the result. 4429 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4430 SelectionDAG &DAG) const { 4431 SDLoc DL(Op); 4432 SDValue Idx = Op.getOperand(1); 4433 SDValue Vec = Op.getOperand(0); 4434 EVT EltVT = Op.getValueType(); 4435 MVT VecVT = Vec.getSimpleValueType(); 4436 MVT XLenVT = Subtarget.getXLenVT(); 4437 4438 if (VecVT.getVectorElementType() == MVT::i1) { 4439 if (VecVT.isFixedLengthVector()) { 4440 unsigned NumElts = VecVT.getVectorNumElements(); 4441 if (NumElts >= 8) { 4442 MVT WideEltVT; 4443 unsigned WidenVecLen; 4444 SDValue ExtractElementIdx; 4445 SDValue ExtractBitIdx; 4446 unsigned MaxEEW = Subtarget.getELEN(); 4447 MVT LargestEltVT = MVT::getIntegerVT( 4448 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4449 if (NumElts <= LargestEltVT.getSizeInBits()) { 4450 assert(isPowerOf2_32(NumElts) && 4451 "the number of elements should be power of 2"); 4452 WideEltVT = MVT::getIntegerVT(NumElts); 4453 WidenVecLen = 1; 4454 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4455 ExtractBitIdx = Idx; 4456 } else { 4457 WideEltVT = LargestEltVT; 4458 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4459 // extract element index = index / element width 4460 ExtractElementIdx = DAG.getNode( 4461 ISD::SRL, DL, XLenVT, Idx, 4462 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4463 // mask bit index = index % element width 4464 ExtractBitIdx = DAG.getNode( 4465 ISD::AND, DL, XLenVT, Idx, 4466 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4467 } 4468 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4469 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4470 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4471 Vec, ExtractElementIdx); 4472 // Extract the bit from GPR. 4473 SDValue ShiftRight = 4474 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4475 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4476 DAG.getConstant(1, DL, XLenVT)); 4477 } 4478 } 4479 // Otherwise, promote to an i8 vector and extract from that. 4480 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4481 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4482 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4483 } 4484 4485 // If this is a fixed vector, we need to convert it to a scalable vector. 4486 MVT ContainerVT = VecVT; 4487 if (VecVT.isFixedLengthVector()) { 4488 ContainerVT = getContainerForFixedLengthVector(VecVT); 4489 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4490 } 4491 4492 // If the index is 0, the vector is already in the right position. 4493 if (!isNullConstant(Idx)) { 4494 // Use a VL of 1 to avoid processing more elements than we need. 4495 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4496 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 4497 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4498 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4499 } 4500 4501 if (!EltVT.isInteger()) { 4502 // Floating-point extracts are handled in TableGen. 4503 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4504 DAG.getConstant(0, DL, XLenVT)); 4505 } 4506 4507 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4508 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4509 } 4510 4511 // Some RVV intrinsics may claim that they want an integer operand to be 4512 // promoted or expanded. 4513 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG, 4514 const RISCVSubtarget &Subtarget) { 4515 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4516 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4517 "Unexpected opcode"); 4518 4519 if (!Subtarget.hasVInstructions()) 4520 return SDValue(); 4521 4522 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4523 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4524 SDLoc DL(Op); 4525 4526 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4527 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4528 if (!II || !II->hasScalarOperand()) 4529 return SDValue(); 4530 4531 unsigned SplatOp = II->ScalarOperand + 1 + HasChain; 4532 assert(SplatOp < Op.getNumOperands()); 4533 4534 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4535 SDValue &ScalarOp = Operands[SplatOp]; 4536 MVT OpVT = ScalarOp.getSimpleValueType(); 4537 MVT XLenVT = Subtarget.getXLenVT(); 4538 4539 // If this isn't a scalar, or its type is XLenVT we're done. 4540 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4541 return SDValue(); 4542 4543 // Simplest case is that the operand needs to be promoted to XLenVT. 4544 if (OpVT.bitsLT(XLenVT)) { 4545 // If the operand is a constant, sign extend to increase our chances 4546 // of being able to use a .vi instruction. ANY_EXTEND would become a 4547 // a zero extend and the simm5 check in isel would fail. 4548 // FIXME: Should we ignore the upper bits in isel instead? 4549 unsigned ExtOpc = 4550 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4551 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4552 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4553 } 4554 4555 // Use the previous operand to get the vXi64 VT. The result might be a mask 4556 // VT for compares. Using the previous operand assumes that the previous 4557 // operand will never have a smaller element size than a scalar operand and 4558 // that a widening operation never uses SEW=64. 4559 // NOTE: If this fails the below assert, we can probably just find the 4560 // element count from any operand or result and use it to construct the VT. 4561 assert(II->ScalarOperand > 0 && "Unexpected splat operand!"); 4562 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4563 4564 // The more complex case is when the scalar is larger than XLenVT. 4565 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4566 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4567 4568 // If this is a sign-extended 32-bit value, we can truncate it and rely on the 4569 // instruction to sign-extend since SEW>XLEN. 4570 if (DAG.ComputeNumSignBits(ScalarOp) > 32) { 4571 ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp); 4572 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4573 } 4574 4575 switch (IntNo) { 4576 case Intrinsic::riscv_vslide1up: 4577 case Intrinsic::riscv_vslide1down: 4578 case Intrinsic::riscv_vslide1up_mask: 4579 case Intrinsic::riscv_vslide1down_mask: { 4580 // We need to special case these when the scalar is larger than XLen. 4581 unsigned NumOps = Op.getNumOperands(); 4582 bool IsMasked = NumOps == 7; 4583 4584 // Convert the vector source to the equivalent nxvXi32 vector. 4585 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4586 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4587 4588 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4589 DAG.getConstant(0, DL, XLenVT)); 4590 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4591 DAG.getConstant(1, DL, XLenVT)); 4592 4593 // Double the VL since we halved SEW. 4594 SDValue AVL = getVLOperand(Op); 4595 SDValue I32VL; 4596 4597 // Optimize for constant AVL 4598 if (isa<ConstantSDNode>(AVL)) { 4599 unsigned EltSize = VT.getScalarSizeInBits(); 4600 unsigned MinSize = VT.getSizeInBits().getKnownMinValue(); 4601 4602 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 4603 unsigned MaxVLMAX = 4604 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 4605 4606 unsigned VectorBitsMin = Subtarget.getRealMinVLen(); 4607 unsigned MinVLMAX = 4608 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize); 4609 4610 uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue(); 4611 if (AVLInt <= MinVLMAX) { 4612 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT); 4613 } else if (AVLInt >= 2 * MaxVLMAX) { 4614 // Just set vl to VLMAX in this situation 4615 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT); 4616 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4617 unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits()); 4618 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4619 SDValue SETVLMAX = DAG.getTargetConstant( 4620 Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32); 4621 I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW, 4622 LMUL); 4623 } else { 4624 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl 4625 // is related to the hardware implementation. 4626 // So let the following code handle 4627 } 4628 } 4629 if (!I32VL) { 4630 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT); 4631 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4632 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits()); 4633 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4634 SDValue SETVL = 4635 DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32); 4636 // Using vsetvli instruction to get actually used length which related to 4637 // the hardware implementation 4638 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL, 4639 SEW, LMUL); 4640 I32VL = 4641 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4642 } 4643 4644 SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG); 4645 4646 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4647 // instructions. 4648 SDValue Passthru; 4649 if (IsMasked) 4650 Passthru = DAG.getUNDEF(I32VT); 4651 else 4652 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4653 4654 if (IntNo == Intrinsic::riscv_vslide1up || 4655 IntNo == Intrinsic::riscv_vslide1up_mask) { 4656 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4657 ScalarHi, I32Mask, I32VL); 4658 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4659 ScalarLo, I32Mask, I32VL); 4660 } else { 4661 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4662 ScalarLo, I32Mask, I32VL); 4663 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4664 ScalarHi, I32Mask, I32VL); 4665 } 4666 4667 // Convert back to nxvXi64. 4668 Vec = DAG.getBitcast(VT, Vec); 4669 4670 if (!IsMasked) 4671 return Vec; 4672 // Apply mask after the operation. 4673 SDValue Mask = Operands[NumOps - 3]; 4674 SDValue MaskedOff = Operands[1]; 4675 // Assume Policy operand is the last operand. 4676 uint64_t Policy = 4677 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4678 // We don't need to select maskedoff if it's undef. 4679 if (MaskedOff.isUndef()) 4680 return Vec; 4681 // TAMU 4682 if (Policy == RISCVII::TAIL_AGNOSTIC) 4683 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4684 AVL); 4685 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4686 // It's fine because vmerge does not care mask policy. 4687 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, 4688 AVL); 4689 } 4690 } 4691 4692 // We need to convert the scalar to a splat vector. 4693 SDValue VL = getVLOperand(Op); 4694 assert(VL.getValueType() == XLenVT); 4695 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4696 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4697 } 4698 4699 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4700 SelectionDAG &DAG) const { 4701 unsigned IntNo = Op.getConstantOperandVal(0); 4702 SDLoc DL(Op); 4703 MVT XLenVT = Subtarget.getXLenVT(); 4704 4705 switch (IntNo) { 4706 default: 4707 break; // Don't custom lower most intrinsics. 4708 case Intrinsic::thread_pointer: { 4709 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4710 return DAG.getRegister(RISCV::X4, PtrVT); 4711 } 4712 case Intrinsic::riscv_orc_b: 4713 case Intrinsic::riscv_brev8: { 4714 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4715 unsigned Opc = 4716 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4717 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4718 DAG.getConstant(7, DL, XLenVT)); 4719 } 4720 case Intrinsic::riscv_grev: 4721 case Intrinsic::riscv_gorc: { 4722 unsigned Opc = 4723 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4724 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4725 } 4726 case Intrinsic::riscv_zip: 4727 case Intrinsic::riscv_unzip: { 4728 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4729 // For i32 the immediate is 15. For i64 the immediate is 31. 4730 unsigned Opc = 4731 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4732 unsigned BitWidth = Op.getValueSizeInBits(); 4733 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4734 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4735 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4736 } 4737 case Intrinsic::riscv_shfl: 4738 case Intrinsic::riscv_unshfl: { 4739 unsigned Opc = 4740 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4741 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4742 } 4743 case Intrinsic::riscv_bcompress: 4744 case Intrinsic::riscv_bdecompress: { 4745 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4746 : RISCVISD::BDECOMPRESS; 4747 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4748 } 4749 case Intrinsic::riscv_bfp: 4750 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4751 Op.getOperand(2)); 4752 case Intrinsic::riscv_fsl: 4753 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4754 Op.getOperand(2), Op.getOperand(3)); 4755 case Intrinsic::riscv_fsr: 4756 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4757 Op.getOperand(2), Op.getOperand(3)); 4758 case Intrinsic::riscv_vmv_x_s: 4759 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4760 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4761 Op.getOperand(1)); 4762 case Intrinsic::riscv_vmv_v_x: 4763 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4764 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4765 Subtarget); 4766 case Intrinsic::riscv_vfmv_v_f: 4767 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4768 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4769 case Intrinsic::riscv_vmv_s_x: { 4770 SDValue Scalar = Op.getOperand(2); 4771 4772 if (Scalar.getValueType().bitsLE(XLenVT)) { 4773 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4774 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4775 Op.getOperand(1), Scalar, Op.getOperand(3)); 4776 } 4777 4778 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4779 4780 // This is an i64 value that lives in two scalar registers. We have to 4781 // insert this in a convoluted way. First we build vXi64 splat containing 4782 // the two values that we assemble using some bit math. Next we'll use 4783 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4784 // to merge element 0 from our splat into the source vector. 4785 // FIXME: This is probably not the best way to do this, but it is 4786 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4787 // point. 4788 // sw lo, (a0) 4789 // sw hi, 4(a0) 4790 // vlse vX, (a0) 4791 // 4792 // vid.v vVid 4793 // vmseq.vx mMask, vVid, 0 4794 // vmerge.vvm vDest, vSrc, vVal, mMask 4795 MVT VT = Op.getSimpleValueType(); 4796 SDValue Vec = Op.getOperand(1); 4797 SDValue VL = getVLOperand(Op); 4798 4799 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4800 if (Op.getOperand(1).isUndef()) 4801 return SplattedVal; 4802 SDValue SplattedIdx = 4803 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4804 DAG.getConstant(0, DL, MVT::i32), VL); 4805 4806 MVT MaskVT = getMaskTypeFor(VT); 4807 SDValue Mask = getAllOnesMask(VT, VL, DL, DAG); 4808 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4809 SDValue SelectCond = 4810 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4811 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4812 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4813 Vec, VL); 4814 } 4815 } 4816 4817 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4818 } 4819 4820 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4821 SelectionDAG &DAG) const { 4822 unsigned IntNo = Op.getConstantOperandVal(1); 4823 switch (IntNo) { 4824 default: 4825 break; 4826 case Intrinsic::riscv_masked_strided_load: { 4827 SDLoc DL(Op); 4828 MVT XLenVT = Subtarget.getXLenVT(); 4829 4830 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4831 // the selection of the masked intrinsics doesn't do this for us. 4832 SDValue Mask = Op.getOperand(5); 4833 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4834 4835 MVT VT = Op->getSimpleValueType(0); 4836 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4837 4838 SDValue PassThru = Op.getOperand(2); 4839 if (!IsUnmasked) { 4840 MVT MaskVT = getMaskTypeFor(ContainerVT); 4841 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4842 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4843 } 4844 4845 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4846 4847 SDValue IntID = DAG.getTargetConstant( 4848 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4849 XLenVT); 4850 4851 auto *Load = cast<MemIntrinsicSDNode>(Op); 4852 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4853 if (IsUnmasked) 4854 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4855 else 4856 Ops.push_back(PassThru); 4857 Ops.push_back(Op.getOperand(3)); // Ptr 4858 Ops.push_back(Op.getOperand(4)); // Stride 4859 if (!IsUnmasked) 4860 Ops.push_back(Mask); 4861 Ops.push_back(VL); 4862 if (!IsUnmasked) { 4863 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4864 Ops.push_back(Policy); 4865 } 4866 4867 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4868 SDValue Result = 4869 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4870 Load->getMemoryVT(), Load->getMemOperand()); 4871 SDValue Chain = Result.getValue(1); 4872 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4873 return DAG.getMergeValues({Result, Chain}, DL); 4874 } 4875 case Intrinsic::riscv_seg2_load: 4876 case Intrinsic::riscv_seg3_load: 4877 case Intrinsic::riscv_seg4_load: 4878 case Intrinsic::riscv_seg5_load: 4879 case Intrinsic::riscv_seg6_load: 4880 case Intrinsic::riscv_seg7_load: 4881 case Intrinsic::riscv_seg8_load: { 4882 SDLoc DL(Op); 4883 static const Intrinsic::ID VlsegInts[7] = { 4884 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 4885 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 4886 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 4887 Intrinsic::riscv_vlseg8}; 4888 unsigned NF = Op->getNumValues() - 1; 4889 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 4890 MVT XLenVT = Subtarget.getXLenVT(); 4891 MVT VT = Op->getSimpleValueType(0); 4892 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4893 4894 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4895 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 4896 auto *Load = cast<MemIntrinsicSDNode>(Op); 4897 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 4898 ContainerVTs.push_back(MVT::Other); 4899 SDVTList VTs = DAG.getVTList(ContainerVTs); 4900 SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID}; 4901 Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT)); 4902 Ops.push_back(Op.getOperand(2)); 4903 Ops.push_back(VL); 4904 SDValue Result = 4905 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4906 Load->getMemoryVT(), Load->getMemOperand()); 4907 SmallVector<SDValue, 9> Results; 4908 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 4909 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 4910 DAG, Subtarget)); 4911 Results.push_back(Result.getValue(NF)); 4912 return DAG.getMergeValues(Results, DL); 4913 } 4914 } 4915 4916 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4917 } 4918 4919 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4920 SelectionDAG &DAG) const { 4921 unsigned IntNo = Op.getConstantOperandVal(1); 4922 switch (IntNo) { 4923 default: 4924 break; 4925 case Intrinsic::riscv_masked_strided_store: { 4926 SDLoc DL(Op); 4927 MVT XLenVT = Subtarget.getXLenVT(); 4928 4929 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4930 // the selection of the masked intrinsics doesn't do this for us. 4931 SDValue Mask = Op.getOperand(5); 4932 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4933 4934 SDValue Val = Op.getOperand(2); 4935 MVT VT = Val.getSimpleValueType(); 4936 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4937 4938 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4939 if (!IsUnmasked) { 4940 MVT MaskVT = getMaskTypeFor(ContainerVT); 4941 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4942 } 4943 4944 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4945 4946 SDValue IntID = DAG.getTargetConstant( 4947 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4948 XLenVT); 4949 4950 auto *Store = cast<MemIntrinsicSDNode>(Op); 4951 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4952 Ops.push_back(Val); 4953 Ops.push_back(Op.getOperand(3)); // Ptr 4954 Ops.push_back(Op.getOperand(4)); // Stride 4955 if (!IsUnmasked) 4956 Ops.push_back(Mask); 4957 Ops.push_back(VL); 4958 4959 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4960 Ops, Store->getMemoryVT(), 4961 Store->getMemOperand()); 4962 } 4963 } 4964 4965 return SDValue(); 4966 } 4967 4968 static MVT getLMUL1VT(MVT VT) { 4969 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4970 "Unexpected vector MVT"); 4971 return MVT::getScalableVectorVT( 4972 VT.getVectorElementType(), 4973 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4974 } 4975 4976 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4977 switch (ISDOpcode) { 4978 default: 4979 llvm_unreachable("Unhandled reduction"); 4980 case ISD::VECREDUCE_ADD: 4981 return RISCVISD::VECREDUCE_ADD_VL; 4982 case ISD::VECREDUCE_UMAX: 4983 return RISCVISD::VECREDUCE_UMAX_VL; 4984 case ISD::VECREDUCE_SMAX: 4985 return RISCVISD::VECREDUCE_SMAX_VL; 4986 case ISD::VECREDUCE_UMIN: 4987 return RISCVISD::VECREDUCE_UMIN_VL; 4988 case ISD::VECREDUCE_SMIN: 4989 return RISCVISD::VECREDUCE_SMIN_VL; 4990 case ISD::VECREDUCE_AND: 4991 return RISCVISD::VECREDUCE_AND_VL; 4992 case ISD::VECREDUCE_OR: 4993 return RISCVISD::VECREDUCE_OR_VL; 4994 case ISD::VECREDUCE_XOR: 4995 return RISCVISD::VECREDUCE_XOR_VL; 4996 } 4997 } 4998 4999 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 5000 SelectionDAG &DAG, 5001 bool IsVP) const { 5002 SDLoc DL(Op); 5003 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 5004 MVT VecVT = Vec.getSimpleValueType(); 5005 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 5006 Op.getOpcode() == ISD::VECREDUCE_OR || 5007 Op.getOpcode() == ISD::VECREDUCE_XOR || 5008 Op.getOpcode() == ISD::VP_REDUCE_AND || 5009 Op.getOpcode() == ISD::VP_REDUCE_OR || 5010 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5011 "Unexpected reduction lowering"); 5012 5013 MVT XLenVT = Subtarget.getXLenVT(); 5014 assert(Op.getValueType() == XLenVT && 5015 "Expected reduction output to be legalized to XLenVT"); 5016 5017 MVT ContainerVT = VecVT; 5018 if (VecVT.isFixedLengthVector()) { 5019 ContainerVT = getContainerForFixedLengthVector(VecVT); 5020 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5021 } 5022 5023 SDValue Mask, VL; 5024 if (IsVP) { 5025 Mask = Op.getOperand(2); 5026 VL = Op.getOperand(3); 5027 } else { 5028 std::tie(Mask, VL) = 5029 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5030 } 5031 5032 unsigned BaseOpc; 5033 ISD::CondCode CC; 5034 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5035 5036 switch (Op.getOpcode()) { 5037 default: 5038 llvm_unreachable("Unhandled reduction"); 5039 case ISD::VECREDUCE_AND: 5040 case ISD::VP_REDUCE_AND: { 5041 // vcpop ~x == 0 5042 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5043 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5044 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5045 CC = ISD::SETEQ; 5046 BaseOpc = ISD::AND; 5047 break; 5048 } 5049 case ISD::VECREDUCE_OR: 5050 case ISD::VP_REDUCE_OR: 5051 // vcpop x != 0 5052 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5053 CC = ISD::SETNE; 5054 BaseOpc = ISD::OR; 5055 break; 5056 case ISD::VECREDUCE_XOR: 5057 case ISD::VP_REDUCE_XOR: { 5058 // ((vcpop x) & 1) != 0 5059 SDValue One = DAG.getConstant(1, DL, XLenVT); 5060 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5061 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5062 CC = ISD::SETNE; 5063 BaseOpc = ISD::XOR; 5064 break; 5065 } 5066 } 5067 5068 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5069 5070 if (!IsVP) 5071 return SetCC; 5072 5073 // Now include the start value in the operation. 5074 // Note that we must return the start value when no elements are operated 5075 // upon. The vcpop instructions we've emitted in each case above will return 5076 // 0 for an inactive vector, and so we've already received the neutral value: 5077 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5078 // can simply include the start value. 5079 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5080 } 5081 5082 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5083 SelectionDAG &DAG) const { 5084 SDLoc DL(Op); 5085 SDValue Vec = Op.getOperand(0); 5086 EVT VecEVT = Vec.getValueType(); 5087 5088 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5089 5090 // Due to ordering in legalize types we may have a vector type that needs to 5091 // be split. Do that manually so we can get down to a legal type. 5092 while (getTypeAction(*DAG.getContext(), VecEVT) == 5093 TargetLowering::TypeSplitVector) { 5094 SDValue Lo, Hi; 5095 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5096 VecEVT = Lo.getValueType(); 5097 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5098 } 5099 5100 // TODO: The type may need to be widened rather than split. Or widened before 5101 // it can be split. 5102 if (!isTypeLegal(VecEVT)) 5103 return SDValue(); 5104 5105 MVT VecVT = VecEVT.getSimpleVT(); 5106 MVT VecEltVT = VecVT.getVectorElementType(); 5107 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5108 5109 MVT ContainerVT = VecVT; 5110 if (VecVT.isFixedLengthVector()) { 5111 ContainerVT = getContainerForFixedLengthVector(VecVT); 5112 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5113 } 5114 5115 MVT M1VT = getLMUL1VT(ContainerVT); 5116 MVT XLenVT = Subtarget.getXLenVT(); 5117 5118 SDValue Mask, VL; 5119 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5120 5121 SDValue NeutralElem = 5122 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5123 SDValue IdentitySplat = 5124 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5125 M1VT, DL, DAG, Subtarget); 5126 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5127 IdentitySplat, Mask, VL); 5128 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5129 DAG.getConstant(0, DL, XLenVT)); 5130 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5131 } 5132 5133 // Given a reduction op, this function returns the matching reduction opcode, 5134 // the vector SDValue and the scalar SDValue required to lower this to a 5135 // RISCVISD node. 5136 static std::tuple<unsigned, SDValue, SDValue> 5137 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5138 SDLoc DL(Op); 5139 auto Flags = Op->getFlags(); 5140 unsigned Opcode = Op.getOpcode(); 5141 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5142 switch (Opcode) { 5143 default: 5144 llvm_unreachable("Unhandled reduction"); 5145 case ISD::VECREDUCE_FADD: { 5146 // Use positive zero if we can. It is cheaper to materialize. 5147 SDValue Zero = 5148 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5149 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5150 } 5151 case ISD::VECREDUCE_SEQ_FADD: 5152 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5153 Op.getOperand(0)); 5154 case ISD::VECREDUCE_FMIN: 5155 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5156 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5157 case ISD::VECREDUCE_FMAX: 5158 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5159 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5160 } 5161 } 5162 5163 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5164 SelectionDAG &DAG) const { 5165 SDLoc DL(Op); 5166 MVT VecEltVT = Op.getSimpleValueType(); 5167 5168 unsigned RVVOpcode; 5169 SDValue VectorVal, ScalarVal; 5170 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5171 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5172 MVT VecVT = VectorVal.getSimpleValueType(); 5173 5174 MVT ContainerVT = VecVT; 5175 if (VecVT.isFixedLengthVector()) { 5176 ContainerVT = getContainerForFixedLengthVector(VecVT); 5177 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5178 } 5179 5180 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5181 MVT XLenVT = Subtarget.getXLenVT(); 5182 5183 SDValue Mask, VL; 5184 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5185 5186 SDValue ScalarSplat = 5187 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5188 M1VT, DL, DAG, Subtarget); 5189 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5190 VectorVal, ScalarSplat, Mask, VL); 5191 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5192 DAG.getConstant(0, DL, XLenVT)); 5193 } 5194 5195 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5196 switch (ISDOpcode) { 5197 default: 5198 llvm_unreachable("Unhandled reduction"); 5199 case ISD::VP_REDUCE_ADD: 5200 return RISCVISD::VECREDUCE_ADD_VL; 5201 case ISD::VP_REDUCE_UMAX: 5202 return RISCVISD::VECREDUCE_UMAX_VL; 5203 case ISD::VP_REDUCE_SMAX: 5204 return RISCVISD::VECREDUCE_SMAX_VL; 5205 case ISD::VP_REDUCE_UMIN: 5206 return RISCVISD::VECREDUCE_UMIN_VL; 5207 case ISD::VP_REDUCE_SMIN: 5208 return RISCVISD::VECREDUCE_SMIN_VL; 5209 case ISD::VP_REDUCE_AND: 5210 return RISCVISD::VECREDUCE_AND_VL; 5211 case ISD::VP_REDUCE_OR: 5212 return RISCVISD::VECREDUCE_OR_VL; 5213 case ISD::VP_REDUCE_XOR: 5214 return RISCVISD::VECREDUCE_XOR_VL; 5215 case ISD::VP_REDUCE_FADD: 5216 return RISCVISD::VECREDUCE_FADD_VL; 5217 case ISD::VP_REDUCE_SEQ_FADD: 5218 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5219 case ISD::VP_REDUCE_FMAX: 5220 return RISCVISD::VECREDUCE_FMAX_VL; 5221 case ISD::VP_REDUCE_FMIN: 5222 return RISCVISD::VECREDUCE_FMIN_VL; 5223 } 5224 } 5225 5226 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5227 SelectionDAG &DAG) const { 5228 SDLoc DL(Op); 5229 SDValue Vec = Op.getOperand(1); 5230 EVT VecEVT = Vec.getValueType(); 5231 5232 // TODO: The type may need to be widened rather than split. Or widened before 5233 // it can be split. 5234 if (!isTypeLegal(VecEVT)) 5235 return SDValue(); 5236 5237 MVT VecVT = VecEVT.getSimpleVT(); 5238 MVT VecEltVT = VecVT.getVectorElementType(); 5239 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5240 5241 MVT ContainerVT = VecVT; 5242 if (VecVT.isFixedLengthVector()) { 5243 ContainerVT = getContainerForFixedLengthVector(VecVT); 5244 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5245 } 5246 5247 SDValue VL = Op.getOperand(3); 5248 SDValue Mask = Op.getOperand(2); 5249 5250 MVT M1VT = getLMUL1VT(ContainerVT); 5251 MVT XLenVT = Subtarget.getXLenVT(); 5252 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5253 5254 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5255 DAG.getConstant(1, DL, XLenVT), M1VT, 5256 DL, DAG, Subtarget); 5257 SDValue Reduction = 5258 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5259 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5260 DAG.getConstant(0, DL, XLenVT)); 5261 if (!VecVT.isInteger()) 5262 return Elt0; 5263 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5264 } 5265 5266 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5267 SelectionDAG &DAG) const { 5268 SDValue Vec = Op.getOperand(0); 5269 SDValue SubVec = Op.getOperand(1); 5270 MVT VecVT = Vec.getSimpleValueType(); 5271 MVT SubVecVT = SubVec.getSimpleValueType(); 5272 5273 SDLoc DL(Op); 5274 MVT XLenVT = Subtarget.getXLenVT(); 5275 unsigned OrigIdx = Op.getConstantOperandVal(2); 5276 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5277 5278 // We don't have the ability to slide mask vectors up indexed by their i1 5279 // elements; the smallest we can do is i8. Often we are able to bitcast to 5280 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5281 // into a scalable one, we might not necessarily have enough scalable 5282 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5283 if (SubVecVT.getVectorElementType() == MVT::i1 && 5284 (OrigIdx != 0 || !Vec.isUndef())) { 5285 if (VecVT.getVectorMinNumElements() >= 8 && 5286 SubVecVT.getVectorMinNumElements() >= 8) { 5287 assert(OrigIdx % 8 == 0 && "Invalid index"); 5288 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5289 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5290 "Unexpected mask vector lowering"); 5291 OrigIdx /= 8; 5292 SubVecVT = 5293 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5294 SubVecVT.isScalableVector()); 5295 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5296 VecVT.isScalableVector()); 5297 Vec = DAG.getBitcast(VecVT, Vec); 5298 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5299 } else { 5300 // We can't slide this mask vector up indexed by its i1 elements. 5301 // This poses a problem when we wish to insert a scalable vector which 5302 // can't be re-expressed as a larger type. Just choose the slow path and 5303 // extend to a larger type, then truncate back down. 5304 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5305 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5306 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5307 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5308 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5309 Op.getOperand(2)); 5310 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5311 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5312 } 5313 } 5314 5315 // If the subvector vector is a fixed-length type, we cannot use subregister 5316 // manipulation to simplify the codegen; we don't know which register of a 5317 // LMUL group contains the specific subvector as we only know the minimum 5318 // register size. Therefore we must slide the vector group up the full 5319 // amount. 5320 if (SubVecVT.isFixedLengthVector()) { 5321 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5322 return Op; 5323 MVT ContainerVT = VecVT; 5324 if (VecVT.isFixedLengthVector()) { 5325 ContainerVT = getContainerForFixedLengthVector(VecVT); 5326 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5327 } 5328 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5329 DAG.getUNDEF(ContainerVT), SubVec, 5330 DAG.getConstant(0, DL, XLenVT)); 5331 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5332 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5333 return DAG.getBitcast(Op.getValueType(), SubVec); 5334 } 5335 SDValue Mask = 5336 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5337 // Set the vector length to only the number of elements we care about. Note 5338 // that for slideup this includes the offset. 5339 SDValue VL = 5340 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5341 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5342 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5343 SubVec, SlideupAmt, Mask, VL); 5344 if (VecVT.isFixedLengthVector()) 5345 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5346 return DAG.getBitcast(Op.getValueType(), Slideup); 5347 } 5348 5349 unsigned SubRegIdx, RemIdx; 5350 std::tie(SubRegIdx, RemIdx) = 5351 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5352 VecVT, SubVecVT, OrigIdx, TRI); 5353 5354 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5355 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5356 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5357 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5358 5359 // 1. If the Idx has been completely eliminated and this subvector's size is 5360 // a vector register or a multiple thereof, or the surrounding elements are 5361 // undef, then this is a subvector insert which naturally aligns to a vector 5362 // register. These can easily be handled using subregister manipulation. 5363 // 2. If the subvector is smaller than a vector register, then the insertion 5364 // must preserve the undisturbed elements of the register. We do this by 5365 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5366 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5367 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5368 // LMUL=1 type back into the larger vector (resolving to another subregister 5369 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5370 // to avoid allocating a large register group to hold our subvector. 5371 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5372 return Op; 5373 5374 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5375 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5376 // (in our case undisturbed). This means we can set up a subvector insertion 5377 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5378 // size of the subvector. 5379 MVT InterSubVT = VecVT; 5380 SDValue AlignedExtract = Vec; 5381 unsigned AlignedIdx = OrigIdx - RemIdx; 5382 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5383 InterSubVT = getLMUL1VT(VecVT); 5384 // Extract a subvector equal to the nearest full vector register type. This 5385 // should resolve to a EXTRACT_SUBREG instruction. 5386 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5387 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5388 } 5389 5390 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5391 // For scalable vectors this must be further multiplied by vscale. 5392 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5393 5394 SDValue Mask, VL; 5395 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5396 5397 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5398 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5399 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5400 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5401 5402 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5403 DAG.getUNDEF(InterSubVT), SubVec, 5404 DAG.getConstant(0, DL, XLenVT)); 5405 5406 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5407 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5408 5409 // If required, insert this subvector back into the correct vector register. 5410 // This should resolve to an INSERT_SUBREG instruction. 5411 if (VecVT.bitsGT(InterSubVT)) 5412 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5413 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5414 5415 // We might have bitcast from a mask type: cast back to the original type if 5416 // required. 5417 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5418 } 5419 5420 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5421 SelectionDAG &DAG) const { 5422 SDValue Vec = Op.getOperand(0); 5423 MVT SubVecVT = Op.getSimpleValueType(); 5424 MVT VecVT = Vec.getSimpleValueType(); 5425 5426 SDLoc DL(Op); 5427 MVT XLenVT = Subtarget.getXLenVT(); 5428 unsigned OrigIdx = Op.getConstantOperandVal(1); 5429 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5430 5431 // We don't have the ability to slide mask vectors down indexed by their i1 5432 // elements; the smallest we can do is i8. Often we are able to bitcast to 5433 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5434 // from a scalable one, we might not necessarily have enough scalable 5435 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5436 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5437 if (VecVT.getVectorMinNumElements() >= 8 && 5438 SubVecVT.getVectorMinNumElements() >= 8) { 5439 assert(OrigIdx % 8 == 0 && "Invalid index"); 5440 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5441 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5442 "Unexpected mask vector lowering"); 5443 OrigIdx /= 8; 5444 SubVecVT = 5445 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5446 SubVecVT.isScalableVector()); 5447 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5448 VecVT.isScalableVector()); 5449 Vec = DAG.getBitcast(VecVT, Vec); 5450 } else { 5451 // We can't slide this mask vector down, indexed by its i1 elements. 5452 // This poses a problem when we wish to extract a scalable vector which 5453 // can't be re-expressed as a larger type. Just choose the slow path and 5454 // extend to a larger type, then truncate back down. 5455 // TODO: We could probably improve this when extracting certain fixed 5456 // from fixed, where we can extract as i8 and shift the correct element 5457 // right to reach the desired subvector? 5458 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5459 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5460 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5461 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5462 Op.getOperand(1)); 5463 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5464 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5465 } 5466 } 5467 5468 // If the subvector vector is a fixed-length type, we cannot use subregister 5469 // manipulation to simplify the codegen; we don't know which register of a 5470 // LMUL group contains the specific subvector as we only know the minimum 5471 // register size. Therefore we must slide the vector group down the full 5472 // amount. 5473 if (SubVecVT.isFixedLengthVector()) { 5474 // With an index of 0 this is a cast-like subvector, which can be performed 5475 // with subregister operations. 5476 if (OrigIdx == 0) 5477 return Op; 5478 MVT ContainerVT = VecVT; 5479 if (VecVT.isFixedLengthVector()) { 5480 ContainerVT = getContainerForFixedLengthVector(VecVT); 5481 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5482 } 5483 SDValue Mask = 5484 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5485 // Set the vector length to only the number of elements we care about. This 5486 // avoids sliding down elements we're going to discard straight away. 5487 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5488 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5489 SDValue Slidedown = 5490 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5491 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5492 // Now we can use a cast-like subvector extract to get the result. 5493 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5494 DAG.getConstant(0, DL, XLenVT)); 5495 return DAG.getBitcast(Op.getValueType(), Slidedown); 5496 } 5497 5498 unsigned SubRegIdx, RemIdx; 5499 std::tie(SubRegIdx, RemIdx) = 5500 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5501 VecVT, SubVecVT, OrigIdx, TRI); 5502 5503 // If the Idx has been completely eliminated then this is a subvector extract 5504 // which naturally aligns to a vector register. These can easily be handled 5505 // using subregister manipulation. 5506 if (RemIdx == 0) 5507 return Op; 5508 5509 // Else we must shift our vector register directly to extract the subvector. 5510 // Do this using VSLIDEDOWN. 5511 5512 // If the vector type is an LMUL-group type, extract a subvector equal to the 5513 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5514 // instruction. 5515 MVT InterSubVT = VecVT; 5516 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5517 InterSubVT = getLMUL1VT(VecVT); 5518 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5519 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5520 } 5521 5522 // Slide this vector register down by the desired number of elements in order 5523 // to place the desired subvector starting at element 0. 5524 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5525 // For scalable vectors this must be further multiplied by vscale. 5526 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5527 5528 SDValue Mask, VL; 5529 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5530 SDValue Slidedown = 5531 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5532 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5533 5534 // Now the vector is in the right position, extract our final subvector. This 5535 // should resolve to a COPY. 5536 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5537 DAG.getConstant(0, DL, XLenVT)); 5538 5539 // We might have bitcast from a mask type: cast back to the original type if 5540 // required. 5541 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5542 } 5543 5544 // Lower step_vector to the vid instruction. Any non-identity step value must 5545 // be accounted for my manual expansion. 5546 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5547 SelectionDAG &DAG) const { 5548 SDLoc DL(Op); 5549 MVT VT = Op.getSimpleValueType(); 5550 MVT XLenVT = Subtarget.getXLenVT(); 5551 SDValue Mask, VL; 5552 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5553 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5554 uint64_t StepValImm = Op.getConstantOperandVal(0); 5555 if (StepValImm != 1) { 5556 if (isPowerOf2_64(StepValImm)) { 5557 SDValue StepVal = 5558 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5559 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5560 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5561 } else { 5562 SDValue StepVal = lowerScalarSplat( 5563 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5564 VL, VT, DL, DAG, Subtarget); 5565 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5566 } 5567 } 5568 return StepVec; 5569 } 5570 5571 // Implement vector_reverse using vrgather.vv with indices determined by 5572 // subtracting the id of each element from (VLMAX-1). This will convert 5573 // the indices like so: 5574 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5575 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5576 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5577 SelectionDAG &DAG) const { 5578 SDLoc DL(Op); 5579 MVT VecVT = Op.getSimpleValueType(); 5580 unsigned EltSize = VecVT.getScalarSizeInBits(); 5581 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5582 5583 unsigned MaxVLMAX = 0; 5584 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5585 if (VectorBitsMax != 0) 5586 MaxVLMAX = 5587 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 5588 5589 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5590 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5591 5592 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5593 // to use vrgatherei16.vv. 5594 // TODO: It's also possible to use vrgatherei16.vv for other types to 5595 // decrease register width for the index calculation. 5596 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5597 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5598 // Reverse each half, then reassemble them in reverse order. 5599 // NOTE: It's also possible that after splitting that VLMAX no longer 5600 // requires vrgatherei16.vv. 5601 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5602 SDValue Lo, Hi; 5603 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5604 EVT LoVT, HiVT; 5605 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5606 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5607 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5608 // Reassemble the low and high pieces reversed. 5609 // FIXME: This is a CONCAT_VECTORS. 5610 SDValue Res = 5611 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5612 DAG.getIntPtrConstant(0, DL)); 5613 return DAG.getNode( 5614 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5615 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5616 } 5617 5618 // Just promote the int type to i16 which will double the LMUL. 5619 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5620 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5621 } 5622 5623 MVT XLenVT = Subtarget.getXLenVT(); 5624 SDValue Mask, VL; 5625 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5626 5627 // Calculate VLMAX-1 for the desired SEW. 5628 unsigned MinElts = VecVT.getVectorMinNumElements(); 5629 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5630 DAG.getConstant(MinElts, DL, XLenVT)); 5631 SDValue VLMinus1 = 5632 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5633 5634 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5635 bool IsRV32E64 = 5636 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5637 SDValue SplatVL; 5638 if (!IsRV32E64) 5639 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5640 else 5641 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5642 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5643 5644 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5645 SDValue Indices = 5646 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5647 5648 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5649 } 5650 5651 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5652 SelectionDAG &DAG) const { 5653 SDLoc DL(Op); 5654 SDValue V1 = Op.getOperand(0); 5655 SDValue V2 = Op.getOperand(1); 5656 MVT XLenVT = Subtarget.getXLenVT(); 5657 MVT VecVT = Op.getSimpleValueType(); 5658 5659 unsigned MinElts = VecVT.getVectorMinNumElements(); 5660 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5661 DAG.getConstant(MinElts, DL, XLenVT)); 5662 5663 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5664 SDValue DownOffset, UpOffset; 5665 if (ImmValue >= 0) { 5666 // The operand is a TargetConstant, we need to rebuild it as a regular 5667 // constant. 5668 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5669 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5670 } else { 5671 // The operand is a TargetConstant, we need to rebuild it as a regular 5672 // constant rather than negating the original operand. 5673 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5674 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5675 } 5676 5677 SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG); 5678 5679 SDValue SlideDown = 5680 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5681 DownOffset, TrueMask, UpOffset); 5682 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5683 TrueMask, 5684 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 5685 } 5686 5687 SDValue 5688 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5689 SelectionDAG &DAG) const { 5690 SDLoc DL(Op); 5691 auto *Load = cast<LoadSDNode>(Op); 5692 5693 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5694 Load->getMemoryVT(), 5695 *Load->getMemOperand()) && 5696 "Expecting a correctly-aligned load"); 5697 5698 MVT VT = Op.getSimpleValueType(); 5699 MVT XLenVT = Subtarget.getXLenVT(); 5700 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5701 5702 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5703 5704 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5705 SDValue IntID = DAG.getTargetConstant( 5706 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 5707 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 5708 if (!IsMaskOp) 5709 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5710 Ops.push_back(Load->getBasePtr()); 5711 Ops.push_back(VL); 5712 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5713 SDValue NewLoad = 5714 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5715 Load->getMemoryVT(), Load->getMemOperand()); 5716 5717 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5718 return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL); 5719 } 5720 5721 SDValue 5722 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5723 SelectionDAG &DAG) const { 5724 SDLoc DL(Op); 5725 auto *Store = cast<StoreSDNode>(Op); 5726 5727 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5728 Store->getMemoryVT(), 5729 *Store->getMemOperand()) && 5730 "Expecting a correctly-aligned store"); 5731 5732 SDValue StoreVal = Store->getValue(); 5733 MVT VT = StoreVal.getSimpleValueType(); 5734 MVT XLenVT = Subtarget.getXLenVT(); 5735 5736 // If the size less than a byte, we need to pad with zeros to make a byte. 5737 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5738 VT = MVT::v8i1; 5739 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5740 DAG.getConstant(0, DL, VT), StoreVal, 5741 DAG.getIntPtrConstant(0, DL)); 5742 } 5743 5744 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5745 5746 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5747 5748 SDValue NewValue = 5749 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5750 5751 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5752 SDValue IntID = DAG.getTargetConstant( 5753 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 5754 return DAG.getMemIntrinsicNode( 5755 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 5756 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 5757 Store->getMemoryVT(), Store->getMemOperand()); 5758 } 5759 5760 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5761 SelectionDAG &DAG) const { 5762 SDLoc DL(Op); 5763 MVT VT = Op.getSimpleValueType(); 5764 5765 const auto *MemSD = cast<MemSDNode>(Op); 5766 EVT MemVT = MemSD->getMemoryVT(); 5767 MachineMemOperand *MMO = MemSD->getMemOperand(); 5768 SDValue Chain = MemSD->getChain(); 5769 SDValue BasePtr = MemSD->getBasePtr(); 5770 5771 SDValue Mask, PassThru, VL; 5772 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5773 Mask = VPLoad->getMask(); 5774 PassThru = DAG.getUNDEF(VT); 5775 VL = VPLoad->getVectorLength(); 5776 } else { 5777 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5778 Mask = MLoad->getMask(); 5779 PassThru = MLoad->getPassThru(); 5780 } 5781 5782 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5783 5784 MVT XLenVT = Subtarget.getXLenVT(); 5785 5786 MVT ContainerVT = VT; 5787 if (VT.isFixedLengthVector()) { 5788 ContainerVT = getContainerForFixedLengthVector(VT); 5789 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5790 if (!IsUnmasked) { 5791 MVT MaskVT = getMaskTypeFor(ContainerVT); 5792 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5793 } 5794 } 5795 5796 if (!VL) 5797 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5798 5799 unsigned IntID = 5800 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5801 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5802 if (IsUnmasked) 5803 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5804 else 5805 Ops.push_back(PassThru); 5806 Ops.push_back(BasePtr); 5807 if (!IsUnmasked) 5808 Ops.push_back(Mask); 5809 Ops.push_back(VL); 5810 if (!IsUnmasked) 5811 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5812 5813 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5814 5815 SDValue Result = 5816 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5817 Chain = Result.getValue(1); 5818 5819 if (VT.isFixedLengthVector()) 5820 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5821 5822 return DAG.getMergeValues({Result, Chain}, DL); 5823 } 5824 5825 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5826 SelectionDAG &DAG) const { 5827 SDLoc DL(Op); 5828 5829 const auto *MemSD = cast<MemSDNode>(Op); 5830 EVT MemVT = MemSD->getMemoryVT(); 5831 MachineMemOperand *MMO = MemSD->getMemOperand(); 5832 SDValue Chain = MemSD->getChain(); 5833 SDValue BasePtr = MemSD->getBasePtr(); 5834 SDValue Val, Mask, VL; 5835 5836 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5837 Val = VPStore->getValue(); 5838 Mask = VPStore->getMask(); 5839 VL = VPStore->getVectorLength(); 5840 } else { 5841 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5842 Val = MStore->getValue(); 5843 Mask = MStore->getMask(); 5844 } 5845 5846 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5847 5848 MVT VT = Val.getSimpleValueType(); 5849 MVT XLenVT = Subtarget.getXLenVT(); 5850 5851 MVT ContainerVT = VT; 5852 if (VT.isFixedLengthVector()) { 5853 ContainerVT = getContainerForFixedLengthVector(VT); 5854 5855 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5856 if (!IsUnmasked) { 5857 MVT MaskVT = getMaskTypeFor(ContainerVT); 5858 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5859 } 5860 } 5861 5862 if (!VL) 5863 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5864 5865 unsigned IntID = 5866 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5867 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5868 Ops.push_back(Val); 5869 Ops.push_back(BasePtr); 5870 if (!IsUnmasked) 5871 Ops.push_back(Mask); 5872 Ops.push_back(VL); 5873 5874 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5875 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5876 } 5877 5878 SDValue 5879 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5880 SelectionDAG &DAG) const { 5881 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5882 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5883 5884 MVT VT = Op.getSimpleValueType(); 5885 5886 SDValue Op1 = 5887 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5888 SDValue Op2 = 5889 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5890 5891 SDLoc DL(Op); 5892 SDValue VL = 5893 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5894 5895 MVT MaskVT = getMaskTypeFor(ContainerVT); 5896 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 5897 5898 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5899 Op.getOperand(2), Mask, VL); 5900 5901 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5902 } 5903 5904 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5905 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5906 MVT VT = Op.getSimpleValueType(); 5907 5908 if (VT.getVectorElementType() == MVT::i1) 5909 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5910 5911 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5912 } 5913 5914 SDValue 5915 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5916 SelectionDAG &DAG) const { 5917 unsigned Opc; 5918 switch (Op.getOpcode()) { 5919 default: llvm_unreachable("Unexpected opcode!"); 5920 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5921 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5922 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5923 } 5924 5925 return lowerToScalableOp(Op, DAG, Opc); 5926 } 5927 5928 // Lower vector ABS to smax(X, sub(0, X)). 5929 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5930 SDLoc DL(Op); 5931 MVT VT = Op.getSimpleValueType(); 5932 SDValue X = Op.getOperand(0); 5933 5934 assert(VT.isFixedLengthVector() && "Unexpected type"); 5935 5936 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5937 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5938 5939 SDValue Mask, VL; 5940 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5941 5942 SDValue SplatZero = DAG.getNode( 5943 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 5944 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5945 SDValue NegX = 5946 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5947 SDValue Max = 5948 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5949 5950 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5951 } 5952 5953 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5954 SDValue Op, SelectionDAG &DAG) const { 5955 SDLoc DL(Op); 5956 MVT VT = Op.getSimpleValueType(); 5957 SDValue Mag = Op.getOperand(0); 5958 SDValue Sign = Op.getOperand(1); 5959 assert(Mag.getValueType() == Sign.getValueType() && 5960 "Can only handle COPYSIGN with matching types."); 5961 5962 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5963 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5964 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5965 5966 SDValue Mask, VL; 5967 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5968 5969 SDValue CopySign = 5970 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5971 5972 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5973 } 5974 5975 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5976 SDValue Op, SelectionDAG &DAG) const { 5977 MVT VT = Op.getSimpleValueType(); 5978 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5979 5980 MVT I1ContainerVT = 5981 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5982 5983 SDValue CC = 5984 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5985 SDValue Op1 = 5986 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5987 SDValue Op2 = 5988 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5989 5990 SDLoc DL(Op); 5991 SDValue Mask, VL; 5992 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5993 5994 SDValue Select = 5995 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5996 5997 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5998 } 5999 6000 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 6001 unsigned NewOpc, 6002 bool HasMask) const { 6003 MVT VT = Op.getSimpleValueType(); 6004 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6005 6006 // Create list of operands by converting existing ones to scalable types. 6007 SmallVector<SDValue, 6> Ops; 6008 for (const SDValue &V : Op->op_values()) { 6009 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6010 6011 // Pass through non-vector operands. 6012 if (!V.getValueType().isVector()) { 6013 Ops.push_back(V); 6014 continue; 6015 } 6016 6017 // "cast" fixed length vector to a scalable vector. 6018 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6019 "Only fixed length vectors are supported!"); 6020 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6021 } 6022 6023 SDLoc DL(Op); 6024 SDValue Mask, VL; 6025 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6026 if (HasMask) 6027 Ops.push_back(Mask); 6028 Ops.push_back(VL); 6029 6030 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6031 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6032 } 6033 6034 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6035 // * Operands of each node are assumed to be in the same order. 6036 // * The EVL operand is promoted from i32 to i64 on RV64. 6037 // * Fixed-length vectors are converted to their scalable-vector container 6038 // types. 6039 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6040 unsigned RISCVISDOpc) const { 6041 SDLoc DL(Op); 6042 MVT VT = Op.getSimpleValueType(); 6043 SmallVector<SDValue, 4> Ops; 6044 6045 for (const auto &OpIdx : enumerate(Op->ops())) { 6046 SDValue V = OpIdx.value(); 6047 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6048 // Pass through operands which aren't fixed-length vectors. 6049 if (!V.getValueType().isFixedLengthVector()) { 6050 Ops.push_back(V); 6051 continue; 6052 } 6053 // "cast" fixed length vector to a scalable vector. 6054 MVT OpVT = V.getSimpleValueType(); 6055 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6056 assert(useRVVForFixedLengthVectorVT(OpVT) && 6057 "Only fixed length vectors are supported!"); 6058 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6059 } 6060 6061 if (!VT.isFixedLengthVector()) 6062 return DAG.getNode(RISCVISDOpc, DL, VT, Ops, Op->getFlags()); 6063 6064 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6065 6066 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops, Op->getFlags()); 6067 6068 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6069 } 6070 6071 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op, 6072 SelectionDAG &DAG) const { 6073 SDLoc DL(Op); 6074 MVT VT = Op.getSimpleValueType(); 6075 6076 SDValue Src = Op.getOperand(0); 6077 // NOTE: Mask is dropped. 6078 SDValue VL = Op.getOperand(2); 6079 6080 MVT ContainerVT = VT; 6081 if (VT.isFixedLengthVector()) { 6082 ContainerVT = getContainerForFixedLengthVector(VT); 6083 MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6084 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6085 } 6086 6087 MVT XLenVT = Subtarget.getXLenVT(); 6088 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6089 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6090 DAG.getUNDEF(ContainerVT), Zero, VL); 6091 6092 SDValue SplatValue = DAG.getConstant( 6093 Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT); 6094 SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6095 DAG.getUNDEF(ContainerVT), SplatValue, VL); 6096 6097 SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src, 6098 Splat, ZeroSplat, VL); 6099 if (!VT.isFixedLengthVector()) 6100 return Result; 6101 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6102 } 6103 6104 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op, 6105 SelectionDAG &DAG) const { 6106 SDLoc DL(Op); 6107 MVT VT = Op.getSimpleValueType(); 6108 6109 SDValue Op1 = Op.getOperand(0); 6110 SDValue Op2 = Op.getOperand(1); 6111 ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 6112 // NOTE: Mask is dropped. 6113 SDValue VL = Op.getOperand(4); 6114 6115 MVT ContainerVT = VT; 6116 if (VT.isFixedLengthVector()) { 6117 ContainerVT = getContainerForFixedLengthVector(VT); 6118 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6119 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6120 } 6121 6122 SDValue Result; 6123 SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 6124 6125 switch (Condition) { 6126 default: 6127 break; 6128 // X != Y --> (X^Y) 6129 case ISD::SETNE: 6130 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6131 break; 6132 // X == Y --> ~(X^Y) 6133 case ISD::SETEQ: { 6134 SDValue Temp = 6135 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6136 Result = 6137 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL); 6138 break; 6139 } 6140 // X >s Y --> X == 0 & Y == 1 --> ~X & Y 6141 // X <u Y --> X == 0 & Y == 1 --> ~X & Y 6142 case ISD::SETGT: 6143 case ISD::SETULT: { 6144 SDValue Temp = 6145 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6146 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL); 6147 break; 6148 } 6149 // X <s Y --> X == 1 & Y == 0 --> ~Y & X 6150 // X >u Y --> X == 1 & Y == 0 --> ~Y & X 6151 case ISD::SETLT: 6152 case ISD::SETUGT: { 6153 SDValue Temp = 6154 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6155 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL); 6156 break; 6157 } 6158 // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 6159 // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 6160 case ISD::SETGE: 6161 case ISD::SETULE: { 6162 SDValue Temp = 6163 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6164 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL); 6165 break; 6166 } 6167 // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 6168 // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 6169 case ISD::SETLE: 6170 case ISD::SETUGE: { 6171 SDValue Temp = 6172 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6173 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL); 6174 break; 6175 } 6176 } 6177 6178 if (!VT.isFixedLengthVector()) 6179 return Result; 6180 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6181 } 6182 6183 // Lower Floating-Point/Integer Type-Convert VP SDNodes 6184 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG, 6185 unsigned RISCVISDOpc) const { 6186 SDLoc DL(Op); 6187 6188 SDValue Src = Op.getOperand(0); 6189 SDValue Mask = Op.getOperand(1); 6190 SDValue VL = Op.getOperand(2); 6191 6192 MVT DstVT = Op.getSimpleValueType(); 6193 MVT SrcVT = Src.getSimpleValueType(); 6194 if (DstVT.isFixedLengthVector()) { 6195 DstVT = getContainerForFixedLengthVector(DstVT); 6196 SrcVT = getContainerForFixedLengthVector(SrcVT); 6197 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6198 MVT MaskVT = getMaskTypeFor(DstVT); 6199 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6200 } 6201 6202 unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL || 6203 RISCVISDOpc == RISCVISD::FP_TO_SINT_VL) 6204 ? RISCVISD::VSEXT_VL 6205 : RISCVISD::VZEXT_VL; 6206 6207 unsigned DstEltSize = DstVT.getScalarSizeInBits(); 6208 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 6209 6210 SDValue Result; 6211 if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion. 6212 if (SrcVT.isInteger()) { 6213 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6214 6215 // Do we need to do any pre-widening before converting? 6216 if (SrcEltSize == 1) { 6217 MVT IntVT = DstVT.changeVectorElementTypeToInteger(); 6218 MVT XLenVT = Subtarget.getXLenVT(); 6219 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6220 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6221 DAG.getUNDEF(IntVT), Zero, VL); 6222 SDValue One = DAG.getConstant( 6223 RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT); 6224 SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6225 DAG.getUNDEF(IntVT), One, VL); 6226 Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat, 6227 ZeroSplat, VL); 6228 } else if (DstEltSize > (2 * SrcEltSize)) { 6229 // Widen before converting. 6230 MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2), 6231 DstVT.getVectorElementCount()); 6232 Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL); 6233 } 6234 6235 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6236 } else { 6237 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6238 "Wrong input/output vector types"); 6239 6240 // Convert f16 to f32 then convert f32 to i64. 6241 if (DstEltSize > (2 * SrcEltSize)) { 6242 assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6243 MVT InterimFVT = 6244 MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6245 Src = 6246 DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL); 6247 } 6248 6249 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6250 } 6251 } else { // Narrowing + Conversion 6252 if (SrcVT.isInteger()) { 6253 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6254 // First do a narrowing convert to an FP type half the size, then round 6255 // the FP type to a small FP type if needed. 6256 6257 MVT InterimFVT = DstVT; 6258 if (SrcEltSize > (2 * DstEltSize)) { 6259 assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!"); 6260 assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6261 InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6262 } 6263 6264 Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL); 6265 6266 if (InterimFVT != DstVT) { 6267 Src = Result; 6268 Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL); 6269 } 6270 } else { 6271 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6272 "Wrong input/output vector types"); 6273 // First do a narrowing conversion to an integer half the size, then 6274 // truncate if needed. 6275 6276 if (DstEltSize == 1) { 6277 // First convert to the same size integer, then convert to mask using 6278 // setcc. 6279 assert(SrcEltSize >= 16 && "Unexpected FP type!"); 6280 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize), 6281 DstVT.getVectorElementCount()); 6282 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6283 6284 // Compare the integer result to 0. The integer should be 0 or 1/-1, 6285 // otherwise the conversion was undefined. 6286 MVT XLenVT = Subtarget.getXLenVT(); 6287 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 6288 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT, 6289 DAG.getUNDEF(InterimIVT), SplatZero); 6290 Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero, 6291 DAG.getCondCode(ISD::SETNE), Mask, VL); 6292 } else { 6293 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6294 DstVT.getVectorElementCount()); 6295 6296 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6297 6298 while (InterimIVT != DstVT) { 6299 SrcEltSize /= 2; 6300 Src = Result; 6301 InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6302 DstVT.getVectorElementCount()); 6303 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT, 6304 Src, Mask, VL); 6305 } 6306 } 6307 } 6308 } 6309 6310 MVT VT = Op.getSimpleValueType(); 6311 if (!VT.isFixedLengthVector()) 6312 return Result; 6313 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6314 } 6315 6316 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6317 unsigned MaskOpc, 6318 unsigned VecOpc) const { 6319 MVT VT = Op.getSimpleValueType(); 6320 if (VT.getVectorElementType() != MVT::i1) 6321 return lowerVPOp(Op, DAG, VecOpc); 6322 6323 // It is safe to drop mask parameter as masked-off elements are undef. 6324 SDValue Op1 = Op->getOperand(0); 6325 SDValue Op2 = Op->getOperand(1); 6326 SDValue VL = Op->getOperand(3); 6327 6328 MVT ContainerVT = VT; 6329 const bool IsFixed = VT.isFixedLengthVector(); 6330 if (IsFixed) { 6331 ContainerVT = getContainerForFixedLengthVector(VT); 6332 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6333 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6334 } 6335 6336 SDLoc DL(Op); 6337 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6338 if (!IsFixed) 6339 return Val; 6340 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6341 } 6342 6343 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6344 // matched to a RVV indexed load. The RVV indexed load instructions only 6345 // support the "unsigned unscaled" addressing mode; indices are implicitly 6346 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6347 // signed or scaled indexing is extended to the XLEN value type and scaled 6348 // accordingly. 6349 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6350 SelectionDAG &DAG) const { 6351 SDLoc DL(Op); 6352 MVT VT = Op.getSimpleValueType(); 6353 6354 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6355 EVT MemVT = MemSD->getMemoryVT(); 6356 MachineMemOperand *MMO = MemSD->getMemOperand(); 6357 SDValue Chain = MemSD->getChain(); 6358 SDValue BasePtr = MemSD->getBasePtr(); 6359 6360 ISD::LoadExtType LoadExtType; 6361 SDValue Index, Mask, PassThru, VL; 6362 6363 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6364 Index = VPGN->getIndex(); 6365 Mask = VPGN->getMask(); 6366 PassThru = DAG.getUNDEF(VT); 6367 VL = VPGN->getVectorLength(); 6368 // VP doesn't support extending loads. 6369 LoadExtType = ISD::NON_EXTLOAD; 6370 } else { 6371 // Else it must be a MGATHER. 6372 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6373 Index = MGN->getIndex(); 6374 Mask = MGN->getMask(); 6375 PassThru = MGN->getPassThru(); 6376 LoadExtType = MGN->getExtensionType(); 6377 } 6378 6379 MVT IndexVT = Index.getSimpleValueType(); 6380 MVT XLenVT = Subtarget.getXLenVT(); 6381 6382 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6383 "Unexpected VTs!"); 6384 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6385 // Targets have to explicitly opt-in for extending vector loads. 6386 assert(LoadExtType == ISD::NON_EXTLOAD && 6387 "Unexpected extending MGATHER/VP_GATHER"); 6388 (void)LoadExtType; 6389 6390 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6391 // the selection of the masked intrinsics doesn't do this for us. 6392 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6393 6394 MVT ContainerVT = VT; 6395 if (VT.isFixedLengthVector()) { 6396 ContainerVT = getContainerForFixedLengthVector(VT); 6397 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6398 ContainerVT.getVectorElementCount()); 6399 6400 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6401 6402 if (!IsUnmasked) { 6403 MVT MaskVT = getMaskTypeFor(ContainerVT); 6404 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6405 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6406 } 6407 } 6408 6409 if (!VL) 6410 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6411 6412 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6413 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6414 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6415 VL); 6416 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6417 TrueMask, VL); 6418 } 6419 6420 unsigned IntID = 6421 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6422 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6423 if (IsUnmasked) 6424 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6425 else 6426 Ops.push_back(PassThru); 6427 Ops.push_back(BasePtr); 6428 Ops.push_back(Index); 6429 if (!IsUnmasked) 6430 Ops.push_back(Mask); 6431 Ops.push_back(VL); 6432 if (!IsUnmasked) 6433 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6434 6435 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6436 SDValue Result = 6437 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6438 Chain = Result.getValue(1); 6439 6440 if (VT.isFixedLengthVector()) 6441 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6442 6443 return DAG.getMergeValues({Result, Chain}, DL); 6444 } 6445 6446 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6447 // matched to a RVV indexed store. The RVV indexed store instructions only 6448 // support the "unsigned unscaled" addressing mode; indices are implicitly 6449 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6450 // signed or scaled indexing is extended to the XLEN value type and scaled 6451 // accordingly. 6452 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6453 SelectionDAG &DAG) const { 6454 SDLoc DL(Op); 6455 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6456 EVT MemVT = MemSD->getMemoryVT(); 6457 MachineMemOperand *MMO = MemSD->getMemOperand(); 6458 SDValue Chain = MemSD->getChain(); 6459 SDValue BasePtr = MemSD->getBasePtr(); 6460 6461 bool IsTruncatingStore = false; 6462 SDValue Index, Mask, Val, VL; 6463 6464 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6465 Index = VPSN->getIndex(); 6466 Mask = VPSN->getMask(); 6467 Val = VPSN->getValue(); 6468 VL = VPSN->getVectorLength(); 6469 // VP doesn't support truncating stores. 6470 IsTruncatingStore = false; 6471 } else { 6472 // Else it must be a MSCATTER. 6473 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6474 Index = MSN->getIndex(); 6475 Mask = MSN->getMask(); 6476 Val = MSN->getValue(); 6477 IsTruncatingStore = MSN->isTruncatingStore(); 6478 } 6479 6480 MVT VT = Val.getSimpleValueType(); 6481 MVT IndexVT = Index.getSimpleValueType(); 6482 MVT XLenVT = Subtarget.getXLenVT(); 6483 6484 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6485 "Unexpected VTs!"); 6486 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6487 // Targets have to explicitly opt-in for extending vector loads and 6488 // truncating vector stores. 6489 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6490 (void)IsTruncatingStore; 6491 6492 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6493 // the selection of the masked intrinsics doesn't do this for us. 6494 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6495 6496 MVT ContainerVT = VT; 6497 if (VT.isFixedLengthVector()) { 6498 ContainerVT = getContainerForFixedLengthVector(VT); 6499 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6500 ContainerVT.getVectorElementCount()); 6501 6502 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6503 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6504 6505 if (!IsUnmasked) { 6506 MVT MaskVT = getMaskTypeFor(ContainerVT); 6507 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6508 } 6509 } 6510 6511 if (!VL) 6512 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6513 6514 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6515 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6516 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6517 VL); 6518 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6519 TrueMask, VL); 6520 } 6521 6522 unsigned IntID = 6523 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6524 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6525 Ops.push_back(Val); 6526 Ops.push_back(BasePtr); 6527 Ops.push_back(Index); 6528 if (!IsUnmasked) 6529 Ops.push_back(Mask); 6530 Ops.push_back(VL); 6531 6532 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6533 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6534 } 6535 6536 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6537 SelectionDAG &DAG) const { 6538 const MVT XLenVT = Subtarget.getXLenVT(); 6539 SDLoc DL(Op); 6540 SDValue Chain = Op->getOperand(0); 6541 SDValue SysRegNo = DAG.getTargetConstant( 6542 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6543 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6544 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6545 6546 // Encoding used for rounding mode in RISCV differs from that used in 6547 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6548 // table, which consists of a sequence of 4-bit fields, each representing 6549 // corresponding FLT_ROUNDS mode. 6550 static const int Table = 6551 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6552 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6553 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6554 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6555 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6556 6557 SDValue Shift = 6558 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6559 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6560 DAG.getConstant(Table, DL, XLenVT), Shift); 6561 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6562 DAG.getConstant(7, DL, XLenVT)); 6563 6564 return DAG.getMergeValues({Masked, Chain}, DL); 6565 } 6566 6567 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6568 SelectionDAG &DAG) const { 6569 const MVT XLenVT = Subtarget.getXLenVT(); 6570 SDLoc DL(Op); 6571 SDValue Chain = Op->getOperand(0); 6572 SDValue RMValue = Op->getOperand(1); 6573 SDValue SysRegNo = DAG.getTargetConstant( 6574 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6575 6576 // Encoding used for rounding mode in RISCV differs from that used in 6577 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6578 // a table, which consists of a sequence of 4-bit fields, each representing 6579 // corresponding RISCV mode. 6580 static const unsigned Table = 6581 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6582 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6583 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6584 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6585 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6586 6587 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6588 DAG.getConstant(2, DL, XLenVT)); 6589 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6590 DAG.getConstant(Table, DL, XLenVT), Shift); 6591 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6592 DAG.getConstant(0x7, DL, XLenVT)); 6593 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6594 RMValue); 6595 } 6596 6597 SDValue RISCVTargetLowering::lowerEH_DWARF_CFA(SDValue Op, 6598 SelectionDAG &DAG) const { 6599 MachineFunction &MF = DAG.getMachineFunction(); 6600 6601 bool isRISCV64 = Subtarget.is64Bit(); 6602 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 6603 6604 int FI = MF.getFrameInfo().CreateFixedObject(isRISCV64 ? 8 : 4, 0, false); 6605 return DAG.getFrameIndex(FI, PtrVT); 6606 } 6607 6608 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6609 switch (IntNo) { 6610 default: 6611 llvm_unreachable("Unexpected Intrinsic"); 6612 case Intrinsic::riscv_bcompress: 6613 return RISCVISD::BCOMPRESSW; 6614 case Intrinsic::riscv_bdecompress: 6615 return RISCVISD::BDECOMPRESSW; 6616 case Intrinsic::riscv_bfp: 6617 return RISCVISD::BFPW; 6618 case Intrinsic::riscv_fsl: 6619 return RISCVISD::FSLW; 6620 case Intrinsic::riscv_fsr: 6621 return RISCVISD::FSRW; 6622 } 6623 } 6624 6625 // Converts the given intrinsic to a i64 operation with any extension. 6626 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6627 unsigned IntNo) { 6628 SDLoc DL(N); 6629 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6630 // Deal with the Instruction Operands 6631 SmallVector<SDValue, 3> NewOps; 6632 for (SDValue Op : drop_begin(N->ops())) 6633 // Promote the operand to i64 type 6634 NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op)); 6635 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps); 6636 // ReplaceNodeResults requires we maintain the same type for the return value. 6637 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6638 } 6639 6640 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6641 // form of the given Opcode. 6642 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6643 switch (Opcode) { 6644 default: 6645 llvm_unreachable("Unexpected opcode"); 6646 case ISD::SHL: 6647 return RISCVISD::SLLW; 6648 case ISD::SRA: 6649 return RISCVISD::SRAW; 6650 case ISD::SRL: 6651 return RISCVISD::SRLW; 6652 case ISD::SDIV: 6653 return RISCVISD::DIVW; 6654 case ISD::UDIV: 6655 return RISCVISD::DIVUW; 6656 case ISD::UREM: 6657 return RISCVISD::REMUW; 6658 case ISD::ROTL: 6659 return RISCVISD::ROLW; 6660 case ISD::ROTR: 6661 return RISCVISD::RORW; 6662 } 6663 } 6664 6665 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6666 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6667 // otherwise be promoted to i64, making it difficult to select the 6668 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6669 // type i8/i16/i32 is lost. 6670 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6671 unsigned ExtOpc = ISD::ANY_EXTEND) { 6672 SDLoc DL(N); 6673 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6674 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6675 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6676 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6677 // ReplaceNodeResults requires we maintain the same type for the return value. 6678 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6679 } 6680 6681 // Converts the given 32-bit operation to a i64 operation with signed extension 6682 // semantic to reduce the signed extension instructions. 6683 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6684 SDLoc DL(N); 6685 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6686 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6687 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6688 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6689 DAG.getValueType(MVT::i32)); 6690 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6691 } 6692 6693 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6694 SmallVectorImpl<SDValue> &Results, 6695 SelectionDAG &DAG) const { 6696 SDLoc DL(N); 6697 switch (N->getOpcode()) { 6698 default: 6699 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6700 case ISD::STRICT_FP_TO_SINT: 6701 case ISD::STRICT_FP_TO_UINT: 6702 case ISD::FP_TO_SINT: 6703 case ISD::FP_TO_UINT: { 6704 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6705 "Unexpected custom legalisation"); 6706 bool IsStrict = N->isStrictFPOpcode(); 6707 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6708 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6709 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6710 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6711 TargetLowering::TypeSoftenFloat) { 6712 if (!isTypeLegal(Op0.getValueType())) 6713 return; 6714 if (IsStrict) { 6715 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6716 : RISCVISD::STRICT_FCVT_WU_RV64; 6717 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6718 SDValue Res = DAG.getNode( 6719 Opc, DL, VTs, N->getOperand(0), Op0, 6720 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6721 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6722 Results.push_back(Res.getValue(1)); 6723 return; 6724 } 6725 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6726 SDValue Res = 6727 DAG.getNode(Opc, DL, MVT::i64, Op0, 6728 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6729 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6730 return; 6731 } 6732 // If the FP type needs to be softened, emit a library call using the 'si' 6733 // version. If we left it to default legalization we'd end up with 'di'. If 6734 // the FP type doesn't need to be softened just let generic type 6735 // legalization promote the result type. 6736 RTLIB::Libcall LC; 6737 if (IsSigned) 6738 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6739 else 6740 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6741 MakeLibCallOptions CallOptions; 6742 EVT OpVT = Op0.getValueType(); 6743 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6744 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6745 SDValue Result; 6746 std::tie(Result, Chain) = 6747 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6748 Results.push_back(Result); 6749 if (IsStrict) 6750 Results.push_back(Chain); 6751 break; 6752 } 6753 case ISD::READCYCLECOUNTER: { 6754 assert(!Subtarget.is64Bit() && 6755 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6756 6757 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6758 SDValue RCW = 6759 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6760 6761 Results.push_back( 6762 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6763 Results.push_back(RCW.getValue(2)); 6764 break; 6765 } 6766 case ISD::MUL: { 6767 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6768 unsigned XLen = Subtarget.getXLen(); 6769 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6770 if (Size > XLen) { 6771 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6772 SDValue LHS = N->getOperand(0); 6773 SDValue RHS = N->getOperand(1); 6774 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6775 6776 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6777 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6778 // We need exactly one side to be unsigned. 6779 if (LHSIsU == RHSIsU) 6780 return; 6781 6782 auto MakeMULPair = [&](SDValue S, SDValue U) { 6783 MVT XLenVT = Subtarget.getXLenVT(); 6784 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6785 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6786 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6787 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6788 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6789 }; 6790 6791 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6792 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6793 6794 // The other operand should be signed, but still prefer MULH when 6795 // possible. 6796 if (RHSIsU && LHSIsS && !RHSIsS) 6797 Results.push_back(MakeMULPair(LHS, RHS)); 6798 else if (LHSIsU && RHSIsS && !LHSIsS) 6799 Results.push_back(MakeMULPair(RHS, LHS)); 6800 6801 return; 6802 } 6803 LLVM_FALLTHROUGH; 6804 } 6805 case ISD::ADD: 6806 case ISD::SUB: 6807 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6808 "Unexpected custom legalisation"); 6809 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6810 break; 6811 case ISD::SHL: 6812 case ISD::SRA: 6813 case ISD::SRL: 6814 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6815 "Unexpected custom legalisation"); 6816 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6817 // If we can use a BSET instruction, allow default promotion to apply. 6818 if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() && 6819 isOneConstant(N->getOperand(0))) 6820 break; 6821 Results.push_back(customLegalizeToWOp(N, DAG)); 6822 break; 6823 } 6824 6825 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6826 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6827 // shift amount. 6828 if (N->getOpcode() == ISD::SHL) { 6829 SDLoc DL(N); 6830 SDValue NewOp0 = 6831 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6832 SDValue NewOp1 = 6833 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6834 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6835 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6836 DAG.getValueType(MVT::i32)); 6837 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6838 } 6839 6840 break; 6841 case ISD::ROTL: 6842 case ISD::ROTR: 6843 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6844 "Unexpected custom legalisation"); 6845 Results.push_back(customLegalizeToWOp(N, DAG)); 6846 break; 6847 case ISD::CTTZ: 6848 case ISD::CTTZ_ZERO_UNDEF: 6849 case ISD::CTLZ: 6850 case ISD::CTLZ_ZERO_UNDEF: { 6851 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6852 "Unexpected custom legalisation"); 6853 6854 SDValue NewOp0 = 6855 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6856 bool IsCTZ = 6857 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6858 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6859 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6860 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6861 return; 6862 } 6863 case ISD::SDIV: 6864 case ISD::UDIV: 6865 case ISD::UREM: { 6866 MVT VT = N->getSimpleValueType(0); 6867 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6868 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6869 "Unexpected custom legalisation"); 6870 // Don't promote division/remainder by constant since we should expand those 6871 // to multiply by magic constant. 6872 // FIXME: What if the expansion is disabled for minsize. 6873 if (N->getOperand(1).getOpcode() == ISD::Constant) 6874 return; 6875 6876 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6877 // the upper 32 bits. For other types we need to sign or zero extend 6878 // based on the opcode. 6879 unsigned ExtOpc = ISD::ANY_EXTEND; 6880 if (VT != MVT::i32) 6881 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6882 : ISD::ZERO_EXTEND; 6883 6884 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6885 break; 6886 } 6887 case ISD::UADDO: 6888 case ISD::USUBO: { 6889 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6890 "Unexpected custom legalisation"); 6891 bool IsAdd = N->getOpcode() == ISD::UADDO; 6892 // Create an ADDW or SUBW. 6893 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6894 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6895 SDValue Res = 6896 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6897 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6898 DAG.getValueType(MVT::i32)); 6899 6900 SDValue Overflow; 6901 if (IsAdd && isOneConstant(RHS)) { 6902 // Special case uaddo X, 1 overflowed if the addition result is 0. 6903 // The general case (X + C) < C is not necessarily beneficial. Although we 6904 // reduce the live range of X, we may introduce the materialization of 6905 // constant C, especially when the setcc result is used by branch. We have 6906 // no compare with constant and branch instructions. 6907 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, 6908 DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ); 6909 } else { 6910 // Sign extend the LHS and perform an unsigned compare with the ADDW 6911 // result. Since the inputs are sign extended from i32, this is equivalent 6912 // to comparing the lower 32 bits. 6913 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6914 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6915 IsAdd ? ISD::SETULT : ISD::SETUGT); 6916 } 6917 6918 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6919 Results.push_back(Overflow); 6920 return; 6921 } 6922 case ISD::UADDSAT: 6923 case ISD::USUBSAT: { 6924 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6925 "Unexpected custom legalisation"); 6926 if (Subtarget.hasStdExtZbb()) { 6927 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6928 // sign extend allows overflow of the lower 32 bits to be detected on 6929 // the promoted size. 6930 SDValue LHS = 6931 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6932 SDValue RHS = 6933 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6934 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6935 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6936 return; 6937 } 6938 6939 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6940 // promotion for UADDO/USUBO. 6941 Results.push_back(expandAddSubSat(N, DAG)); 6942 return; 6943 } 6944 case ISD::ABS: { 6945 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6946 "Unexpected custom legalisation"); 6947 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6948 6949 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 6950 6951 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6952 6953 // Freeze the source so we can increase it's use count. 6954 Src = DAG.getFreeze(Src); 6955 6956 // Copy sign bit to all bits using the sraiw pattern. 6957 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 6958 DAG.getValueType(MVT::i32)); 6959 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 6960 DAG.getConstant(31, DL, MVT::i64)); 6961 6962 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 6963 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 6964 6965 // NOTE: The result is only required to be anyextended, but sext is 6966 // consistent with type legalization of sub. 6967 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 6968 DAG.getValueType(MVT::i32)); 6969 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6970 return; 6971 } 6972 case ISD::BITCAST: { 6973 EVT VT = N->getValueType(0); 6974 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6975 SDValue Op0 = N->getOperand(0); 6976 EVT Op0VT = Op0.getValueType(); 6977 MVT XLenVT = Subtarget.getXLenVT(); 6978 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6979 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6980 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6981 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6982 Subtarget.hasStdExtF()) { 6983 SDValue FPConv = 6984 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6985 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6986 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6987 isTypeLegal(Op0VT)) { 6988 // Custom-legalize bitcasts from fixed-length vector types to illegal 6989 // scalar types in order to improve codegen. Bitcast the vector to a 6990 // one-element vector type whose element type is the same as the result 6991 // type, and extract the first element. 6992 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6993 if (isTypeLegal(BVT)) { 6994 SDValue BVec = DAG.getBitcast(BVT, Op0); 6995 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6996 DAG.getConstant(0, DL, XLenVT))); 6997 } 6998 } 6999 break; 7000 } 7001 case RISCVISD::GREV: 7002 case RISCVISD::GORC: 7003 case RISCVISD::SHFL: { 7004 MVT VT = N->getSimpleValueType(0); 7005 MVT XLenVT = Subtarget.getXLenVT(); 7006 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) && 7007 "Unexpected custom legalisation"); 7008 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 7009 assert((Subtarget.hasStdExtZbp() || 7010 (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV && 7011 N->getConstantOperandVal(1) == 7)) && 7012 "Unexpected extension"); 7013 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7014 SDValue NewOp1 = 7015 DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1)); 7016 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1); 7017 // ReplaceNodeResults requires we maintain the same type for the return 7018 // value. 7019 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes)); 7020 break; 7021 } 7022 case ISD::BSWAP: 7023 case ISD::BITREVERSE: { 7024 MVT VT = N->getSimpleValueType(0); 7025 MVT XLenVT = Subtarget.getXLenVT(); 7026 assert((VT == MVT::i8 || VT == MVT::i16 || 7027 (VT == MVT::i32 && Subtarget.is64Bit())) && 7028 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 7029 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7030 unsigned Imm = VT.getSizeInBits() - 1; 7031 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 7032 if (N->getOpcode() == ISD::BSWAP) 7033 Imm &= ~0x7U; 7034 SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0, 7035 DAG.getConstant(Imm, DL, XLenVT)); 7036 // ReplaceNodeResults requires we maintain the same type for the return 7037 // value. 7038 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 7039 break; 7040 } 7041 case ISD::FSHL: 7042 case ISD::FSHR: { 7043 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7044 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 7045 SDValue NewOp0 = 7046 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7047 SDValue NewOp1 = 7048 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7049 SDValue NewShAmt = 7050 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7051 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 7052 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 7053 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 7054 DAG.getConstant(0x1f, DL, MVT::i64)); 7055 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 7056 // instruction use different orders. fshl will return its first operand for 7057 // shift of zero, fshr will return its second operand. fsl and fsr both 7058 // return rs1 so the ISD nodes need to have different operand orders. 7059 // Shift amount is in rs2. 7060 unsigned Opc = RISCVISD::FSLW; 7061 if (N->getOpcode() == ISD::FSHR) { 7062 std::swap(NewOp0, NewOp1); 7063 Opc = RISCVISD::FSRW; 7064 } 7065 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 7066 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 7067 break; 7068 } 7069 case ISD::EXTRACT_VECTOR_ELT: { 7070 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 7071 // type is illegal (currently only vXi64 RV32). 7072 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 7073 // transferred to the destination register. We issue two of these from the 7074 // upper- and lower- halves of the SEW-bit vector element, slid down to the 7075 // first element. 7076 SDValue Vec = N->getOperand(0); 7077 SDValue Idx = N->getOperand(1); 7078 7079 // The vector type hasn't been legalized yet so we can't issue target 7080 // specific nodes if it needs legalization. 7081 // FIXME: We would manually legalize if it's important. 7082 if (!isTypeLegal(Vec.getValueType())) 7083 return; 7084 7085 MVT VecVT = Vec.getSimpleValueType(); 7086 7087 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 7088 VecVT.getVectorElementType() == MVT::i64 && 7089 "Unexpected EXTRACT_VECTOR_ELT legalization"); 7090 7091 // If this is a fixed vector, we need to convert it to a scalable vector. 7092 MVT ContainerVT = VecVT; 7093 if (VecVT.isFixedLengthVector()) { 7094 ContainerVT = getContainerForFixedLengthVector(VecVT); 7095 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 7096 } 7097 7098 MVT XLenVT = Subtarget.getXLenVT(); 7099 7100 // Use a VL of 1 to avoid processing more elements than we need. 7101 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7102 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 7103 7104 // Unless the index is known to be 0, we must slide the vector down to get 7105 // the desired element into index 0. 7106 if (!isNullConstant(Idx)) { 7107 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 7108 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 7109 } 7110 7111 // Extract the lower XLEN bits of the correct vector element. 7112 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7113 7114 // To extract the upper XLEN bits of the vector element, shift the first 7115 // element right by 32 bits and re-extract the lower XLEN bits. 7116 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 7117 DAG.getUNDEF(ContainerVT), 7118 DAG.getConstant(32, DL, XLenVT), VL); 7119 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 7120 ThirtyTwoV, Mask, VL); 7121 7122 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7123 7124 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7125 break; 7126 } 7127 case ISD::INTRINSIC_WO_CHAIN: { 7128 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7129 switch (IntNo) { 7130 default: 7131 llvm_unreachable( 7132 "Don't know how to custom type legalize this intrinsic!"); 7133 case Intrinsic::riscv_grev: 7134 case Intrinsic::riscv_gorc: { 7135 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7136 "Unexpected custom legalisation"); 7137 SDValue NewOp1 = 7138 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7139 SDValue NewOp2 = 7140 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7141 unsigned Opc = 7142 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 7143 // If the control is a constant, promote the node by clearing any extra 7144 // bits bits in the control. isel will form greviw/gorciw if the result is 7145 // sign extended. 7146 if (isa<ConstantSDNode>(NewOp2)) { 7147 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7148 DAG.getConstant(0x1f, DL, MVT::i64)); 7149 Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 7150 } 7151 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7152 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7153 break; 7154 } 7155 case Intrinsic::riscv_bcompress: 7156 case Intrinsic::riscv_bdecompress: 7157 case Intrinsic::riscv_bfp: 7158 case Intrinsic::riscv_fsl: 7159 case Intrinsic::riscv_fsr: { 7160 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7161 "Unexpected custom legalisation"); 7162 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 7163 break; 7164 } 7165 case Intrinsic::riscv_orc_b: { 7166 // Lower to the GORCI encoding for orc.b with the operand extended. 7167 SDValue NewOp = 7168 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7169 SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp, 7170 DAG.getConstant(7, DL, MVT::i64)); 7171 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7172 return; 7173 } 7174 case Intrinsic::riscv_shfl: 7175 case Intrinsic::riscv_unshfl: { 7176 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7177 "Unexpected custom legalisation"); 7178 SDValue NewOp1 = 7179 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7180 SDValue NewOp2 = 7181 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7182 unsigned Opc = 7183 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 7184 // There is no (UN)SHFLIW. If the control word is a constant, we can use 7185 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 7186 // will be shuffled the same way as the lower 32 bit half, but the two 7187 // halves won't cross. 7188 if (isa<ConstantSDNode>(NewOp2)) { 7189 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7190 DAG.getConstant(0xf, DL, MVT::i64)); 7191 Opc = 7192 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 7193 } 7194 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7195 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7196 break; 7197 } 7198 case Intrinsic::riscv_vmv_x_s: { 7199 EVT VT = N->getValueType(0); 7200 MVT XLenVT = Subtarget.getXLenVT(); 7201 if (VT.bitsLT(XLenVT)) { 7202 // Simple case just extract using vmv.x.s and truncate. 7203 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 7204 Subtarget.getXLenVT(), N->getOperand(1)); 7205 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 7206 return; 7207 } 7208 7209 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 7210 "Unexpected custom legalization"); 7211 7212 // We need to do the move in two steps. 7213 SDValue Vec = N->getOperand(1); 7214 MVT VecVT = Vec.getSimpleValueType(); 7215 7216 // First extract the lower XLEN bits of the element. 7217 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7218 7219 // To extract the upper XLEN bits of the vector element, shift the first 7220 // element right by 32 bits and re-extract the lower XLEN bits. 7221 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7222 SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG); 7223 7224 SDValue ThirtyTwoV = 7225 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 7226 DAG.getConstant(32, DL, XLenVT), VL); 7227 SDValue LShr32 = 7228 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 7229 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7230 7231 Results.push_back( 7232 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7233 break; 7234 } 7235 } 7236 break; 7237 } 7238 case ISD::VECREDUCE_ADD: 7239 case ISD::VECREDUCE_AND: 7240 case ISD::VECREDUCE_OR: 7241 case ISD::VECREDUCE_XOR: 7242 case ISD::VECREDUCE_SMAX: 7243 case ISD::VECREDUCE_UMAX: 7244 case ISD::VECREDUCE_SMIN: 7245 case ISD::VECREDUCE_UMIN: 7246 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 7247 Results.push_back(V); 7248 break; 7249 case ISD::VP_REDUCE_ADD: 7250 case ISD::VP_REDUCE_AND: 7251 case ISD::VP_REDUCE_OR: 7252 case ISD::VP_REDUCE_XOR: 7253 case ISD::VP_REDUCE_SMAX: 7254 case ISD::VP_REDUCE_UMAX: 7255 case ISD::VP_REDUCE_SMIN: 7256 case ISD::VP_REDUCE_UMIN: 7257 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 7258 Results.push_back(V); 7259 break; 7260 case ISD::FLT_ROUNDS_: { 7261 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7262 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7263 Results.push_back(Res.getValue(0)); 7264 Results.push_back(Res.getValue(1)); 7265 break; 7266 } 7267 } 7268 } 7269 7270 // A structure to hold one of the bit-manipulation patterns below. Together, a 7271 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7272 // (or (and (shl x, 1), 0xAAAAAAAA), 7273 // (and (srl x, 1), 0x55555555)) 7274 struct RISCVBitmanipPat { 7275 SDValue Op; 7276 unsigned ShAmt; 7277 bool IsSHL; 7278 7279 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7280 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7281 } 7282 }; 7283 7284 // Matches patterns of the form 7285 // (and (shl x, C2), (C1 << C2)) 7286 // (and (srl x, C2), C1) 7287 // (shl (and x, C1), C2) 7288 // (srl (and x, (C1 << C2)), C2) 7289 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7290 // The expected masks for each shift amount are specified in BitmanipMasks where 7291 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7292 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7293 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7294 // XLen is 64. 7295 static Optional<RISCVBitmanipPat> 7296 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7297 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7298 "Unexpected number of masks"); 7299 Optional<uint64_t> Mask; 7300 // Optionally consume a mask around the shift operation. 7301 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7302 Mask = Op.getConstantOperandVal(1); 7303 Op = Op.getOperand(0); 7304 } 7305 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7306 return None; 7307 bool IsSHL = Op.getOpcode() == ISD::SHL; 7308 7309 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7310 return None; 7311 uint64_t ShAmt = Op.getConstantOperandVal(1); 7312 7313 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7314 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7315 return None; 7316 // If we don't have enough masks for 64 bit, then we must be trying to 7317 // match SHFL so we're only allowed to shift 1/4 of the width. 7318 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7319 return None; 7320 7321 SDValue Src = Op.getOperand(0); 7322 7323 // The expected mask is shifted left when the AND is found around SHL 7324 // patterns. 7325 // ((x >> 1) & 0x55555555) 7326 // ((x << 1) & 0xAAAAAAAA) 7327 bool SHLExpMask = IsSHL; 7328 7329 if (!Mask) { 7330 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7331 // the mask is all ones: consume that now. 7332 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7333 Mask = Src.getConstantOperandVal(1); 7334 Src = Src.getOperand(0); 7335 // The expected mask is now in fact shifted left for SRL, so reverse the 7336 // decision. 7337 // ((x & 0xAAAAAAAA) >> 1) 7338 // ((x & 0x55555555) << 1) 7339 SHLExpMask = !SHLExpMask; 7340 } else { 7341 // Use a default shifted mask of all-ones if there's no AND, truncated 7342 // down to the expected width. This simplifies the logic later on. 7343 Mask = maskTrailingOnes<uint64_t>(Width); 7344 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7345 } 7346 } 7347 7348 unsigned MaskIdx = Log2_32(ShAmt); 7349 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7350 7351 if (SHLExpMask) 7352 ExpMask <<= ShAmt; 7353 7354 if (Mask != ExpMask) 7355 return None; 7356 7357 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7358 } 7359 7360 // Matches any of the following bit-manipulation patterns: 7361 // (and (shl x, 1), (0x55555555 << 1)) 7362 // (and (srl x, 1), 0x55555555) 7363 // (shl (and x, 0x55555555), 1) 7364 // (srl (and x, (0x55555555 << 1)), 1) 7365 // where the shift amount and mask may vary thus: 7366 // [1] = 0x55555555 / 0xAAAAAAAA 7367 // [2] = 0x33333333 / 0xCCCCCCCC 7368 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7369 // [8] = 0x00FF00FF / 0xFF00FF00 7370 // [16] = 0x0000FFFF / 0xFFFFFFFF 7371 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7372 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7373 // These are the unshifted masks which we use to match bit-manipulation 7374 // patterns. They may be shifted left in certain circumstances. 7375 static const uint64_t BitmanipMasks[] = { 7376 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7377 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7378 7379 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7380 } 7381 7382 // Try to fold (<bop> x, (reduction.<bop> vec, start)) 7383 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) { 7384 auto BinOpToRVVReduce = [](unsigned Opc) { 7385 switch (Opc) { 7386 default: 7387 llvm_unreachable("Unhandled binary to transfrom reduction"); 7388 case ISD::ADD: 7389 return RISCVISD::VECREDUCE_ADD_VL; 7390 case ISD::UMAX: 7391 return RISCVISD::VECREDUCE_UMAX_VL; 7392 case ISD::SMAX: 7393 return RISCVISD::VECREDUCE_SMAX_VL; 7394 case ISD::UMIN: 7395 return RISCVISD::VECREDUCE_UMIN_VL; 7396 case ISD::SMIN: 7397 return RISCVISD::VECREDUCE_SMIN_VL; 7398 case ISD::AND: 7399 return RISCVISD::VECREDUCE_AND_VL; 7400 case ISD::OR: 7401 return RISCVISD::VECREDUCE_OR_VL; 7402 case ISD::XOR: 7403 return RISCVISD::VECREDUCE_XOR_VL; 7404 case ISD::FADD: 7405 return RISCVISD::VECREDUCE_FADD_VL; 7406 case ISD::FMAXNUM: 7407 return RISCVISD::VECREDUCE_FMAX_VL; 7408 case ISD::FMINNUM: 7409 return RISCVISD::VECREDUCE_FMIN_VL; 7410 } 7411 }; 7412 7413 auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) { 7414 return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7415 isNullConstant(V.getOperand(1)) && 7416 V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc); 7417 }; 7418 7419 unsigned Opc = N->getOpcode(); 7420 unsigned ReduceIdx; 7421 if (IsReduction(N->getOperand(0), Opc)) 7422 ReduceIdx = 0; 7423 else if (IsReduction(N->getOperand(1), Opc)) 7424 ReduceIdx = 1; 7425 else 7426 return SDValue(); 7427 7428 // Skip if FADD disallows reassociation but the combiner needs. 7429 if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation()) 7430 return SDValue(); 7431 7432 SDValue Extract = N->getOperand(ReduceIdx); 7433 SDValue Reduce = Extract.getOperand(0); 7434 if (!Reduce.hasOneUse()) 7435 return SDValue(); 7436 7437 SDValue ScalarV = Reduce.getOperand(2); 7438 7439 // Make sure that ScalarV is a splat with VL=1. 7440 if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL && 7441 ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL && 7442 ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL) 7443 return SDValue(); 7444 7445 if (!isOneConstant(ScalarV.getOperand(2))) 7446 return SDValue(); 7447 7448 // TODO: Deal with value other than neutral element. 7449 auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) { 7450 if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() && 7451 isNullFPConstant(V)) 7452 return true; 7453 return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(), 7454 N->getFlags()) == V; 7455 }; 7456 7457 // Check the scalar of ScalarV is neutral element 7458 if (!IsRVVNeutralElement(N, ScalarV.getOperand(1))) 7459 return SDValue(); 7460 7461 if (!ScalarV.hasOneUse()) 7462 return SDValue(); 7463 7464 EVT SplatVT = ScalarV.getValueType(); 7465 SDValue NewStart = N->getOperand(1 - ReduceIdx); 7466 unsigned SplatOpc = RISCVISD::VFMV_S_F_VL; 7467 if (SplatVT.isInteger()) { 7468 auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode()); 7469 if (!C || C->isZero() || !isInt<5>(C->getSExtValue())) 7470 SplatOpc = RISCVISD::VMV_S_X_VL; 7471 else 7472 SplatOpc = RISCVISD::VMV_V_X_VL; 7473 } 7474 7475 SDValue NewScalarV = 7476 DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart, 7477 ScalarV.getOperand(2)); 7478 SDValue NewReduce = 7479 DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(), 7480 Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV, 7481 Reduce.getOperand(3), Reduce.getOperand(4)); 7482 return DAG.getNode(Extract.getOpcode(), SDLoc(Extract), 7483 Extract.getValueType(), NewReduce, Extract.getOperand(1)); 7484 } 7485 7486 // Match the following pattern as a GREVI(W) operation 7487 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7488 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7489 const RISCVSubtarget &Subtarget) { 7490 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7491 EVT VT = Op.getValueType(); 7492 7493 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7494 auto LHS = matchGREVIPat(Op.getOperand(0)); 7495 auto RHS = matchGREVIPat(Op.getOperand(1)); 7496 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7497 SDLoc DL(Op); 7498 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7499 DAG.getConstant(LHS->ShAmt, DL, VT)); 7500 } 7501 } 7502 return SDValue(); 7503 } 7504 7505 // Matches any the following pattern as a GORCI(W) operation 7506 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7507 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7508 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7509 // Note that with the variant of 3., 7510 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7511 // the inner pattern will first be matched as GREVI and then the outer 7512 // pattern will be matched to GORC via the first rule above. 7513 // 4. (or (rotl/rotr x, bitwidth/2), x) 7514 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7515 const RISCVSubtarget &Subtarget) { 7516 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7517 EVT VT = Op.getValueType(); 7518 7519 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7520 SDLoc DL(Op); 7521 SDValue Op0 = Op.getOperand(0); 7522 SDValue Op1 = Op.getOperand(1); 7523 7524 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7525 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7526 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7527 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7528 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7529 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7530 if ((Reverse.getOpcode() == ISD::ROTL || 7531 Reverse.getOpcode() == ISD::ROTR) && 7532 Reverse.getOperand(0) == X && 7533 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7534 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7535 if (RotAmt == (VT.getSizeInBits() / 2)) 7536 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7537 DAG.getConstant(RotAmt, DL, VT)); 7538 } 7539 return SDValue(); 7540 }; 7541 7542 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7543 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7544 return V; 7545 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7546 return V; 7547 7548 // OR is commutable so canonicalize its OR operand to the left 7549 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7550 std::swap(Op0, Op1); 7551 if (Op0.getOpcode() != ISD::OR) 7552 return SDValue(); 7553 SDValue OrOp0 = Op0.getOperand(0); 7554 SDValue OrOp1 = Op0.getOperand(1); 7555 auto LHS = matchGREVIPat(OrOp0); 7556 // OR is commutable so swap the operands and try again: x might have been 7557 // on the left 7558 if (!LHS) { 7559 std::swap(OrOp0, OrOp1); 7560 LHS = matchGREVIPat(OrOp0); 7561 } 7562 auto RHS = matchGREVIPat(Op1); 7563 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7564 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7565 DAG.getConstant(LHS->ShAmt, DL, VT)); 7566 } 7567 } 7568 return SDValue(); 7569 } 7570 7571 // Matches any of the following bit-manipulation patterns: 7572 // (and (shl x, 1), (0x22222222 << 1)) 7573 // (and (srl x, 1), 0x22222222) 7574 // (shl (and x, 0x22222222), 1) 7575 // (srl (and x, (0x22222222 << 1)), 1) 7576 // where the shift amount and mask may vary thus: 7577 // [1] = 0x22222222 / 0x44444444 7578 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7579 // [4] = 0x00F000F0 / 0x0F000F00 7580 // [8] = 0x0000FF00 / 0x00FF0000 7581 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7582 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7583 // These are the unshifted masks which we use to match bit-manipulation 7584 // patterns. They may be shifted left in certain circumstances. 7585 static const uint64_t BitmanipMasks[] = { 7586 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7587 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7588 7589 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7590 } 7591 7592 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7593 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7594 const RISCVSubtarget &Subtarget) { 7595 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7596 EVT VT = Op.getValueType(); 7597 7598 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7599 return SDValue(); 7600 7601 SDValue Op0 = Op.getOperand(0); 7602 SDValue Op1 = Op.getOperand(1); 7603 7604 // Or is commutable so canonicalize the second OR to the LHS. 7605 if (Op0.getOpcode() != ISD::OR) 7606 std::swap(Op0, Op1); 7607 if (Op0.getOpcode() != ISD::OR) 7608 return SDValue(); 7609 7610 // We found an inner OR, so our operands are the operands of the inner OR 7611 // and the other operand of the outer OR. 7612 SDValue A = Op0.getOperand(0); 7613 SDValue B = Op0.getOperand(1); 7614 SDValue C = Op1; 7615 7616 auto Match1 = matchSHFLPat(A); 7617 auto Match2 = matchSHFLPat(B); 7618 7619 // If neither matched, we failed. 7620 if (!Match1 && !Match2) 7621 return SDValue(); 7622 7623 // We had at least one match. if one failed, try the remaining C operand. 7624 if (!Match1) { 7625 std::swap(A, C); 7626 Match1 = matchSHFLPat(A); 7627 if (!Match1) 7628 return SDValue(); 7629 } else if (!Match2) { 7630 std::swap(B, C); 7631 Match2 = matchSHFLPat(B); 7632 if (!Match2) 7633 return SDValue(); 7634 } 7635 assert(Match1 && Match2); 7636 7637 // Make sure our matches pair up. 7638 if (!Match1->formsPairWith(*Match2)) 7639 return SDValue(); 7640 7641 // All the remains is to make sure C is an AND with the same input, that masks 7642 // out the bits that are being shuffled. 7643 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7644 C.getOperand(0) != Match1->Op) 7645 return SDValue(); 7646 7647 uint64_t Mask = C.getConstantOperandVal(1); 7648 7649 static const uint64_t BitmanipMasks[] = { 7650 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7651 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7652 }; 7653 7654 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7655 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7656 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7657 7658 if (Mask != ExpMask) 7659 return SDValue(); 7660 7661 SDLoc DL(Op); 7662 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7663 DAG.getConstant(Match1->ShAmt, DL, VT)); 7664 } 7665 7666 // Optimize (add (shl x, c0), (shl y, c1)) -> 7667 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7668 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7669 const RISCVSubtarget &Subtarget) { 7670 // Perform this optimization only in the zba extension. 7671 if (!Subtarget.hasStdExtZba()) 7672 return SDValue(); 7673 7674 // Skip for vector types and larger types. 7675 EVT VT = N->getValueType(0); 7676 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7677 return SDValue(); 7678 7679 // The two operand nodes must be SHL and have no other use. 7680 SDValue N0 = N->getOperand(0); 7681 SDValue N1 = N->getOperand(1); 7682 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7683 !N0->hasOneUse() || !N1->hasOneUse()) 7684 return SDValue(); 7685 7686 // Check c0 and c1. 7687 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7688 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7689 if (!N0C || !N1C) 7690 return SDValue(); 7691 int64_t C0 = N0C->getSExtValue(); 7692 int64_t C1 = N1C->getSExtValue(); 7693 if (C0 <= 0 || C1 <= 0) 7694 return SDValue(); 7695 7696 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7697 int64_t Bits = std::min(C0, C1); 7698 int64_t Diff = std::abs(C0 - C1); 7699 if (Diff != 1 && Diff != 2 && Diff != 3) 7700 return SDValue(); 7701 7702 // Build nodes. 7703 SDLoc DL(N); 7704 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7705 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7706 SDValue NA0 = 7707 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7708 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7709 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7710 } 7711 7712 // Combine 7713 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7714 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7715 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7716 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7717 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7718 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7719 // The grev patterns represents BSWAP. 7720 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7721 // off the grev. 7722 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7723 const RISCVSubtarget &Subtarget) { 7724 bool IsWInstruction = 7725 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7726 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7727 IsWInstruction) && 7728 "Unexpected opcode!"); 7729 SDValue Src = N->getOperand(0); 7730 EVT VT = N->getValueType(0); 7731 SDLoc DL(N); 7732 7733 if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV) 7734 return SDValue(); 7735 7736 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7737 !isa<ConstantSDNode>(Src.getOperand(1))) 7738 return SDValue(); 7739 7740 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7741 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7742 7743 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7744 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7745 unsigned ShAmt1 = N->getConstantOperandVal(1); 7746 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7747 if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7748 return SDValue(); 7749 7750 Src = Src.getOperand(0); 7751 7752 // Toggle bit the MSB of the shift. 7753 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7754 if (CombinedShAmt == 0) 7755 return Src; 7756 7757 SDValue Res = DAG.getNode( 7758 RISCVISD::GREV, DL, VT, Src, 7759 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7760 if (!IsWInstruction) 7761 return Res; 7762 7763 // Sign extend the result to match the behavior of the rotate. This will be 7764 // selected to GREVIW in isel. 7765 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res, 7766 DAG.getValueType(MVT::i32)); 7767 } 7768 7769 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7770 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7771 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7772 // not undo itself, but they are redundant. 7773 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7774 bool IsGORC = N->getOpcode() == RISCVISD::GORC; 7775 assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode"); 7776 SDValue Src = N->getOperand(0); 7777 7778 if (Src.getOpcode() != N->getOpcode()) 7779 return SDValue(); 7780 7781 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7782 !isa<ConstantSDNode>(Src.getOperand(1))) 7783 return SDValue(); 7784 7785 unsigned ShAmt1 = N->getConstantOperandVal(1); 7786 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7787 Src = Src.getOperand(0); 7788 7789 unsigned CombinedShAmt; 7790 if (IsGORC) 7791 CombinedShAmt = ShAmt1 | ShAmt2; 7792 else 7793 CombinedShAmt = ShAmt1 ^ ShAmt2; 7794 7795 if (CombinedShAmt == 0) 7796 return Src; 7797 7798 SDLoc DL(N); 7799 return DAG.getNode( 7800 N->getOpcode(), DL, N->getValueType(0), Src, 7801 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7802 } 7803 7804 // Combine a constant select operand into its use: 7805 // 7806 // (and (select cond, -1, c), x) 7807 // -> (select cond, x, (and x, c)) [AllOnes=1] 7808 // (or (select cond, 0, c), x) 7809 // -> (select cond, x, (or x, c)) [AllOnes=0] 7810 // (xor (select cond, 0, c), x) 7811 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7812 // (add (select cond, 0, c), x) 7813 // -> (select cond, x, (add x, c)) [AllOnes=0] 7814 // (sub x, (select cond, 0, c)) 7815 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7816 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7817 SelectionDAG &DAG, bool AllOnes) { 7818 EVT VT = N->getValueType(0); 7819 7820 // Skip vectors. 7821 if (VT.isVector()) 7822 return SDValue(); 7823 7824 if ((Slct.getOpcode() != ISD::SELECT && 7825 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7826 !Slct.hasOneUse()) 7827 return SDValue(); 7828 7829 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7830 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7831 }; 7832 7833 bool SwapSelectOps; 7834 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7835 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7836 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7837 SDValue NonConstantVal; 7838 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7839 SwapSelectOps = false; 7840 NonConstantVal = FalseVal; 7841 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7842 SwapSelectOps = true; 7843 NonConstantVal = TrueVal; 7844 } else 7845 return SDValue(); 7846 7847 // Slct is now know to be the desired identity constant when CC is true. 7848 TrueVal = OtherOp; 7849 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7850 // Unless SwapSelectOps says the condition should be false. 7851 if (SwapSelectOps) 7852 std::swap(TrueVal, FalseVal); 7853 7854 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7855 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7856 {Slct.getOperand(0), Slct.getOperand(1), 7857 Slct.getOperand(2), TrueVal, FalseVal}); 7858 7859 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7860 {Slct.getOperand(0), TrueVal, FalseVal}); 7861 } 7862 7863 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7864 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7865 bool AllOnes) { 7866 SDValue N0 = N->getOperand(0); 7867 SDValue N1 = N->getOperand(1); 7868 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7869 return Result; 7870 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7871 return Result; 7872 return SDValue(); 7873 } 7874 7875 // Transform (add (mul x, c0), c1) -> 7876 // (add (mul (add x, c1/c0), c0), c1%c0). 7877 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7878 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7879 // to an infinite loop in DAGCombine if transformed. 7880 // Or transform (add (mul x, c0), c1) -> 7881 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7882 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7883 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7884 // lead to an infinite loop in DAGCombine if transformed. 7885 // Or transform (add (mul x, c0), c1) -> 7886 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7887 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7888 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7889 // lead to an infinite loop in DAGCombine if transformed. 7890 // Or transform (add (mul x, c0), c1) -> 7891 // (mul (add x, c1/c0), c0). 7892 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7893 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7894 const RISCVSubtarget &Subtarget) { 7895 // Skip for vector types and larger types. 7896 EVT VT = N->getValueType(0); 7897 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7898 return SDValue(); 7899 // The first operand node must be a MUL and has no other use. 7900 SDValue N0 = N->getOperand(0); 7901 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7902 return SDValue(); 7903 // Check if c0 and c1 match above conditions. 7904 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7905 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7906 if (!N0C || !N1C) 7907 return SDValue(); 7908 // If N0C has multiple uses it's possible one of the cases in 7909 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 7910 // in an infinite loop. 7911 if (!N0C->hasOneUse()) 7912 return SDValue(); 7913 int64_t C0 = N0C->getSExtValue(); 7914 int64_t C1 = N1C->getSExtValue(); 7915 int64_t CA, CB; 7916 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7917 return SDValue(); 7918 // Search for proper CA (non-zero) and CB that both are simm12. 7919 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7920 !isInt<12>(C0 * (C1 / C0))) { 7921 CA = C1 / C0; 7922 CB = C1 % C0; 7923 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7924 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7925 CA = C1 / C0 + 1; 7926 CB = C1 % C0 - C0; 7927 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7928 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7929 CA = C1 / C0 - 1; 7930 CB = C1 % C0 + C0; 7931 } else 7932 return SDValue(); 7933 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7934 SDLoc DL(N); 7935 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7936 DAG.getConstant(CA, DL, VT)); 7937 SDValue New1 = 7938 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7939 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7940 } 7941 7942 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7943 const RISCVSubtarget &Subtarget) { 7944 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7945 return V; 7946 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7947 return V; 7948 if (SDValue V = combineBinOpToReduce(N, DAG)) 7949 return V; 7950 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7951 // (select lhs, rhs, cc, x, (add x, y)) 7952 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7953 } 7954 7955 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7956 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 7957 // (select lhs, rhs, cc, x, (sub x, y)) 7958 SDValue N0 = N->getOperand(0); 7959 SDValue N1 = N->getOperand(1); 7960 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 7961 } 7962 7963 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG, 7964 const RISCVSubtarget &Subtarget) { 7965 SDValue N0 = N->getOperand(0); 7966 // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero 7967 // extending X. This is safe since we only need the LSB after the shift and 7968 // shift amounts larger than 31 would produce poison. If we wait until 7969 // type legalization, we'll create RISCVISD::SRLW and we can't recover it 7970 // to use a BEXT instruction. 7971 if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() && 7972 N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) && 7973 N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) && 7974 N0.hasOneUse()) { 7975 SDLoc DL(N); 7976 SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0)); 7977 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1)); 7978 SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1); 7979 SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl, 7980 DAG.getConstant(1, DL, MVT::i64)); 7981 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And); 7982 } 7983 7984 if (SDValue V = combineBinOpToReduce(N, DAG)) 7985 return V; 7986 7987 // fold (and (select lhs, rhs, cc, -1, y), x) -> 7988 // (select lhs, rhs, cc, x, (and x, y)) 7989 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 7990 } 7991 7992 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 7993 const RISCVSubtarget &Subtarget) { 7994 if (Subtarget.hasStdExtZbp()) { 7995 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 7996 return GREV; 7997 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 7998 return GORC; 7999 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 8000 return SHFL; 8001 } 8002 8003 if (SDValue V = combineBinOpToReduce(N, DAG)) 8004 return V; 8005 // fold (or (select cond, 0, y), x) -> 8006 // (select cond, x, (or x, y)) 8007 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8008 } 8009 8010 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 8011 SDValue N0 = N->getOperand(0); 8012 SDValue N1 = N->getOperand(1); 8013 8014 // fold (xor (sllw 1, x), -1) -> (rolw ~1, x) 8015 // NOTE: Assumes ROL being legal means ROLW is legal. 8016 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8017 if (N0.getOpcode() == RISCVISD::SLLW && 8018 isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) && 8019 TLI.isOperationLegal(ISD::ROTL, MVT::i64)) { 8020 SDLoc DL(N); 8021 return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64, 8022 DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1)); 8023 } 8024 8025 if (SDValue V = combineBinOpToReduce(N, DAG)) 8026 return V; 8027 // fold (xor (select cond, 0, y), x) -> 8028 // (select cond, x, (xor x, y)) 8029 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8030 } 8031 8032 static SDValue 8033 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 8034 const RISCVSubtarget &Subtarget) { 8035 SDValue Src = N->getOperand(0); 8036 EVT VT = N->getValueType(0); 8037 8038 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 8039 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8040 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 8041 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 8042 Src.getOperand(0)); 8043 8044 // Fold (i64 (sext_inreg (abs X), i32)) -> 8045 // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits. 8046 // The (sext_inreg (neg X), i32) will be selected to negw by isel. This 8047 // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user 8048 // of the (i32 (abs X)) is a sext or setcc or something else that causes type 8049 // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have 8050 // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg 8051 // may get combined into an earlier operation so we need to use 8052 // ComputeNumSignBits. 8053 // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for 8054 // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so 8055 // we can't assume that X has 33 sign bits. We must check. 8056 if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() && 8057 Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 && 8058 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 && 8059 DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) { 8060 SDLoc DL(N); 8061 SDValue Freeze = DAG.getFreeze(Src.getOperand(0)); 8062 SDValue Neg = 8063 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze); 8064 Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg, 8065 DAG.getValueType(MVT::i32)); 8066 return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg); 8067 } 8068 8069 return SDValue(); 8070 } 8071 8072 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 8073 // vwadd(u).vv/vx or vwsub(u).vv/vx. 8074 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 8075 bool Commute = false) { 8076 assert((N->getOpcode() == RISCVISD::ADD_VL || 8077 N->getOpcode() == RISCVISD::SUB_VL) && 8078 "Unexpected opcode"); 8079 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 8080 SDValue Op0 = N->getOperand(0); 8081 SDValue Op1 = N->getOperand(1); 8082 if (Commute) 8083 std::swap(Op0, Op1); 8084 8085 MVT VT = N->getSimpleValueType(0); 8086 8087 // Determine the narrow size for a widening add/sub. 8088 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8089 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8090 VT.getVectorElementCount()); 8091 8092 SDValue Mask = N->getOperand(2); 8093 SDValue VL = N->getOperand(3); 8094 8095 SDLoc DL(N); 8096 8097 // If the RHS is a sext or zext, we can form a widening op. 8098 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 8099 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 8100 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 8101 unsigned ExtOpc = Op1.getOpcode(); 8102 Op1 = Op1.getOperand(0); 8103 // Re-introduce narrower extends if needed. 8104 if (Op1.getValueType() != NarrowVT) 8105 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8106 8107 unsigned WOpc; 8108 if (ExtOpc == RISCVISD::VSEXT_VL) 8109 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 8110 else 8111 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 8112 8113 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 8114 } 8115 8116 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 8117 // sext/zext? 8118 8119 return SDValue(); 8120 } 8121 8122 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 8123 // vwsub(u).vv/vx. 8124 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 8125 SDValue Op0 = N->getOperand(0); 8126 SDValue Op1 = N->getOperand(1); 8127 SDValue Mask = N->getOperand(2); 8128 SDValue VL = N->getOperand(3); 8129 8130 MVT VT = N->getSimpleValueType(0); 8131 MVT NarrowVT = Op1.getSimpleValueType(); 8132 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 8133 8134 unsigned VOpc; 8135 switch (N->getOpcode()) { 8136 default: llvm_unreachable("Unexpected opcode"); 8137 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 8138 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 8139 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 8140 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 8141 } 8142 8143 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 8144 N->getOpcode() == RISCVISD::VWSUB_W_VL; 8145 8146 SDLoc DL(N); 8147 8148 // If the LHS is a sext or zext, we can narrow this op to the same size as 8149 // the RHS. 8150 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 8151 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 8152 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 8153 unsigned ExtOpc = Op0.getOpcode(); 8154 Op0 = Op0.getOperand(0); 8155 // Re-introduce narrower extends if needed. 8156 if (Op0.getValueType() != NarrowVT) 8157 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8158 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 8159 } 8160 8161 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 8162 N->getOpcode() == RISCVISD::VWADDU_W_VL; 8163 8164 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 8165 // to commute and use a vwadd(u).vx instead. 8166 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 8167 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 8168 Op0 = Op0.getOperand(1); 8169 8170 // See if have enough sign bits or zero bits in the scalar to use a 8171 // widening add/sub by splatting to smaller element size. 8172 unsigned EltBits = VT.getScalarSizeInBits(); 8173 unsigned ScalarBits = Op0.getValueSizeInBits(); 8174 // Make sure we're getting all element bits from the scalar register. 8175 // FIXME: Support implicit sign extension of vmv.v.x? 8176 if (ScalarBits < EltBits) 8177 return SDValue(); 8178 8179 if (IsSigned) { 8180 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 8181 return SDValue(); 8182 } else { 8183 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8184 if (!DAG.MaskedValueIsZero(Op0, Mask)) 8185 return SDValue(); 8186 } 8187 8188 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8189 DAG.getUNDEF(NarrowVT), Op0, VL); 8190 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 8191 } 8192 8193 return SDValue(); 8194 } 8195 8196 // Try to form VWMUL, VWMULU or VWMULSU. 8197 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 8198 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 8199 bool Commute) { 8200 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 8201 SDValue Op0 = N->getOperand(0); 8202 SDValue Op1 = N->getOperand(1); 8203 if (Commute) 8204 std::swap(Op0, Op1); 8205 8206 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 8207 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 8208 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 8209 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 8210 return SDValue(); 8211 8212 SDValue Mask = N->getOperand(2); 8213 SDValue VL = N->getOperand(3); 8214 8215 // Make sure the mask and VL match. 8216 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 8217 return SDValue(); 8218 8219 MVT VT = N->getSimpleValueType(0); 8220 8221 // Determine the narrow size for a widening multiply. 8222 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8223 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8224 VT.getVectorElementCount()); 8225 8226 SDLoc DL(N); 8227 8228 // See if the other operand is the same opcode. 8229 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 8230 if (!Op1.hasOneUse()) 8231 return SDValue(); 8232 8233 // Make sure the mask and VL match. 8234 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 8235 return SDValue(); 8236 8237 Op1 = Op1.getOperand(0); 8238 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 8239 // The operand is a splat of a scalar. 8240 8241 // The pasthru must be undef for tail agnostic 8242 if (!Op1.getOperand(0).isUndef()) 8243 return SDValue(); 8244 // The VL must be the same. 8245 if (Op1.getOperand(2) != VL) 8246 return SDValue(); 8247 8248 // Get the scalar value. 8249 Op1 = Op1.getOperand(1); 8250 8251 // See if have enough sign bits or zero bits in the scalar to use a 8252 // widening multiply by splatting to smaller element size. 8253 unsigned EltBits = VT.getScalarSizeInBits(); 8254 unsigned ScalarBits = Op1.getValueSizeInBits(); 8255 // Make sure we're getting all element bits from the scalar register. 8256 // FIXME: Support implicit sign extension of vmv.v.x? 8257 if (ScalarBits < EltBits) 8258 return SDValue(); 8259 8260 // If the LHS is a sign extend, try to use vwmul. 8261 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 8262 // Can use vwmul. 8263 } else { 8264 // Otherwise try to use vwmulu or vwmulsu. 8265 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8266 if (DAG.MaskedValueIsZero(Op1, Mask)) 8267 IsVWMULSU = IsSignExt; 8268 else 8269 return SDValue(); 8270 } 8271 8272 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8273 DAG.getUNDEF(NarrowVT), Op1, VL); 8274 } else 8275 return SDValue(); 8276 8277 Op0 = Op0.getOperand(0); 8278 8279 // Re-introduce narrower extends if needed. 8280 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 8281 if (Op0.getValueType() != NarrowVT) 8282 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8283 // vwmulsu requires second operand to be zero extended. 8284 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 8285 if (Op1.getValueType() != NarrowVT) 8286 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8287 8288 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 8289 if (!IsVWMULSU) 8290 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 8291 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 8292 } 8293 8294 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 8295 switch (Op.getOpcode()) { 8296 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 8297 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 8298 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 8299 case ISD::FCEIL: return RISCVFPRndMode::RUP; 8300 case ISD::FROUND: return RISCVFPRndMode::RMM; 8301 } 8302 8303 return RISCVFPRndMode::Invalid; 8304 } 8305 8306 // Fold 8307 // (fp_to_int (froundeven X)) -> fcvt X, rne 8308 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 8309 // (fp_to_int (ffloor X)) -> fcvt X, rdn 8310 // (fp_to_int (fceil X)) -> fcvt X, rup 8311 // (fp_to_int (fround X)) -> fcvt X, rmm 8312 static SDValue performFP_TO_INTCombine(SDNode *N, 8313 TargetLowering::DAGCombinerInfo &DCI, 8314 const RISCVSubtarget &Subtarget) { 8315 SelectionDAG &DAG = DCI.DAG; 8316 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8317 MVT XLenVT = Subtarget.getXLenVT(); 8318 8319 // Only handle XLen or i32 types. Other types narrower than XLen will 8320 // eventually be legalized to XLenVT. 8321 EVT VT = N->getValueType(0); 8322 if (VT != MVT::i32 && VT != XLenVT) 8323 return SDValue(); 8324 8325 SDValue Src = N->getOperand(0); 8326 8327 // Ensure the FP type is also legal. 8328 if (!TLI.isTypeLegal(Src.getValueType())) 8329 return SDValue(); 8330 8331 // Don't do this for f16 with Zfhmin and not Zfh. 8332 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8333 return SDValue(); 8334 8335 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8336 if (FRM == RISCVFPRndMode::Invalid) 8337 return SDValue(); 8338 8339 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8340 8341 unsigned Opc; 8342 if (VT == XLenVT) 8343 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8344 else 8345 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8346 8347 SDLoc DL(N); 8348 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 8349 DAG.getTargetConstant(FRM, DL, XLenVT)); 8350 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 8351 } 8352 8353 // Fold 8354 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 8355 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 8356 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8357 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8358 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8359 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8360 TargetLowering::DAGCombinerInfo &DCI, 8361 const RISCVSubtarget &Subtarget) { 8362 SelectionDAG &DAG = DCI.DAG; 8363 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8364 MVT XLenVT = Subtarget.getXLenVT(); 8365 8366 // Only handle XLen types. Other types narrower than XLen will eventually be 8367 // legalized to XLenVT. 8368 EVT DstVT = N->getValueType(0); 8369 if (DstVT != XLenVT) 8370 return SDValue(); 8371 8372 SDValue Src = N->getOperand(0); 8373 8374 // Ensure the FP type is also legal. 8375 if (!TLI.isTypeLegal(Src.getValueType())) 8376 return SDValue(); 8377 8378 // Don't do this for f16 with Zfhmin and not Zfh. 8379 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8380 return SDValue(); 8381 8382 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8383 8384 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8385 if (FRM == RISCVFPRndMode::Invalid) 8386 return SDValue(); 8387 8388 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8389 8390 unsigned Opc; 8391 if (SatVT == DstVT) 8392 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8393 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8394 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8395 else 8396 return SDValue(); 8397 // FIXME: Support other SatVTs by clamping before or after the conversion. 8398 8399 Src = Src.getOperand(0); 8400 8401 SDLoc DL(N); 8402 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8403 DAG.getTargetConstant(FRM, DL, XLenVT)); 8404 8405 // RISCV FP-to-int conversions saturate to the destination register size, but 8406 // don't produce 0 for nan. 8407 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8408 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8409 } 8410 8411 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is 8412 // smaller than XLenVT. 8413 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG, 8414 const RISCVSubtarget &Subtarget) { 8415 assert(Subtarget.hasStdExtZbkb() && "Unexpected extension"); 8416 8417 SDValue Src = N->getOperand(0); 8418 if (Src.getOpcode() != ISD::BSWAP) 8419 return SDValue(); 8420 8421 EVT VT = N->getValueType(0); 8422 if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() || 8423 !isPowerOf2_32(VT.getSizeInBits())) 8424 return SDValue(); 8425 8426 SDLoc DL(N); 8427 return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0), 8428 DAG.getConstant(7, DL, VT)); 8429 } 8430 8431 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8432 DAGCombinerInfo &DCI) const { 8433 SelectionDAG &DAG = DCI.DAG; 8434 8435 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8436 // bits are demanded. N will be added to the Worklist if it was not deleted. 8437 // Caller should return SDValue(N, 0) if this returns true. 8438 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8439 SDValue Op = N->getOperand(OpNo); 8440 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8441 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8442 return false; 8443 8444 if (N->getOpcode() != ISD::DELETED_NODE) 8445 DCI.AddToWorklist(N); 8446 return true; 8447 }; 8448 8449 switch (N->getOpcode()) { 8450 default: 8451 break; 8452 case RISCVISD::SplitF64: { 8453 SDValue Op0 = N->getOperand(0); 8454 // If the input to SplitF64 is just BuildPairF64 then the operation is 8455 // redundant. Instead, use BuildPairF64's operands directly. 8456 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8457 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8458 8459 if (Op0->isUndef()) { 8460 SDValue Lo = DAG.getUNDEF(MVT::i32); 8461 SDValue Hi = DAG.getUNDEF(MVT::i32); 8462 return DCI.CombineTo(N, Lo, Hi); 8463 } 8464 8465 SDLoc DL(N); 8466 8467 // It's cheaper to materialise two 32-bit integers than to load a double 8468 // from the constant pool and transfer it to integer registers through the 8469 // stack. 8470 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8471 APInt V = C->getValueAPF().bitcastToAPInt(); 8472 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8473 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8474 return DCI.CombineTo(N, Lo, Hi); 8475 } 8476 8477 // This is a target-specific version of a DAGCombine performed in 8478 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8479 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8480 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8481 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8482 !Op0.getNode()->hasOneUse()) 8483 break; 8484 SDValue NewSplitF64 = 8485 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8486 Op0.getOperand(0)); 8487 SDValue Lo = NewSplitF64.getValue(0); 8488 SDValue Hi = NewSplitF64.getValue(1); 8489 APInt SignBit = APInt::getSignMask(32); 8490 if (Op0.getOpcode() == ISD::FNEG) { 8491 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8492 DAG.getConstant(SignBit, DL, MVT::i32)); 8493 return DCI.CombineTo(N, Lo, NewHi); 8494 } 8495 assert(Op0.getOpcode() == ISD::FABS); 8496 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8497 DAG.getConstant(~SignBit, DL, MVT::i32)); 8498 return DCI.CombineTo(N, Lo, NewHi); 8499 } 8500 case RISCVISD::SLLW: 8501 case RISCVISD::SRAW: 8502 case RISCVISD::SRLW: { 8503 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8504 if (SimplifyDemandedLowBitsHelper(0, 32) || 8505 SimplifyDemandedLowBitsHelper(1, 5)) 8506 return SDValue(N, 0); 8507 8508 break; 8509 } 8510 case ISD::ROTR: 8511 case ISD::ROTL: 8512 case RISCVISD::RORW: 8513 case RISCVISD::ROLW: { 8514 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8515 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8516 if (SimplifyDemandedLowBitsHelper(0, 32) || 8517 SimplifyDemandedLowBitsHelper(1, 5)) 8518 return SDValue(N, 0); 8519 } 8520 8521 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8522 } 8523 case RISCVISD::CLZW: 8524 case RISCVISD::CTZW: { 8525 // Only the lower 32 bits of the first operand are read 8526 if (SimplifyDemandedLowBitsHelper(0, 32)) 8527 return SDValue(N, 0); 8528 break; 8529 } 8530 case RISCVISD::GREV: 8531 case RISCVISD::GORC: { 8532 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8533 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8534 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8535 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8536 return SDValue(N, 0); 8537 8538 return combineGREVI_GORCI(N, DAG); 8539 } 8540 case RISCVISD::GREVW: 8541 case RISCVISD::GORCW: { 8542 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8543 if (SimplifyDemandedLowBitsHelper(0, 32) || 8544 SimplifyDemandedLowBitsHelper(1, 5)) 8545 return SDValue(N, 0); 8546 8547 break; 8548 } 8549 case RISCVISD::SHFL: 8550 case RISCVISD::UNSHFL: { 8551 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8552 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8553 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8554 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8555 return SDValue(N, 0); 8556 8557 break; 8558 } 8559 case RISCVISD::SHFLW: 8560 case RISCVISD::UNSHFLW: { 8561 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8562 if (SimplifyDemandedLowBitsHelper(0, 32) || 8563 SimplifyDemandedLowBitsHelper(1, 4)) 8564 return SDValue(N, 0); 8565 8566 break; 8567 } 8568 case RISCVISD::BCOMPRESSW: 8569 case RISCVISD::BDECOMPRESSW: { 8570 // Only the lower 32 bits of LHS and RHS are read. 8571 if (SimplifyDemandedLowBitsHelper(0, 32) || 8572 SimplifyDemandedLowBitsHelper(1, 32)) 8573 return SDValue(N, 0); 8574 8575 break; 8576 } 8577 case RISCVISD::FSR: 8578 case RISCVISD::FSL: 8579 case RISCVISD::FSRW: 8580 case RISCVISD::FSLW: { 8581 bool IsWInstruction = 8582 N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW; 8583 unsigned BitWidth = 8584 IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits(); 8585 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8586 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 8587 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1)) 8588 return SDValue(N, 0); 8589 8590 break; 8591 } 8592 case RISCVISD::FMV_X_ANYEXTH: 8593 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8594 SDLoc DL(N); 8595 SDValue Op0 = N->getOperand(0); 8596 MVT VT = N->getSimpleValueType(0); 8597 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8598 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8599 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8600 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8601 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8602 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8603 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8604 assert(Op0.getOperand(0).getValueType() == VT && 8605 "Unexpected value type!"); 8606 return Op0.getOperand(0); 8607 } 8608 8609 // This is a target-specific version of a DAGCombine performed in 8610 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8611 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8612 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8613 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8614 !Op0.getNode()->hasOneUse()) 8615 break; 8616 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8617 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8618 APInt SignBit = APInt::getSignMask(FPBits).sext(VT.getSizeInBits()); 8619 if (Op0.getOpcode() == ISD::FNEG) 8620 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8621 DAG.getConstant(SignBit, DL, VT)); 8622 8623 assert(Op0.getOpcode() == ISD::FABS); 8624 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8625 DAG.getConstant(~SignBit, DL, VT)); 8626 } 8627 case ISD::ADD: 8628 return performADDCombine(N, DAG, Subtarget); 8629 case ISD::SUB: 8630 return performSUBCombine(N, DAG); 8631 case ISD::AND: 8632 return performANDCombine(N, DAG, Subtarget); 8633 case ISD::OR: 8634 return performORCombine(N, DAG, Subtarget); 8635 case ISD::XOR: 8636 return performXORCombine(N, DAG); 8637 case ISD::FADD: 8638 case ISD::UMAX: 8639 case ISD::UMIN: 8640 case ISD::SMAX: 8641 case ISD::SMIN: 8642 case ISD::FMAXNUM: 8643 case ISD::FMINNUM: 8644 return combineBinOpToReduce(N, DAG); 8645 case ISD::SIGN_EXTEND_INREG: 8646 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 8647 case ISD::ZERO_EXTEND: 8648 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8649 // type legalization. This is safe because fp_to_uint produces poison if 8650 // it overflows. 8651 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8652 SDValue Src = N->getOperand(0); 8653 if (Src.getOpcode() == ISD::FP_TO_UINT && 8654 isTypeLegal(Src.getOperand(0).getValueType())) 8655 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8656 Src.getOperand(0)); 8657 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8658 isTypeLegal(Src.getOperand(1).getValueType())) { 8659 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8660 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8661 Src.getOperand(0), Src.getOperand(1)); 8662 DCI.CombineTo(N, Res); 8663 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8664 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8665 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8666 } 8667 } 8668 return SDValue(); 8669 case RISCVISD::SELECT_CC: { 8670 // Transform 8671 SDValue LHS = N->getOperand(0); 8672 SDValue RHS = N->getOperand(1); 8673 SDValue TrueV = N->getOperand(3); 8674 SDValue FalseV = N->getOperand(4); 8675 8676 // If the True and False values are the same, we don't need a select_cc. 8677 if (TrueV == FalseV) 8678 return TrueV; 8679 8680 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8681 if (!ISD::isIntEqualitySetCC(CCVal)) 8682 break; 8683 8684 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8685 // (select_cc X, Y, lt, trueV, falseV) 8686 // Sometimes the setcc is introduced after select_cc has been formed. 8687 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8688 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8689 // If we're looking for eq 0 instead of ne 0, we need to invert the 8690 // condition. 8691 bool Invert = CCVal == ISD::SETEQ; 8692 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8693 if (Invert) 8694 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8695 8696 SDLoc DL(N); 8697 RHS = LHS.getOperand(1); 8698 LHS = LHS.getOperand(0); 8699 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8700 8701 SDValue TargetCC = DAG.getCondCode(CCVal); 8702 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8703 {LHS, RHS, TargetCC, TrueV, FalseV}); 8704 } 8705 8706 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8707 // (select_cc X, Y, eq/ne, trueV, falseV) 8708 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8709 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8710 {LHS.getOperand(0), LHS.getOperand(1), 8711 N->getOperand(2), TrueV, FalseV}); 8712 // (select_cc X, 1, setne, trueV, falseV) -> 8713 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8714 // This can occur when legalizing some floating point comparisons. 8715 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8716 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8717 SDLoc DL(N); 8718 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8719 SDValue TargetCC = DAG.getCondCode(CCVal); 8720 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8721 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8722 {LHS, RHS, TargetCC, TrueV, FalseV}); 8723 } 8724 8725 break; 8726 } 8727 case RISCVISD::BR_CC: { 8728 SDValue LHS = N->getOperand(1); 8729 SDValue RHS = N->getOperand(2); 8730 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8731 if (!ISD::isIntEqualitySetCC(CCVal)) 8732 break; 8733 8734 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8735 // (br_cc X, Y, lt, dest) 8736 // Sometimes the setcc is introduced after br_cc has been formed. 8737 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8738 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8739 // If we're looking for eq 0 instead of ne 0, we need to invert the 8740 // condition. 8741 bool Invert = CCVal == ISD::SETEQ; 8742 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8743 if (Invert) 8744 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8745 8746 SDLoc DL(N); 8747 RHS = LHS.getOperand(1); 8748 LHS = LHS.getOperand(0); 8749 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8750 8751 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8752 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8753 N->getOperand(4)); 8754 } 8755 8756 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8757 // (br_cc X, Y, eq/ne, trueV, falseV) 8758 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8759 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8760 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8761 N->getOperand(3), N->getOperand(4)); 8762 8763 // (br_cc X, 1, setne, br_cc) -> 8764 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8765 // This can occur when legalizing some floating point comparisons. 8766 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8767 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8768 SDLoc DL(N); 8769 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8770 SDValue TargetCC = DAG.getCondCode(CCVal); 8771 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8772 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8773 N->getOperand(0), LHS, RHS, TargetCC, 8774 N->getOperand(4)); 8775 } 8776 break; 8777 } 8778 case ISD::BITREVERSE: 8779 return performBITREVERSECombine(N, DAG, Subtarget); 8780 case ISD::FP_TO_SINT: 8781 case ISD::FP_TO_UINT: 8782 return performFP_TO_INTCombine(N, DCI, Subtarget); 8783 case ISD::FP_TO_SINT_SAT: 8784 case ISD::FP_TO_UINT_SAT: 8785 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8786 case ISD::FCOPYSIGN: { 8787 EVT VT = N->getValueType(0); 8788 if (!VT.isVector()) 8789 break; 8790 // There is a form of VFSGNJ which injects the negated sign of its second 8791 // operand. Try and bubble any FNEG up after the extend/round to produce 8792 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8793 // TRUNC=1. 8794 SDValue In2 = N->getOperand(1); 8795 // Avoid cases where the extend/round has multiple uses, as duplicating 8796 // those is typically more expensive than removing a fneg. 8797 if (!In2.hasOneUse()) 8798 break; 8799 if (In2.getOpcode() != ISD::FP_EXTEND && 8800 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8801 break; 8802 In2 = In2.getOperand(0); 8803 if (In2.getOpcode() != ISD::FNEG) 8804 break; 8805 SDLoc DL(N); 8806 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8807 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8808 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8809 } 8810 case ISD::MGATHER: 8811 case ISD::MSCATTER: 8812 case ISD::VP_GATHER: 8813 case ISD::VP_SCATTER: { 8814 if (!DCI.isBeforeLegalize()) 8815 break; 8816 SDValue Index, ScaleOp; 8817 bool IsIndexScaled = false; 8818 bool IsIndexSigned = false; 8819 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8820 Index = VPGSN->getIndex(); 8821 ScaleOp = VPGSN->getScale(); 8822 IsIndexScaled = VPGSN->isIndexScaled(); 8823 IsIndexSigned = VPGSN->isIndexSigned(); 8824 } else { 8825 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 8826 Index = MGSN->getIndex(); 8827 ScaleOp = MGSN->getScale(); 8828 IsIndexScaled = MGSN->isIndexScaled(); 8829 IsIndexSigned = MGSN->isIndexSigned(); 8830 } 8831 EVT IndexVT = Index.getValueType(); 8832 MVT XLenVT = Subtarget.getXLenVT(); 8833 // RISCV indexed loads only support the "unsigned unscaled" addressing 8834 // mode, so anything else must be manually legalized. 8835 bool NeedsIdxLegalization = 8836 IsIndexScaled || 8837 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 8838 if (!NeedsIdxLegalization) 8839 break; 8840 8841 SDLoc DL(N); 8842 8843 // Any index legalization should first promote to XLenVT, so we don't lose 8844 // bits when scaling. This may create an illegal index type so we let 8845 // LLVM's legalization take care of the splitting. 8846 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 8847 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 8848 IndexVT = IndexVT.changeVectorElementType(XLenVT); 8849 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8850 DL, IndexVT, Index); 8851 } 8852 8853 if (IsIndexScaled) { 8854 // Manually scale the indices. 8855 // TODO: Sanitize the scale operand here? 8856 // TODO: For VP nodes, should we use VP_SHL here? 8857 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 8858 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 8859 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 8860 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 8861 ScaleOp = DAG.getTargetConstant(1, DL, ScaleOp.getValueType()); 8862 } 8863 8864 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_SCALED; 8865 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 8866 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 8867 {VPGN->getChain(), VPGN->getBasePtr(), Index, 8868 ScaleOp, VPGN->getMask(), 8869 VPGN->getVectorLength()}, 8870 VPGN->getMemOperand(), NewIndexTy); 8871 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 8872 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 8873 {VPSN->getChain(), VPSN->getValue(), 8874 VPSN->getBasePtr(), Index, ScaleOp, 8875 VPSN->getMask(), VPSN->getVectorLength()}, 8876 VPSN->getMemOperand(), NewIndexTy); 8877 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 8878 return DAG.getMaskedGather( 8879 N->getVTList(), MGN->getMemoryVT(), DL, 8880 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 8881 MGN->getBasePtr(), Index, ScaleOp}, 8882 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 8883 const auto *MSN = cast<MaskedScatterSDNode>(N); 8884 return DAG.getMaskedScatter( 8885 N->getVTList(), MSN->getMemoryVT(), DL, 8886 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 8887 Index, ScaleOp}, 8888 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 8889 } 8890 case RISCVISD::SRA_VL: 8891 case RISCVISD::SRL_VL: 8892 case RISCVISD::SHL_VL: { 8893 SDValue ShAmt = N->getOperand(1); 8894 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8895 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8896 SDLoc DL(N); 8897 SDValue VL = N->getOperand(3); 8898 EVT VT = N->getValueType(0); 8899 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8900 ShAmt.getOperand(1), VL); 8901 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8902 N->getOperand(2), N->getOperand(3)); 8903 } 8904 break; 8905 } 8906 case ISD::SRA: 8907 case ISD::SRL: 8908 case ISD::SHL: { 8909 SDValue ShAmt = N->getOperand(1); 8910 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8911 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8912 SDLoc DL(N); 8913 EVT VT = N->getValueType(0); 8914 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8915 ShAmt.getOperand(1), 8916 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 8917 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 8918 } 8919 break; 8920 } 8921 case RISCVISD::ADD_VL: 8922 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 8923 return V; 8924 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 8925 case RISCVISD::SUB_VL: 8926 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 8927 case RISCVISD::VWADD_W_VL: 8928 case RISCVISD::VWADDU_W_VL: 8929 case RISCVISD::VWSUB_W_VL: 8930 case RISCVISD::VWSUBU_W_VL: 8931 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 8932 case RISCVISD::MUL_VL: 8933 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 8934 return V; 8935 // Mul is commutative. 8936 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 8937 case ISD::STORE: { 8938 auto *Store = cast<StoreSDNode>(N); 8939 SDValue Val = Store->getValue(); 8940 // Combine store of vmv.x.s to vse with VL of 1. 8941 // FIXME: Support FP. 8942 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 8943 SDValue Src = Val.getOperand(0); 8944 EVT VecVT = Src.getValueType(); 8945 EVT MemVT = Store->getMemoryVT(); 8946 // The memory VT and the element type must match. 8947 if (VecVT.getVectorElementType() == MemVT) { 8948 SDLoc DL(N); 8949 MVT MaskVT = getMaskTypeFor(VecVT); 8950 return DAG.getStoreVP( 8951 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 8952 DAG.getConstant(1, DL, MaskVT), 8953 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 8954 Store->getMemOperand(), Store->getAddressingMode(), 8955 Store->isTruncatingStore(), /*IsCompress*/ false); 8956 } 8957 } 8958 8959 break; 8960 } 8961 case ISD::SPLAT_VECTOR: { 8962 EVT VT = N->getValueType(0); 8963 // Only perform this combine on legal MVT types. 8964 if (!isTypeLegal(VT)) 8965 break; 8966 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 8967 DAG, Subtarget)) 8968 return Gather; 8969 break; 8970 } 8971 case RISCVISD::VMV_V_X_VL: { 8972 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 8973 // scalar input. 8974 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 8975 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 8976 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 8977 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 8978 return SDValue(N, 0); 8979 8980 break; 8981 } 8982 case ISD::INTRINSIC_WO_CHAIN: { 8983 unsigned IntNo = N->getConstantOperandVal(0); 8984 switch (IntNo) { 8985 // By default we do not combine any intrinsic. 8986 default: 8987 return SDValue(); 8988 case Intrinsic::riscv_vcpop: 8989 case Intrinsic::riscv_vcpop_mask: 8990 case Intrinsic::riscv_vfirst: 8991 case Intrinsic::riscv_vfirst_mask: { 8992 SDValue VL = N->getOperand(2); 8993 if (IntNo == Intrinsic::riscv_vcpop_mask || 8994 IntNo == Intrinsic::riscv_vfirst_mask) 8995 VL = N->getOperand(3); 8996 if (!isNullConstant(VL)) 8997 return SDValue(); 8998 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 8999 SDLoc DL(N); 9000 EVT VT = N->getValueType(0); 9001 if (IntNo == Intrinsic::riscv_vfirst || 9002 IntNo == Intrinsic::riscv_vfirst_mask) 9003 return DAG.getConstant(-1, DL, VT); 9004 return DAG.getConstant(0, DL, VT); 9005 } 9006 } 9007 } 9008 } 9009 9010 return SDValue(); 9011 } 9012 9013 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 9014 const SDNode *N, CombineLevel Level) const { 9015 // The following folds are only desirable if `(OP _, c1 << c2)` can be 9016 // materialised in fewer instructions than `(OP _, c1)`: 9017 // 9018 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 9019 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 9020 SDValue N0 = N->getOperand(0); 9021 EVT Ty = N0.getValueType(); 9022 if (Ty.isScalarInteger() && 9023 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 9024 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 9025 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9026 if (C1 && C2) { 9027 const APInt &C1Int = C1->getAPIntValue(); 9028 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 9029 9030 // We can materialise `c1 << c2` into an add immediate, so it's "free", 9031 // and the combine should happen, to potentially allow further combines 9032 // later. 9033 if (ShiftedC1Int.getMinSignedBits() <= 64 && 9034 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 9035 return true; 9036 9037 // We can materialise `c1` in an add immediate, so it's "free", and the 9038 // combine should be prevented. 9039 if (C1Int.getMinSignedBits() <= 64 && 9040 isLegalAddImmediate(C1Int.getSExtValue())) 9041 return false; 9042 9043 // Neither constant will fit into an immediate, so find materialisation 9044 // costs. 9045 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 9046 Subtarget.getFeatureBits(), 9047 /*CompressionCost*/true); 9048 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 9049 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 9050 /*CompressionCost*/true); 9051 9052 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 9053 // combine should be prevented. 9054 if (C1Cost < ShiftedC1Cost) 9055 return false; 9056 } 9057 } 9058 return true; 9059 } 9060 9061 bool RISCVTargetLowering::targetShrinkDemandedConstant( 9062 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 9063 TargetLoweringOpt &TLO) const { 9064 // Delay this optimization as late as possible. 9065 if (!TLO.LegalOps) 9066 return false; 9067 9068 EVT VT = Op.getValueType(); 9069 if (VT.isVector()) 9070 return false; 9071 9072 // Only handle AND for now. 9073 if (Op.getOpcode() != ISD::AND) 9074 return false; 9075 9076 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 9077 if (!C) 9078 return false; 9079 9080 const APInt &Mask = C->getAPIntValue(); 9081 9082 // Clear all non-demanded bits initially. 9083 APInt ShrunkMask = Mask & DemandedBits; 9084 9085 // Try to make a smaller immediate by setting undemanded bits. 9086 9087 APInt ExpandedMask = Mask | ~DemandedBits; 9088 9089 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 9090 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 9091 }; 9092 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 9093 if (NewMask == Mask) 9094 return true; 9095 SDLoc DL(Op); 9096 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 9097 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 9098 return TLO.CombineTo(Op, NewOp); 9099 }; 9100 9101 // If the shrunk mask fits in sign extended 12 bits, let the target 9102 // independent code apply it. 9103 if (ShrunkMask.isSignedIntN(12)) 9104 return false; 9105 9106 // Preserve (and X, 0xffff) when zext.h is supported. 9107 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 9108 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 9109 if (IsLegalMask(NewMask)) 9110 return UseMask(NewMask); 9111 } 9112 9113 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 9114 if (VT == MVT::i64) { 9115 APInt NewMask = APInt(64, 0xffffffff); 9116 if (IsLegalMask(NewMask)) 9117 return UseMask(NewMask); 9118 } 9119 9120 // For the remaining optimizations, we need to be able to make a negative 9121 // number through a combination of mask and undemanded bits. 9122 if (!ExpandedMask.isNegative()) 9123 return false; 9124 9125 // What is the fewest number of bits we need to represent the negative number. 9126 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 9127 9128 // Try to make a 12 bit negative immediate. If that fails try to make a 32 9129 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 9130 APInt NewMask = ShrunkMask; 9131 if (MinSignedBits <= 12) 9132 NewMask.setBitsFrom(11); 9133 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 9134 NewMask.setBitsFrom(31); 9135 else 9136 return false; 9137 9138 // Check that our new mask is a subset of the demanded mask. 9139 assert(IsLegalMask(NewMask)); 9140 return UseMask(NewMask); 9141 } 9142 9143 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) { 9144 static const uint64_t GREVMasks[] = { 9145 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 9146 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 9147 9148 for (unsigned Stage = 0; Stage != 6; ++Stage) { 9149 unsigned Shift = 1 << Stage; 9150 if (ShAmt & Shift) { 9151 uint64_t Mask = GREVMasks[Stage]; 9152 uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask); 9153 if (IsGORC) 9154 Res |= x; 9155 x = Res; 9156 } 9157 } 9158 9159 return x; 9160 } 9161 9162 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 9163 KnownBits &Known, 9164 const APInt &DemandedElts, 9165 const SelectionDAG &DAG, 9166 unsigned Depth) const { 9167 unsigned BitWidth = Known.getBitWidth(); 9168 unsigned Opc = Op.getOpcode(); 9169 assert((Opc >= ISD::BUILTIN_OP_END || 9170 Opc == ISD::INTRINSIC_WO_CHAIN || 9171 Opc == ISD::INTRINSIC_W_CHAIN || 9172 Opc == ISD::INTRINSIC_VOID) && 9173 "Should use MaskedValueIsZero if you don't know whether Op" 9174 " is a target node!"); 9175 9176 Known.resetAll(); 9177 switch (Opc) { 9178 default: break; 9179 case RISCVISD::SELECT_CC: { 9180 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 9181 // If we don't know any bits, early out. 9182 if (Known.isUnknown()) 9183 break; 9184 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 9185 9186 // Only known if known in both the LHS and RHS. 9187 Known = KnownBits::commonBits(Known, Known2); 9188 break; 9189 } 9190 case RISCVISD::REMUW: { 9191 KnownBits Known2; 9192 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9193 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9194 // We only care about the lower 32 bits. 9195 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 9196 // Restore the original width by sign extending. 9197 Known = Known.sext(BitWidth); 9198 break; 9199 } 9200 case RISCVISD::DIVUW: { 9201 KnownBits Known2; 9202 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9203 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9204 // We only care about the lower 32 bits. 9205 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 9206 // Restore the original width by sign extending. 9207 Known = Known.sext(BitWidth); 9208 break; 9209 } 9210 case RISCVISD::CTZW: { 9211 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9212 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 9213 unsigned LowBits = Log2_32(PossibleTZ) + 1; 9214 Known.Zero.setBitsFrom(LowBits); 9215 break; 9216 } 9217 case RISCVISD::CLZW: { 9218 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9219 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 9220 unsigned LowBits = Log2_32(PossibleLZ) + 1; 9221 Known.Zero.setBitsFrom(LowBits); 9222 break; 9223 } 9224 case RISCVISD::GREV: 9225 case RISCVISD::GORC: { 9226 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 9227 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9228 unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1); 9229 bool IsGORC = Op.getOpcode() == RISCVISD::GORC; 9230 // To compute zeros, we need to invert the value and invert it back after. 9231 Known.Zero = 9232 ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC); 9233 Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC); 9234 } 9235 break; 9236 } 9237 case RISCVISD::READ_VLENB: { 9238 // If we know the minimum VLen from Zvl extensions, we can use that to 9239 // determine the trailing zeros of VLENB. 9240 // FIXME: Limit to 128 bit vectors until we have more testing. 9241 unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8; 9242 if (MinVLenB > 0) 9243 Known.Zero.setLowBits(Log2_32(MinVLenB)); 9244 // We assume VLENB is no more than 65536 / 8 bytes. 9245 Known.Zero.setBitsFrom(14); 9246 break; 9247 } 9248 case ISD::INTRINSIC_W_CHAIN: 9249 case ISD::INTRINSIC_WO_CHAIN: { 9250 unsigned IntNo = 9251 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 9252 switch (IntNo) { 9253 default: 9254 // We can't do anything for most intrinsics. 9255 break; 9256 case Intrinsic::riscv_vsetvli: 9257 case Intrinsic::riscv_vsetvlimax: 9258 case Intrinsic::riscv_vsetvli_opt: 9259 case Intrinsic::riscv_vsetvlimax_opt: 9260 // Assume that VL output is positive and would fit in an int32_t. 9261 // TODO: VLEN might be capped at 16 bits in a future V spec update. 9262 if (BitWidth >= 32) 9263 Known.Zero.setBitsFrom(31); 9264 break; 9265 } 9266 break; 9267 } 9268 } 9269 } 9270 9271 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 9272 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 9273 unsigned Depth) const { 9274 switch (Op.getOpcode()) { 9275 default: 9276 break; 9277 case RISCVISD::SELECT_CC: { 9278 unsigned Tmp = 9279 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 9280 if (Tmp == 1) return 1; // Early out. 9281 unsigned Tmp2 = 9282 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 9283 return std::min(Tmp, Tmp2); 9284 } 9285 case RISCVISD::SLLW: 9286 case RISCVISD::SRAW: 9287 case RISCVISD::SRLW: 9288 case RISCVISD::DIVW: 9289 case RISCVISD::DIVUW: 9290 case RISCVISD::REMUW: 9291 case RISCVISD::ROLW: 9292 case RISCVISD::RORW: 9293 case RISCVISD::GREVW: 9294 case RISCVISD::GORCW: 9295 case RISCVISD::FSLW: 9296 case RISCVISD::FSRW: 9297 case RISCVISD::SHFLW: 9298 case RISCVISD::UNSHFLW: 9299 case RISCVISD::BCOMPRESSW: 9300 case RISCVISD::BDECOMPRESSW: 9301 case RISCVISD::BFPW: 9302 case RISCVISD::FCVT_W_RV64: 9303 case RISCVISD::FCVT_WU_RV64: 9304 case RISCVISD::STRICT_FCVT_W_RV64: 9305 case RISCVISD::STRICT_FCVT_WU_RV64: 9306 // TODO: As the result is sign-extended, this is conservatively correct. A 9307 // more precise answer could be calculated for SRAW depending on known 9308 // bits in the shift amount. 9309 return 33; 9310 case RISCVISD::SHFL: 9311 case RISCVISD::UNSHFL: { 9312 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 9313 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 9314 // will stay within the upper 32 bits. If there were more than 32 sign bits 9315 // before there will be at least 33 sign bits after. 9316 if (Op.getValueType() == MVT::i64 && 9317 isa<ConstantSDNode>(Op.getOperand(1)) && 9318 (Op.getConstantOperandVal(1) & 0x10) == 0) { 9319 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 9320 if (Tmp > 32) 9321 return 33; 9322 } 9323 break; 9324 } 9325 case RISCVISD::VMV_X_S: { 9326 // The number of sign bits of the scalar result is computed by obtaining the 9327 // element type of the input vector operand, subtracting its width from the 9328 // XLEN, and then adding one (sign bit within the element type). If the 9329 // element type is wider than XLen, the least-significant XLEN bits are 9330 // taken. 9331 unsigned XLen = Subtarget.getXLen(); 9332 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 9333 if (EltBits <= XLen) 9334 return XLen - EltBits + 1; 9335 break; 9336 } 9337 } 9338 9339 return 1; 9340 } 9341 9342 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 9343 MachineBasicBlock *BB) { 9344 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 9345 9346 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 9347 // Should the count have wrapped while it was being read, we need to try 9348 // again. 9349 // ... 9350 // read: 9351 // rdcycleh x3 # load high word of cycle 9352 // rdcycle x2 # load low word of cycle 9353 // rdcycleh x4 # load high word of cycle 9354 // bne x3, x4, read # check if high word reads match, otherwise try again 9355 // ... 9356 9357 MachineFunction &MF = *BB->getParent(); 9358 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9359 MachineFunction::iterator It = ++BB->getIterator(); 9360 9361 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9362 MF.insert(It, LoopMBB); 9363 9364 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9365 MF.insert(It, DoneMBB); 9366 9367 // Transfer the remainder of BB and its successor edges to DoneMBB. 9368 DoneMBB->splice(DoneMBB->begin(), BB, 9369 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9370 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 9371 9372 BB->addSuccessor(LoopMBB); 9373 9374 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9375 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9376 Register LoReg = MI.getOperand(0).getReg(); 9377 Register HiReg = MI.getOperand(1).getReg(); 9378 DebugLoc DL = MI.getDebugLoc(); 9379 9380 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 9381 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 9382 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9383 .addReg(RISCV::X0); 9384 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 9385 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 9386 .addReg(RISCV::X0); 9387 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 9388 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9389 .addReg(RISCV::X0); 9390 9391 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 9392 .addReg(HiReg) 9393 .addReg(ReadAgainReg) 9394 .addMBB(LoopMBB); 9395 9396 LoopMBB->addSuccessor(LoopMBB); 9397 LoopMBB->addSuccessor(DoneMBB); 9398 9399 MI.eraseFromParent(); 9400 9401 return DoneMBB; 9402 } 9403 9404 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9405 MachineBasicBlock *BB) { 9406 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9407 9408 MachineFunction &MF = *BB->getParent(); 9409 DebugLoc DL = MI.getDebugLoc(); 9410 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9411 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9412 Register LoReg = MI.getOperand(0).getReg(); 9413 Register HiReg = MI.getOperand(1).getReg(); 9414 Register SrcReg = MI.getOperand(2).getReg(); 9415 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9416 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9417 9418 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9419 RI); 9420 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9421 MachineMemOperand *MMOLo = 9422 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9423 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9424 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9425 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9426 .addFrameIndex(FI) 9427 .addImm(0) 9428 .addMemOperand(MMOLo); 9429 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9430 .addFrameIndex(FI) 9431 .addImm(4) 9432 .addMemOperand(MMOHi); 9433 MI.eraseFromParent(); // The pseudo instruction is gone now. 9434 return BB; 9435 } 9436 9437 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9438 MachineBasicBlock *BB) { 9439 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9440 "Unexpected instruction"); 9441 9442 MachineFunction &MF = *BB->getParent(); 9443 DebugLoc DL = MI.getDebugLoc(); 9444 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9445 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9446 Register DstReg = MI.getOperand(0).getReg(); 9447 Register LoReg = MI.getOperand(1).getReg(); 9448 Register HiReg = MI.getOperand(2).getReg(); 9449 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9450 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9451 9452 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9453 MachineMemOperand *MMOLo = 9454 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9455 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9456 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9457 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9458 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9459 .addFrameIndex(FI) 9460 .addImm(0) 9461 .addMemOperand(MMOLo); 9462 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9463 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9464 .addFrameIndex(FI) 9465 .addImm(4) 9466 .addMemOperand(MMOHi); 9467 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9468 MI.eraseFromParent(); // The pseudo instruction is gone now. 9469 return BB; 9470 } 9471 9472 static bool isSelectPseudo(MachineInstr &MI) { 9473 switch (MI.getOpcode()) { 9474 default: 9475 return false; 9476 case RISCV::Select_GPR_Using_CC_GPR: 9477 case RISCV::Select_FPR16_Using_CC_GPR: 9478 case RISCV::Select_FPR32_Using_CC_GPR: 9479 case RISCV::Select_FPR64_Using_CC_GPR: 9480 return true; 9481 } 9482 } 9483 9484 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9485 unsigned RelOpcode, unsigned EqOpcode, 9486 const RISCVSubtarget &Subtarget) { 9487 DebugLoc DL = MI.getDebugLoc(); 9488 Register DstReg = MI.getOperand(0).getReg(); 9489 Register Src1Reg = MI.getOperand(1).getReg(); 9490 Register Src2Reg = MI.getOperand(2).getReg(); 9491 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9492 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9493 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9494 9495 // Save the current FFLAGS. 9496 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9497 9498 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9499 .addReg(Src1Reg) 9500 .addReg(Src2Reg); 9501 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9502 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9503 9504 // Restore the FFLAGS. 9505 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9506 .addReg(SavedFFlags, RegState::Kill); 9507 9508 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9509 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9510 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9511 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9512 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9513 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9514 9515 // Erase the pseudoinstruction. 9516 MI.eraseFromParent(); 9517 return BB; 9518 } 9519 9520 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9521 MachineBasicBlock *BB, 9522 const RISCVSubtarget &Subtarget) { 9523 // To "insert" Select_* instructions, we actually have to insert the triangle 9524 // control-flow pattern. The incoming instructions know the destination vreg 9525 // to set, the condition code register to branch on, the true/false values to 9526 // select between, and the condcode to use to select the appropriate branch. 9527 // 9528 // We produce the following control flow: 9529 // HeadMBB 9530 // | \ 9531 // | IfFalseMBB 9532 // | / 9533 // TailMBB 9534 // 9535 // When we find a sequence of selects we attempt to optimize their emission 9536 // by sharing the control flow. Currently we only handle cases where we have 9537 // multiple selects with the exact same condition (same LHS, RHS and CC). 9538 // The selects may be interleaved with other instructions if the other 9539 // instructions meet some requirements we deem safe: 9540 // - They are debug instructions. Otherwise, 9541 // - They do not have side-effects, do not access memory and their inputs do 9542 // not depend on the results of the select pseudo-instructions. 9543 // The TrueV/FalseV operands of the selects cannot depend on the result of 9544 // previous selects in the sequence. 9545 // These conditions could be further relaxed. See the X86 target for a 9546 // related approach and more information. 9547 Register LHS = MI.getOperand(1).getReg(); 9548 Register RHS = MI.getOperand(2).getReg(); 9549 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9550 9551 SmallVector<MachineInstr *, 4> SelectDebugValues; 9552 SmallSet<Register, 4> SelectDests; 9553 SelectDests.insert(MI.getOperand(0).getReg()); 9554 9555 MachineInstr *LastSelectPseudo = &MI; 9556 9557 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9558 SequenceMBBI != E; ++SequenceMBBI) { 9559 if (SequenceMBBI->isDebugInstr()) 9560 continue; 9561 if (isSelectPseudo(*SequenceMBBI)) { 9562 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9563 SequenceMBBI->getOperand(2).getReg() != RHS || 9564 SequenceMBBI->getOperand(3).getImm() != CC || 9565 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9566 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9567 break; 9568 LastSelectPseudo = &*SequenceMBBI; 9569 SequenceMBBI->collectDebugValues(SelectDebugValues); 9570 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9571 } else { 9572 if (SequenceMBBI->hasUnmodeledSideEffects() || 9573 SequenceMBBI->mayLoadOrStore()) 9574 break; 9575 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9576 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9577 })) 9578 break; 9579 } 9580 } 9581 9582 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9583 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9584 DebugLoc DL = MI.getDebugLoc(); 9585 MachineFunction::iterator I = ++BB->getIterator(); 9586 9587 MachineBasicBlock *HeadMBB = BB; 9588 MachineFunction *F = BB->getParent(); 9589 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9590 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9591 9592 F->insert(I, IfFalseMBB); 9593 F->insert(I, TailMBB); 9594 9595 // Transfer debug instructions associated with the selects to TailMBB. 9596 for (MachineInstr *DebugInstr : SelectDebugValues) { 9597 TailMBB->push_back(DebugInstr->removeFromParent()); 9598 } 9599 9600 // Move all instructions after the sequence to TailMBB. 9601 TailMBB->splice(TailMBB->end(), HeadMBB, 9602 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9603 // Update machine-CFG edges by transferring all successors of the current 9604 // block to the new block which will contain the Phi nodes for the selects. 9605 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9606 // Set the successors for HeadMBB. 9607 HeadMBB->addSuccessor(IfFalseMBB); 9608 HeadMBB->addSuccessor(TailMBB); 9609 9610 // Insert appropriate branch. 9611 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9612 .addReg(LHS) 9613 .addReg(RHS) 9614 .addMBB(TailMBB); 9615 9616 // IfFalseMBB just falls through to TailMBB. 9617 IfFalseMBB->addSuccessor(TailMBB); 9618 9619 // Create PHIs for all of the select pseudo-instructions. 9620 auto SelectMBBI = MI.getIterator(); 9621 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9622 auto InsertionPoint = TailMBB->begin(); 9623 while (SelectMBBI != SelectEnd) { 9624 auto Next = std::next(SelectMBBI); 9625 if (isSelectPseudo(*SelectMBBI)) { 9626 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9627 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9628 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9629 .addReg(SelectMBBI->getOperand(4).getReg()) 9630 .addMBB(HeadMBB) 9631 .addReg(SelectMBBI->getOperand(5).getReg()) 9632 .addMBB(IfFalseMBB); 9633 SelectMBBI->eraseFromParent(); 9634 } 9635 SelectMBBI = Next; 9636 } 9637 9638 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9639 return TailMBB; 9640 } 9641 9642 MachineBasicBlock * 9643 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9644 MachineBasicBlock *BB) const { 9645 switch (MI.getOpcode()) { 9646 default: 9647 llvm_unreachable("Unexpected instr type to insert"); 9648 case RISCV::ReadCycleWide: 9649 assert(!Subtarget.is64Bit() && 9650 "ReadCycleWrite is only to be used on riscv32"); 9651 return emitReadCycleWidePseudo(MI, BB); 9652 case RISCV::Select_GPR_Using_CC_GPR: 9653 case RISCV::Select_FPR16_Using_CC_GPR: 9654 case RISCV::Select_FPR32_Using_CC_GPR: 9655 case RISCV::Select_FPR64_Using_CC_GPR: 9656 return emitSelectPseudo(MI, BB, Subtarget); 9657 case RISCV::BuildPairF64Pseudo: 9658 return emitBuildPairF64Pseudo(MI, BB); 9659 case RISCV::SplitF64Pseudo: 9660 return emitSplitF64Pseudo(MI, BB); 9661 case RISCV::PseudoQuietFLE_H: 9662 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9663 case RISCV::PseudoQuietFLT_H: 9664 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9665 case RISCV::PseudoQuietFLE_S: 9666 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9667 case RISCV::PseudoQuietFLT_S: 9668 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9669 case RISCV::PseudoQuietFLE_D: 9670 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9671 case RISCV::PseudoQuietFLT_D: 9672 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9673 } 9674 } 9675 9676 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9677 SDNode *Node) const { 9678 // Add FRM dependency to any instructions with dynamic rounding mode. 9679 unsigned Opc = MI.getOpcode(); 9680 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9681 if (Idx < 0) 9682 return; 9683 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9684 return; 9685 // If the instruction already reads FRM, don't add another read. 9686 if (MI.readsRegister(RISCV::FRM)) 9687 return; 9688 MI.addOperand( 9689 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9690 } 9691 9692 // Calling Convention Implementation. 9693 // The expectations for frontend ABI lowering vary from target to target. 9694 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 9695 // details, but this is a longer term goal. For now, we simply try to keep the 9696 // role of the frontend as simple and well-defined as possible. The rules can 9697 // be summarised as: 9698 // * Never split up large scalar arguments. We handle them here. 9699 // * If a hardfloat calling convention is being used, and the struct may be 9700 // passed in a pair of registers (fp+fp, int+fp), and both registers are 9701 // available, then pass as two separate arguments. If either the GPRs or FPRs 9702 // are exhausted, then pass according to the rule below. 9703 // * If a struct could never be passed in registers or directly in a stack 9704 // slot (as it is larger than 2*XLEN and the floating point rules don't 9705 // apply), then pass it using a pointer with the byval attribute. 9706 // * If a struct is less than 2*XLEN, then coerce to either a two-element 9707 // word-sized array or a 2*XLEN scalar (depending on alignment). 9708 // * The frontend can determine whether a struct is returned by reference or 9709 // not based on its size and fields. If it will be returned by reference, the 9710 // frontend must modify the prototype so a pointer with the sret annotation is 9711 // passed as the first argument. This is not necessary for large scalar 9712 // returns. 9713 // * Struct return values and varargs should be coerced to structs containing 9714 // register-size fields in the same situations they would be for fixed 9715 // arguments. 9716 9717 static const MCPhysReg ArgGPRs[] = { 9718 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 9719 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 9720 }; 9721 static const MCPhysReg ArgFPR16s[] = { 9722 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 9723 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 9724 }; 9725 static const MCPhysReg ArgFPR32s[] = { 9726 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 9727 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 9728 }; 9729 static const MCPhysReg ArgFPR64s[] = { 9730 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 9731 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 9732 }; 9733 // This is an interim calling convention and it may be changed in the future. 9734 static const MCPhysReg ArgVRs[] = { 9735 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 9736 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 9737 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 9738 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 9739 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 9740 RISCV::V20M2, RISCV::V22M2}; 9741 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 9742 RISCV::V20M4}; 9743 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 9744 9745 // Pass a 2*XLEN argument that has been split into two XLEN values through 9746 // registers or the stack as necessary. 9747 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 9748 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 9749 MVT ValVT2, MVT LocVT2, 9750 ISD::ArgFlagsTy ArgFlags2) { 9751 unsigned XLenInBytes = XLen / 8; 9752 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9753 // At least one half can be passed via register. 9754 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 9755 VA1.getLocVT(), CCValAssign::Full)); 9756 } else { 9757 // Both halves must be passed on the stack, with proper alignment. 9758 Align StackAlign = 9759 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 9760 State.addLoc( 9761 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 9762 State.AllocateStack(XLenInBytes, StackAlign), 9763 VA1.getLocVT(), CCValAssign::Full)); 9764 State.addLoc(CCValAssign::getMem( 9765 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9766 LocVT2, CCValAssign::Full)); 9767 return false; 9768 } 9769 9770 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9771 // The second half can also be passed via register. 9772 State.addLoc( 9773 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 9774 } else { 9775 // The second half is passed via the stack, without additional alignment. 9776 State.addLoc(CCValAssign::getMem( 9777 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9778 LocVT2, CCValAssign::Full)); 9779 } 9780 9781 return false; 9782 } 9783 9784 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 9785 Optional<unsigned> FirstMaskArgument, 9786 CCState &State, const RISCVTargetLowering &TLI) { 9787 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 9788 if (RC == &RISCV::VRRegClass) { 9789 // Assign the first mask argument to V0. 9790 // This is an interim calling convention and it may be changed in the 9791 // future. 9792 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 9793 return State.AllocateReg(RISCV::V0); 9794 return State.AllocateReg(ArgVRs); 9795 } 9796 if (RC == &RISCV::VRM2RegClass) 9797 return State.AllocateReg(ArgVRM2s); 9798 if (RC == &RISCV::VRM4RegClass) 9799 return State.AllocateReg(ArgVRM4s); 9800 if (RC == &RISCV::VRM8RegClass) 9801 return State.AllocateReg(ArgVRM8s); 9802 llvm_unreachable("Unhandled register class for ValueType"); 9803 } 9804 9805 // Implements the RISC-V calling convention. Returns true upon failure. 9806 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 9807 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 9808 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 9809 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 9810 Optional<unsigned> FirstMaskArgument) { 9811 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 9812 assert(XLen == 32 || XLen == 64); 9813 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 9814 9815 // Any return value split in to more than two values can't be returned 9816 // directly. Vectors are returned via the available vector registers. 9817 if (!LocVT.isVector() && IsRet && ValNo > 1) 9818 return true; 9819 9820 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 9821 // variadic argument, or if no F16/F32 argument registers are available. 9822 bool UseGPRForF16_F32 = true; 9823 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 9824 // variadic argument, or if no F64 argument registers are available. 9825 bool UseGPRForF64 = true; 9826 9827 switch (ABI) { 9828 default: 9829 llvm_unreachable("Unexpected ABI"); 9830 case RISCVABI::ABI_ILP32: 9831 case RISCVABI::ABI_LP64: 9832 break; 9833 case RISCVABI::ABI_ILP32F: 9834 case RISCVABI::ABI_LP64F: 9835 UseGPRForF16_F32 = !IsFixed; 9836 break; 9837 case RISCVABI::ABI_ILP32D: 9838 case RISCVABI::ABI_LP64D: 9839 UseGPRForF16_F32 = !IsFixed; 9840 UseGPRForF64 = !IsFixed; 9841 break; 9842 } 9843 9844 // FPR16, FPR32, and FPR64 alias each other. 9845 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 9846 UseGPRForF16_F32 = true; 9847 UseGPRForF64 = true; 9848 } 9849 9850 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 9851 // similar local variables rather than directly checking against the target 9852 // ABI. 9853 9854 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 9855 LocVT = XLenVT; 9856 LocInfo = CCValAssign::BCvt; 9857 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 9858 LocVT = MVT::i64; 9859 LocInfo = CCValAssign::BCvt; 9860 } 9861 9862 // If this is a variadic argument, the RISC-V calling convention requires 9863 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 9864 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 9865 // be used regardless of whether the original argument was split during 9866 // legalisation or not. The argument will not be passed by registers if the 9867 // original type is larger than 2*XLEN, so the register alignment rule does 9868 // not apply. 9869 unsigned TwoXLenInBytes = (2 * XLen) / 8; 9870 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 9871 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 9872 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 9873 // Skip 'odd' register if necessary. 9874 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 9875 State.AllocateReg(ArgGPRs); 9876 } 9877 9878 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 9879 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 9880 State.getPendingArgFlags(); 9881 9882 assert(PendingLocs.size() == PendingArgFlags.size() && 9883 "PendingLocs and PendingArgFlags out of sync"); 9884 9885 // Handle passing f64 on RV32D with a soft float ABI or when floating point 9886 // registers are exhausted. 9887 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 9888 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 9889 "Can't lower f64 if it is split"); 9890 // Depending on available argument GPRS, f64 may be passed in a pair of 9891 // GPRs, split between a GPR and the stack, or passed completely on the 9892 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 9893 // cases. 9894 Register Reg = State.AllocateReg(ArgGPRs); 9895 LocVT = MVT::i32; 9896 if (!Reg) { 9897 unsigned StackOffset = State.AllocateStack(8, Align(8)); 9898 State.addLoc( 9899 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9900 return false; 9901 } 9902 if (!State.AllocateReg(ArgGPRs)) 9903 State.AllocateStack(4, Align(4)); 9904 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9905 return false; 9906 } 9907 9908 // Fixed-length vectors are located in the corresponding scalable-vector 9909 // container types. 9910 if (ValVT.isFixedLengthVector()) 9911 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9912 9913 // Split arguments might be passed indirectly, so keep track of the pending 9914 // values. Split vectors are passed via a mix of registers and indirectly, so 9915 // treat them as we would any other argument. 9916 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 9917 LocVT = XLenVT; 9918 LocInfo = CCValAssign::Indirect; 9919 PendingLocs.push_back( 9920 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 9921 PendingArgFlags.push_back(ArgFlags); 9922 if (!ArgFlags.isSplitEnd()) { 9923 return false; 9924 } 9925 } 9926 9927 // If the split argument only had two elements, it should be passed directly 9928 // in registers or on the stack. 9929 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 9930 PendingLocs.size() <= 2) { 9931 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 9932 // Apply the normal calling convention rules to the first half of the 9933 // split argument. 9934 CCValAssign VA = PendingLocs[0]; 9935 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 9936 PendingLocs.clear(); 9937 PendingArgFlags.clear(); 9938 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 9939 ArgFlags); 9940 } 9941 9942 // Allocate to a register if possible, or else a stack slot. 9943 Register Reg; 9944 unsigned StoreSizeBytes = XLen / 8; 9945 Align StackAlign = Align(XLen / 8); 9946 9947 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 9948 Reg = State.AllocateReg(ArgFPR16s); 9949 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 9950 Reg = State.AllocateReg(ArgFPR32s); 9951 else if (ValVT == MVT::f64 && !UseGPRForF64) 9952 Reg = State.AllocateReg(ArgFPR64s); 9953 else if (ValVT.isVector()) { 9954 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 9955 if (!Reg) { 9956 // For return values, the vector must be passed fully via registers or 9957 // via the stack. 9958 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 9959 // but we're using all of them. 9960 if (IsRet) 9961 return true; 9962 // Try using a GPR to pass the address 9963 if ((Reg = State.AllocateReg(ArgGPRs))) { 9964 LocVT = XLenVT; 9965 LocInfo = CCValAssign::Indirect; 9966 } else if (ValVT.isScalableVector()) { 9967 LocVT = XLenVT; 9968 LocInfo = CCValAssign::Indirect; 9969 } else { 9970 // Pass fixed-length vectors on the stack. 9971 LocVT = ValVT; 9972 StoreSizeBytes = ValVT.getStoreSize(); 9973 // Align vectors to their element sizes, being careful for vXi1 9974 // vectors. 9975 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9976 } 9977 } 9978 } else { 9979 Reg = State.AllocateReg(ArgGPRs); 9980 } 9981 9982 unsigned StackOffset = 9983 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 9984 9985 // If we reach this point and PendingLocs is non-empty, we must be at the 9986 // end of a split argument that must be passed indirectly. 9987 if (!PendingLocs.empty()) { 9988 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 9989 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 9990 9991 for (auto &It : PendingLocs) { 9992 if (Reg) 9993 It.convertToReg(Reg); 9994 else 9995 It.convertToMem(StackOffset); 9996 State.addLoc(It); 9997 } 9998 PendingLocs.clear(); 9999 PendingArgFlags.clear(); 10000 return false; 10001 } 10002 10003 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 10004 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 10005 "Expected an XLenVT or vector types at this stage"); 10006 10007 if (Reg) { 10008 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10009 return false; 10010 } 10011 10012 // When a floating-point value is passed on the stack, no bit-conversion is 10013 // needed. 10014 if (ValVT.isFloatingPoint()) { 10015 LocVT = ValVT; 10016 LocInfo = CCValAssign::Full; 10017 } 10018 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10019 return false; 10020 } 10021 10022 template <typename ArgTy> 10023 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 10024 for (const auto &ArgIdx : enumerate(Args)) { 10025 MVT ArgVT = ArgIdx.value().VT; 10026 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 10027 return ArgIdx.index(); 10028 } 10029 return None; 10030 } 10031 10032 void RISCVTargetLowering::analyzeInputArgs( 10033 MachineFunction &MF, CCState &CCInfo, 10034 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 10035 RISCVCCAssignFn Fn) const { 10036 unsigned NumArgs = Ins.size(); 10037 FunctionType *FType = MF.getFunction().getFunctionType(); 10038 10039 Optional<unsigned> FirstMaskArgument; 10040 if (Subtarget.hasVInstructions()) 10041 FirstMaskArgument = preAssignMask(Ins); 10042 10043 for (unsigned i = 0; i != NumArgs; ++i) { 10044 MVT ArgVT = Ins[i].VT; 10045 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 10046 10047 Type *ArgTy = nullptr; 10048 if (IsRet) 10049 ArgTy = FType->getReturnType(); 10050 else if (Ins[i].isOrigArg()) 10051 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 10052 10053 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10054 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10055 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 10056 FirstMaskArgument)) { 10057 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 10058 << EVT(ArgVT).getEVTString() << '\n'); 10059 llvm_unreachable(nullptr); 10060 } 10061 } 10062 } 10063 10064 void RISCVTargetLowering::analyzeOutputArgs( 10065 MachineFunction &MF, CCState &CCInfo, 10066 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 10067 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 10068 unsigned NumArgs = Outs.size(); 10069 10070 Optional<unsigned> FirstMaskArgument; 10071 if (Subtarget.hasVInstructions()) 10072 FirstMaskArgument = preAssignMask(Outs); 10073 10074 for (unsigned i = 0; i != NumArgs; i++) { 10075 MVT ArgVT = Outs[i].VT; 10076 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10077 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 10078 10079 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10080 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10081 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 10082 FirstMaskArgument)) { 10083 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 10084 << EVT(ArgVT).getEVTString() << "\n"); 10085 llvm_unreachable(nullptr); 10086 } 10087 } 10088 } 10089 10090 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 10091 // values. 10092 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 10093 const CCValAssign &VA, const SDLoc &DL, 10094 const RISCVSubtarget &Subtarget) { 10095 switch (VA.getLocInfo()) { 10096 default: 10097 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10098 case CCValAssign::Full: 10099 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 10100 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 10101 break; 10102 case CCValAssign::BCvt: 10103 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10104 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 10105 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10106 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 10107 else 10108 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 10109 break; 10110 } 10111 return Val; 10112 } 10113 10114 // The caller is responsible for loading the full value if the argument is 10115 // passed with CCValAssign::Indirect. 10116 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 10117 const CCValAssign &VA, const SDLoc &DL, 10118 const RISCVTargetLowering &TLI) { 10119 MachineFunction &MF = DAG.getMachineFunction(); 10120 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10121 EVT LocVT = VA.getLocVT(); 10122 SDValue Val; 10123 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 10124 Register VReg = RegInfo.createVirtualRegister(RC); 10125 RegInfo.addLiveIn(VA.getLocReg(), VReg); 10126 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 10127 10128 if (VA.getLocInfo() == CCValAssign::Indirect) 10129 return Val; 10130 10131 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 10132 } 10133 10134 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 10135 const CCValAssign &VA, const SDLoc &DL, 10136 const RISCVSubtarget &Subtarget) { 10137 EVT LocVT = VA.getLocVT(); 10138 10139 switch (VA.getLocInfo()) { 10140 default: 10141 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10142 case CCValAssign::Full: 10143 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 10144 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 10145 break; 10146 case CCValAssign::BCvt: 10147 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10148 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 10149 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10150 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 10151 else 10152 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 10153 break; 10154 } 10155 return Val; 10156 } 10157 10158 // The caller is responsible for loading the full value if the argument is 10159 // passed with CCValAssign::Indirect. 10160 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 10161 const CCValAssign &VA, const SDLoc &DL) { 10162 MachineFunction &MF = DAG.getMachineFunction(); 10163 MachineFrameInfo &MFI = MF.getFrameInfo(); 10164 EVT LocVT = VA.getLocVT(); 10165 EVT ValVT = VA.getValVT(); 10166 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 10167 if (ValVT.isScalableVector()) { 10168 // When the value is a scalable vector, we save the pointer which points to 10169 // the scalable vector value in the stack. The ValVT will be the pointer 10170 // type, instead of the scalable vector type. 10171 ValVT = LocVT; 10172 } 10173 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 10174 /*IsImmutable=*/true); 10175 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 10176 SDValue Val; 10177 10178 ISD::LoadExtType ExtType; 10179 switch (VA.getLocInfo()) { 10180 default: 10181 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10182 case CCValAssign::Full: 10183 case CCValAssign::Indirect: 10184 case CCValAssign::BCvt: 10185 ExtType = ISD::NON_EXTLOAD; 10186 break; 10187 } 10188 Val = DAG.getExtLoad( 10189 ExtType, DL, LocVT, Chain, FIN, 10190 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 10191 return Val; 10192 } 10193 10194 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 10195 const CCValAssign &VA, const SDLoc &DL) { 10196 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 10197 "Unexpected VA"); 10198 MachineFunction &MF = DAG.getMachineFunction(); 10199 MachineFrameInfo &MFI = MF.getFrameInfo(); 10200 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10201 10202 if (VA.isMemLoc()) { 10203 // f64 is passed on the stack. 10204 int FI = 10205 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 10206 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10207 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 10208 MachinePointerInfo::getFixedStack(MF, FI)); 10209 } 10210 10211 assert(VA.isRegLoc() && "Expected register VA assignment"); 10212 10213 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10214 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 10215 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 10216 SDValue Hi; 10217 if (VA.getLocReg() == RISCV::X17) { 10218 // Second half of f64 is passed on the stack. 10219 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 10220 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10221 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 10222 MachinePointerInfo::getFixedStack(MF, FI)); 10223 } else { 10224 // Second half of f64 is passed in another GPR. 10225 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10226 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 10227 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 10228 } 10229 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 10230 } 10231 10232 // FastCC has less than 1% performance improvement for some particular 10233 // benchmark. But theoretically, it may has benenfit for some cases. 10234 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 10235 unsigned ValNo, MVT ValVT, MVT LocVT, 10236 CCValAssign::LocInfo LocInfo, 10237 ISD::ArgFlagsTy ArgFlags, CCState &State, 10238 bool IsFixed, bool IsRet, Type *OrigTy, 10239 const RISCVTargetLowering &TLI, 10240 Optional<unsigned> FirstMaskArgument) { 10241 10242 // X5 and X6 might be used for save-restore libcall. 10243 static const MCPhysReg GPRList[] = { 10244 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 10245 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 10246 RISCV::X29, RISCV::X30, RISCV::X31}; 10247 10248 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10249 if (unsigned Reg = State.AllocateReg(GPRList)) { 10250 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10251 return false; 10252 } 10253 } 10254 10255 if (LocVT == MVT::f16) { 10256 static const MCPhysReg FPR16List[] = { 10257 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 10258 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 10259 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 10260 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 10261 if (unsigned Reg = State.AllocateReg(FPR16List)) { 10262 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10263 return false; 10264 } 10265 } 10266 10267 if (LocVT == MVT::f32) { 10268 static const MCPhysReg FPR32List[] = { 10269 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 10270 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 10271 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 10272 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 10273 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10274 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10275 return false; 10276 } 10277 } 10278 10279 if (LocVT == MVT::f64) { 10280 static const MCPhysReg FPR64List[] = { 10281 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 10282 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 10283 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 10284 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 10285 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10286 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10287 return false; 10288 } 10289 } 10290 10291 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 10292 unsigned Offset4 = State.AllocateStack(4, Align(4)); 10293 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 10294 return false; 10295 } 10296 10297 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 10298 unsigned Offset5 = State.AllocateStack(8, Align(8)); 10299 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 10300 return false; 10301 } 10302 10303 if (LocVT.isVector()) { 10304 if (unsigned Reg = 10305 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 10306 // Fixed-length vectors are located in the corresponding scalable-vector 10307 // container types. 10308 if (ValVT.isFixedLengthVector()) 10309 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10310 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10311 } else { 10312 // Try and pass the address via a "fast" GPR. 10313 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 10314 LocInfo = CCValAssign::Indirect; 10315 LocVT = TLI.getSubtarget().getXLenVT(); 10316 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 10317 } else if (ValVT.isFixedLengthVector()) { 10318 auto StackAlign = 10319 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10320 unsigned StackOffset = 10321 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 10322 State.addLoc( 10323 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10324 } else { 10325 // Can't pass scalable vectors on the stack. 10326 return true; 10327 } 10328 } 10329 10330 return false; 10331 } 10332 10333 return true; // CC didn't match. 10334 } 10335 10336 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 10337 CCValAssign::LocInfo LocInfo, 10338 ISD::ArgFlagsTy ArgFlags, CCState &State) { 10339 10340 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10341 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 10342 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 10343 static const MCPhysReg GPRList[] = { 10344 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 10345 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 10346 if (unsigned Reg = State.AllocateReg(GPRList)) { 10347 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10348 return false; 10349 } 10350 } 10351 10352 if (LocVT == MVT::f32) { 10353 // Pass in STG registers: F1, ..., F6 10354 // fs0 ... fs5 10355 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 10356 RISCV::F18_F, RISCV::F19_F, 10357 RISCV::F20_F, RISCV::F21_F}; 10358 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10359 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10360 return false; 10361 } 10362 } 10363 10364 if (LocVT == MVT::f64) { 10365 // Pass in STG registers: D1, ..., D6 10366 // fs6 ... fs11 10367 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 10368 RISCV::F24_D, RISCV::F25_D, 10369 RISCV::F26_D, RISCV::F27_D}; 10370 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10371 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10372 return false; 10373 } 10374 } 10375 10376 report_fatal_error("No registers left in GHC calling convention"); 10377 return true; 10378 } 10379 10380 // Transform physical registers into virtual registers. 10381 SDValue RISCVTargetLowering::LowerFormalArguments( 10382 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 10383 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 10384 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 10385 10386 MachineFunction &MF = DAG.getMachineFunction(); 10387 10388 switch (CallConv) { 10389 default: 10390 report_fatal_error("Unsupported calling convention"); 10391 case CallingConv::C: 10392 case CallingConv::Fast: 10393 break; 10394 case CallingConv::GHC: 10395 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10396 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10397 report_fatal_error( 10398 "GHC calling convention requires the F and D instruction set extensions"); 10399 } 10400 10401 const Function &Func = MF.getFunction(); 10402 if (Func.hasFnAttribute("interrupt")) { 10403 if (!Func.arg_empty()) 10404 report_fatal_error( 10405 "Functions with the interrupt attribute cannot have arguments!"); 10406 10407 StringRef Kind = 10408 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10409 10410 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10411 report_fatal_error( 10412 "Function interrupt attribute argument not supported!"); 10413 } 10414 10415 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10416 MVT XLenVT = Subtarget.getXLenVT(); 10417 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10418 // Used with vargs to acumulate store chains. 10419 std::vector<SDValue> OutChains; 10420 10421 // Assign locations to all of the incoming arguments. 10422 SmallVector<CCValAssign, 16> ArgLocs; 10423 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10424 10425 if (CallConv == CallingConv::GHC) 10426 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10427 else 10428 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10429 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10430 : CC_RISCV); 10431 10432 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10433 CCValAssign &VA = ArgLocs[i]; 10434 SDValue ArgValue; 10435 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10436 // case. 10437 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10438 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10439 else if (VA.isRegLoc()) 10440 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10441 else 10442 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10443 10444 if (VA.getLocInfo() == CCValAssign::Indirect) { 10445 // If the original argument was split and passed by reference (e.g. i128 10446 // on RV32), we need to load all parts of it here (using the same 10447 // address). Vectors may be partly split to registers and partly to the 10448 // stack, in which case the base address is partly offset and subsequent 10449 // stores are relative to that. 10450 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10451 MachinePointerInfo())); 10452 unsigned ArgIndex = Ins[i].OrigArgIndex; 10453 unsigned ArgPartOffset = Ins[i].PartOffset; 10454 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10455 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10456 CCValAssign &PartVA = ArgLocs[i + 1]; 10457 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10458 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10459 if (PartVA.getValVT().isScalableVector()) 10460 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10461 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10462 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10463 MachinePointerInfo())); 10464 ++i; 10465 } 10466 continue; 10467 } 10468 InVals.push_back(ArgValue); 10469 } 10470 10471 if (IsVarArg) { 10472 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10473 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10474 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10475 MachineFrameInfo &MFI = MF.getFrameInfo(); 10476 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10477 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10478 10479 // Offset of the first variable argument from stack pointer, and size of 10480 // the vararg save area. For now, the varargs save area is either zero or 10481 // large enough to hold a0-a7. 10482 int VaArgOffset, VarArgsSaveSize; 10483 10484 // If all registers are allocated, then all varargs must be passed on the 10485 // stack and we don't need to save any argregs. 10486 if (ArgRegs.size() == Idx) { 10487 VaArgOffset = CCInfo.getNextStackOffset(); 10488 VarArgsSaveSize = 0; 10489 } else { 10490 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10491 VaArgOffset = -VarArgsSaveSize; 10492 } 10493 10494 // Record the frame index of the first variable argument 10495 // which is a value necessary to VASTART. 10496 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10497 RVFI->setVarArgsFrameIndex(FI); 10498 10499 // If saving an odd number of registers then create an extra stack slot to 10500 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10501 // offsets to even-numbered registered remain 2*XLEN-aligned. 10502 if (Idx % 2) { 10503 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10504 VarArgsSaveSize += XLenInBytes; 10505 } 10506 10507 // Copy the integer registers that may have been used for passing varargs 10508 // to the vararg save area. 10509 for (unsigned I = Idx; I < ArgRegs.size(); 10510 ++I, VaArgOffset += XLenInBytes) { 10511 const Register Reg = RegInfo.createVirtualRegister(RC); 10512 RegInfo.addLiveIn(ArgRegs[I], Reg); 10513 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10514 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10515 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10516 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10517 MachinePointerInfo::getFixedStack(MF, FI)); 10518 cast<StoreSDNode>(Store.getNode()) 10519 ->getMemOperand() 10520 ->setValue((Value *)nullptr); 10521 OutChains.push_back(Store); 10522 } 10523 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10524 } 10525 10526 // All stores are grouped in one node to allow the matching between 10527 // the size of Ins and InVals. This only happens for vararg functions. 10528 if (!OutChains.empty()) { 10529 OutChains.push_back(Chain); 10530 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10531 } 10532 10533 return Chain; 10534 } 10535 10536 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10537 /// for tail call optimization. 10538 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10539 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10540 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10541 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10542 10543 auto &Callee = CLI.Callee; 10544 auto CalleeCC = CLI.CallConv; 10545 auto &Outs = CLI.Outs; 10546 auto &Caller = MF.getFunction(); 10547 auto CallerCC = Caller.getCallingConv(); 10548 10549 // Exception-handling functions need a special set of instructions to 10550 // indicate a return to the hardware. Tail-calling another function would 10551 // probably break this. 10552 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10553 // should be expanded as new function attributes are introduced. 10554 if (Caller.hasFnAttribute("interrupt")) 10555 return false; 10556 10557 // Do not tail call opt if the stack is used to pass parameters. 10558 if (CCInfo.getNextStackOffset() != 0) 10559 return false; 10560 10561 // Do not tail call opt if any parameters need to be passed indirectly. 10562 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10563 // passed indirectly. So the address of the value will be passed in a 10564 // register, or if not available, then the address is put on the stack. In 10565 // order to pass indirectly, space on the stack often needs to be allocated 10566 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10567 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10568 // are passed CCValAssign::Indirect. 10569 for (auto &VA : ArgLocs) 10570 if (VA.getLocInfo() == CCValAssign::Indirect) 10571 return false; 10572 10573 // Do not tail call opt if either caller or callee uses struct return 10574 // semantics. 10575 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10576 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10577 if (IsCallerStructRet || IsCalleeStructRet) 10578 return false; 10579 10580 // Externally-defined functions with weak linkage should not be 10581 // tail-called. The behaviour of branch instructions in this situation (as 10582 // used for tail calls) is implementation-defined, so we cannot rely on the 10583 // linker replacing the tail call with a return. 10584 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10585 const GlobalValue *GV = G->getGlobal(); 10586 if (GV->hasExternalWeakLinkage()) 10587 return false; 10588 } 10589 10590 // The callee has to preserve all registers the caller needs to preserve. 10591 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10592 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10593 if (CalleeCC != CallerCC) { 10594 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10595 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10596 return false; 10597 } 10598 10599 // Byval parameters hand the function a pointer directly into the stack area 10600 // we want to reuse during a tail call. Working around this *is* possible 10601 // but less efficient and uglier in LowerCall. 10602 for (auto &Arg : Outs) 10603 if (Arg.Flags.isByVal()) 10604 return false; 10605 10606 return true; 10607 } 10608 10609 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10610 return DAG.getDataLayout().getPrefTypeAlign( 10611 VT.getTypeForEVT(*DAG.getContext())); 10612 } 10613 10614 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10615 // and output parameter nodes. 10616 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10617 SmallVectorImpl<SDValue> &InVals) const { 10618 SelectionDAG &DAG = CLI.DAG; 10619 SDLoc &DL = CLI.DL; 10620 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10621 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10622 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10623 SDValue Chain = CLI.Chain; 10624 SDValue Callee = CLI.Callee; 10625 bool &IsTailCall = CLI.IsTailCall; 10626 CallingConv::ID CallConv = CLI.CallConv; 10627 bool IsVarArg = CLI.IsVarArg; 10628 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10629 MVT XLenVT = Subtarget.getXLenVT(); 10630 10631 MachineFunction &MF = DAG.getMachineFunction(); 10632 10633 // Analyze the operands of the call, assigning locations to each operand. 10634 SmallVector<CCValAssign, 16> ArgLocs; 10635 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10636 10637 if (CallConv == CallingConv::GHC) 10638 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10639 else 10640 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10641 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10642 : CC_RISCV); 10643 10644 // Check if it's really possible to do a tail call. 10645 if (IsTailCall) 10646 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10647 10648 if (IsTailCall) 10649 ++NumTailCalls; 10650 else if (CLI.CB && CLI.CB->isMustTailCall()) 10651 report_fatal_error("failed to perform tail call elimination on a call " 10652 "site marked musttail"); 10653 10654 // Get a count of how many bytes are to be pushed on the stack. 10655 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10656 10657 // Create local copies for byval args 10658 SmallVector<SDValue, 8> ByValArgs; 10659 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10660 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10661 if (!Flags.isByVal()) 10662 continue; 10663 10664 SDValue Arg = OutVals[i]; 10665 unsigned Size = Flags.getByValSize(); 10666 Align Alignment = Flags.getNonZeroByValAlign(); 10667 10668 int FI = 10669 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10670 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10671 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10672 10673 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10674 /*IsVolatile=*/false, 10675 /*AlwaysInline=*/false, IsTailCall, 10676 MachinePointerInfo(), MachinePointerInfo()); 10677 ByValArgs.push_back(FIPtr); 10678 } 10679 10680 if (!IsTailCall) 10681 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10682 10683 // Copy argument values to their designated locations. 10684 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10685 SmallVector<SDValue, 8> MemOpChains; 10686 SDValue StackPtr; 10687 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10688 CCValAssign &VA = ArgLocs[i]; 10689 SDValue ArgValue = OutVals[i]; 10690 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10691 10692 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10693 bool IsF64OnRV32DSoftABI = 10694 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 10695 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 10696 SDValue SplitF64 = DAG.getNode( 10697 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 10698 SDValue Lo = SplitF64.getValue(0); 10699 SDValue Hi = SplitF64.getValue(1); 10700 10701 Register RegLo = VA.getLocReg(); 10702 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 10703 10704 if (RegLo == RISCV::X17) { 10705 // Second half of f64 is passed on the stack. 10706 // Work out the address of the stack slot. 10707 if (!StackPtr.getNode()) 10708 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10709 // Emit the store. 10710 MemOpChains.push_back( 10711 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 10712 } else { 10713 // Second half of f64 is passed in another GPR. 10714 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10715 Register RegHigh = RegLo + 1; 10716 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 10717 } 10718 continue; 10719 } 10720 10721 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 10722 // as any other MemLoc. 10723 10724 // Promote the value if needed. 10725 // For now, only handle fully promoted and indirect arguments. 10726 if (VA.getLocInfo() == CCValAssign::Indirect) { 10727 // Store the argument in a stack slot and pass its address. 10728 Align StackAlign = 10729 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 10730 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 10731 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 10732 // If the original argument was split (e.g. i128), we need 10733 // to store the required parts of it here (and pass just one address). 10734 // Vectors may be partly split to registers and partly to the stack, in 10735 // which case the base address is partly offset and subsequent stores are 10736 // relative to that. 10737 unsigned ArgIndex = Outs[i].OrigArgIndex; 10738 unsigned ArgPartOffset = Outs[i].PartOffset; 10739 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10740 // Calculate the total size to store. We don't have access to what we're 10741 // actually storing other than performing the loop and collecting the 10742 // info. 10743 SmallVector<std::pair<SDValue, SDValue>> Parts; 10744 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 10745 SDValue PartValue = OutVals[i + 1]; 10746 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 10747 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10748 EVT PartVT = PartValue.getValueType(); 10749 if (PartVT.isScalableVector()) 10750 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10751 StoredSize += PartVT.getStoreSize(); 10752 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 10753 Parts.push_back(std::make_pair(PartValue, Offset)); 10754 ++i; 10755 } 10756 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 10757 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 10758 MemOpChains.push_back( 10759 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 10760 MachinePointerInfo::getFixedStack(MF, FI))); 10761 for (const auto &Part : Parts) { 10762 SDValue PartValue = Part.first; 10763 SDValue PartOffset = Part.second; 10764 SDValue Address = 10765 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 10766 MemOpChains.push_back( 10767 DAG.getStore(Chain, DL, PartValue, Address, 10768 MachinePointerInfo::getFixedStack(MF, FI))); 10769 } 10770 ArgValue = SpillSlot; 10771 } else { 10772 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 10773 } 10774 10775 // Use local copy if it is a byval arg. 10776 if (Flags.isByVal()) 10777 ArgValue = ByValArgs[j++]; 10778 10779 if (VA.isRegLoc()) { 10780 // Queue up the argument copies and emit them at the end. 10781 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 10782 } else { 10783 assert(VA.isMemLoc() && "Argument not register or memory"); 10784 assert(!IsTailCall && "Tail call not allowed if stack is used " 10785 "for passing parameters"); 10786 10787 // Work out the address of the stack slot. 10788 if (!StackPtr.getNode()) 10789 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10790 SDValue Address = 10791 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 10792 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 10793 10794 // Emit the store. 10795 MemOpChains.push_back( 10796 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 10797 } 10798 } 10799 10800 // Join the stores, which are independent of one another. 10801 if (!MemOpChains.empty()) 10802 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 10803 10804 SDValue Glue; 10805 10806 // Build a sequence of copy-to-reg nodes, chained and glued together. 10807 for (auto &Reg : RegsToPass) { 10808 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 10809 Glue = Chain.getValue(1); 10810 } 10811 10812 // Validate that none of the argument registers have been marked as 10813 // reserved, if so report an error. Do the same for the return address if this 10814 // is not a tailcall. 10815 validateCCReservedRegs(RegsToPass, MF); 10816 if (!IsTailCall && 10817 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 10818 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10819 MF.getFunction(), 10820 "Return address register required, but has been reserved."}); 10821 10822 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 10823 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 10824 // split it and then direct call can be matched by PseudoCALL. 10825 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 10826 const GlobalValue *GV = S->getGlobal(); 10827 10828 unsigned OpFlags = RISCVII::MO_CALL; 10829 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 10830 OpFlags = RISCVII::MO_PLT; 10831 10832 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 10833 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 10834 unsigned OpFlags = RISCVII::MO_CALL; 10835 10836 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 10837 nullptr)) 10838 OpFlags = RISCVII::MO_PLT; 10839 10840 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 10841 } 10842 10843 // The first call operand is the chain and the second is the target address. 10844 SmallVector<SDValue, 8> Ops; 10845 Ops.push_back(Chain); 10846 Ops.push_back(Callee); 10847 10848 // Add argument registers to the end of the list so that they are 10849 // known live into the call. 10850 for (auto &Reg : RegsToPass) 10851 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 10852 10853 if (!IsTailCall) { 10854 // Add a register mask operand representing the call-preserved registers. 10855 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10856 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 10857 assert(Mask && "Missing call preserved mask for calling convention"); 10858 Ops.push_back(DAG.getRegisterMask(Mask)); 10859 } 10860 10861 // Glue the call to the argument copies, if any. 10862 if (Glue.getNode()) 10863 Ops.push_back(Glue); 10864 10865 // Emit the call. 10866 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10867 10868 if (IsTailCall) { 10869 MF.getFrameInfo().setHasTailCall(); 10870 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 10871 } 10872 10873 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 10874 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 10875 Glue = Chain.getValue(1); 10876 10877 // Mark the end of the call, which is glued to the call itself. 10878 Chain = DAG.getCALLSEQ_END(Chain, 10879 DAG.getConstant(NumBytes, DL, PtrVT, true), 10880 DAG.getConstant(0, DL, PtrVT, true), 10881 Glue, DL); 10882 Glue = Chain.getValue(1); 10883 10884 // Assign locations to each value returned by this call. 10885 SmallVector<CCValAssign, 16> RVLocs; 10886 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 10887 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 10888 10889 // Copy all of the result registers out of their specified physreg. 10890 for (auto &VA : RVLocs) { 10891 // Copy the value out 10892 SDValue RetValue = 10893 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 10894 // Glue the RetValue to the end of the call sequence 10895 Chain = RetValue.getValue(1); 10896 Glue = RetValue.getValue(2); 10897 10898 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10899 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 10900 SDValue RetValue2 = 10901 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 10902 Chain = RetValue2.getValue(1); 10903 Glue = RetValue2.getValue(2); 10904 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 10905 RetValue2); 10906 } 10907 10908 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 10909 10910 InVals.push_back(RetValue); 10911 } 10912 10913 return Chain; 10914 } 10915 10916 bool RISCVTargetLowering::CanLowerReturn( 10917 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 10918 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 10919 SmallVector<CCValAssign, 16> RVLocs; 10920 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 10921 10922 Optional<unsigned> FirstMaskArgument; 10923 if (Subtarget.hasVInstructions()) 10924 FirstMaskArgument = preAssignMask(Outs); 10925 10926 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10927 MVT VT = Outs[i].VT; 10928 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10929 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10930 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 10931 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 10932 *this, FirstMaskArgument)) 10933 return false; 10934 } 10935 return true; 10936 } 10937 10938 SDValue 10939 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 10940 bool IsVarArg, 10941 const SmallVectorImpl<ISD::OutputArg> &Outs, 10942 const SmallVectorImpl<SDValue> &OutVals, 10943 const SDLoc &DL, SelectionDAG &DAG) const { 10944 const MachineFunction &MF = DAG.getMachineFunction(); 10945 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10946 10947 // Stores the assignment of the return value to a location. 10948 SmallVector<CCValAssign, 16> RVLocs; 10949 10950 // Info about the registers and stack slot. 10951 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 10952 *DAG.getContext()); 10953 10954 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 10955 nullptr, CC_RISCV); 10956 10957 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 10958 report_fatal_error("GHC functions return void only"); 10959 10960 SDValue Glue; 10961 SmallVector<SDValue, 4> RetOps(1, Chain); 10962 10963 // Copy the result values into the output registers. 10964 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 10965 SDValue Val = OutVals[i]; 10966 CCValAssign &VA = RVLocs[i]; 10967 assert(VA.isRegLoc() && "Can only return in registers!"); 10968 10969 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10970 // Handle returning f64 on RV32D with a soft float ABI. 10971 assert(VA.isRegLoc() && "Expected return via registers"); 10972 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 10973 DAG.getVTList(MVT::i32, MVT::i32), Val); 10974 SDValue Lo = SplitF64.getValue(0); 10975 SDValue Hi = SplitF64.getValue(1); 10976 Register RegLo = VA.getLocReg(); 10977 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10978 Register RegHi = RegLo + 1; 10979 10980 if (STI.isRegisterReservedByUser(RegLo) || 10981 STI.isRegisterReservedByUser(RegHi)) 10982 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10983 MF.getFunction(), 10984 "Return value register required, but has been reserved."}); 10985 10986 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 10987 Glue = Chain.getValue(1); 10988 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 10989 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 10990 Glue = Chain.getValue(1); 10991 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 10992 } else { 10993 // Handle a 'normal' return. 10994 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 10995 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 10996 10997 if (STI.isRegisterReservedByUser(VA.getLocReg())) 10998 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10999 MF.getFunction(), 11000 "Return value register required, but has been reserved."}); 11001 11002 // Guarantee that all emitted copies are stuck together. 11003 Glue = Chain.getValue(1); 11004 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 11005 } 11006 } 11007 11008 RetOps[0] = Chain; // Update chain. 11009 11010 // Add the glue node if we have it. 11011 if (Glue.getNode()) { 11012 RetOps.push_back(Glue); 11013 } 11014 11015 unsigned RetOpc = RISCVISD::RET_FLAG; 11016 // Interrupt service routines use different return instructions. 11017 const Function &Func = DAG.getMachineFunction().getFunction(); 11018 if (Func.hasFnAttribute("interrupt")) { 11019 if (!Func.getReturnType()->isVoidTy()) 11020 report_fatal_error( 11021 "Functions with the interrupt attribute must have void return type!"); 11022 11023 MachineFunction &MF = DAG.getMachineFunction(); 11024 StringRef Kind = 11025 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 11026 11027 if (Kind == "user") 11028 RetOpc = RISCVISD::URET_FLAG; 11029 else if (Kind == "supervisor") 11030 RetOpc = RISCVISD::SRET_FLAG; 11031 else 11032 RetOpc = RISCVISD::MRET_FLAG; 11033 } 11034 11035 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 11036 } 11037 11038 void RISCVTargetLowering::validateCCReservedRegs( 11039 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 11040 MachineFunction &MF) const { 11041 const Function &F = MF.getFunction(); 11042 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 11043 11044 if (llvm::any_of(Regs, [&STI](auto Reg) { 11045 return STI.isRegisterReservedByUser(Reg.first); 11046 })) 11047 F.getContext().diagnose(DiagnosticInfoUnsupported{ 11048 F, "Argument register required, but has been reserved."}); 11049 } 11050 11051 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 11052 return CI->isTailCall(); 11053 } 11054 11055 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 11056 #define NODE_NAME_CASE(NODE) \ 11057 case RISCVISD::NODE: \ 11058 return "RISCVISD::" #NODE; 11059 // clang-format off 11060 switch ((RISCVISD::NodeType)Opcode) { 11061 case RISCVISD::FIRST_NUMBER: 11062 break; 11063 NODE_NAME_CASE(RET_FLAG) 11064 NODE_NAME_CASE(URET_FLAG) 11065 NODE_NAME_CASE(SRET_FLAG) 11066 NODE_NAME_CASE(MRET_FLAG) 11067 NODE_NAME_CASE(CALL) 11068 NODE_NAME_CASE(SELECT_CC) 11069 NODE_NAME_CASE(BR_CC) 11070 NODE_NAME_CASE(BuildPairF64) 11071 NODE_NAME_CASE(SplitF64) 11072 NODE_NAME_CASE(TAIL) 11073 NODE_NAME_CASE(MULHSU) 11074 NODE_NAME_CASE(SLLW) 11075 NODE_NAME_CASE(SRAW) 11076 NODE_NAME_CASE(SRLW) 11077 NODE_NAME_CASE(DIVW) 11078 NODE_NAME_CASE(DIVUW) 11079 NODE_NAME_CASE(REMUW) 11080 NODE_NAME_CASE(ROLW) 11081 NODE_NAME_CASE(RORW) 11082 NODE_NAME_CASE(CLZW) 11083 NODE_NAME_CASE(CTZW) 11084 NODE_NAME_CASE(FSLW) 11085 NODE_NAME_CASE(FSRW) 11086 NODE_NAME_CASE(FSL) 11087 NODE_NAME_CASE(FSR) 11088 NODE_NAME_CASE(FMV_H_X) 11089 NODE_NAME_CASE(FMV_X_ANYEXTH) 11090 NODE_NAME_CASE(FMV_X_SIGNEXTH) 11091 NODE_NAME_CASE(FMV_W_X_RV64) 11092 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 11093 NODE_NAME_CASE(FCVT_X) 11094 NODE_NAME_CASE(FCVT_XU) 11095 NODE_NAME_CASE(FCVT_W_RV64) 11096 NODE_NAME_CASE(FCVT_WU_RV64) 11097 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 11098 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 11099 NODE_NAME_CASE(READ_CYCLE_WIDE) 11100 NODE_NAME_CASE(GREV) 11101 NODE_NAME_CASE(GREVW) 11102 NODE_NAME_CASE(GORC) 11103 NODE_NAME_CASE(GORCW) 11104 NODE_NAME_CASE(SHFL) 11105 NODE_NAME_CASE(SHFLW) 11106 NODE_NAME_CASE(UNSHFL) 11107 NODE_NAME_CASE(UNSHFLW) 11108 NODE_NAME_CASE(BFP) 11109 NODE_NAME_CASE(BFPW) 11110 NODE_NAME_CASE(BCOMPRESS) 11111 NODE_NAME_CASE(BCOMPRESSW) 11112 NODE_NAME_CASE(BDECOMPRESS) 11113 NODE_NAME_CASE(BDECOMPRESSW) 11114 NODE_NAME_CASE(VMV_V_X_VL) 11115 NODE_NAME_CASE(VFMV_V_F_VL) 11116 NODE_NAME_CASE(VMV_X_S) 11117 NODE_NAME_CASE(VMV_S_X_VL) 11118 NODE_NAME_CASE(VFMV_S_F_VL) 11119 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 11120 NODE_NAME_CASE(READ_VLENB) 11121 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 11122 NODE_NAME_CASE(VSLIDEUP_VL) 11123 NODE_NAME_CASE(VSLIDE1UP_VL) 11124 NODE_NAME_CASE(VSLIDEDOWN_VL) 11125 NODE_NAME_CASE(VSLIDE1DOWN_VL) 11126 NODE_NAME_CASE(VID_VL) 11127 NODE_NAME_CASE(VFNCVT_ROD_VL) 11128 NODE_NAME_CASE(VECREDUCE_ADD_VL) 11129 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 11130 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 11131 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 11132 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 11133 NODE_NAME_CASE(VECREDUCE_AND_VL) 11134 NODE_NAME_CASE(VECREDUCE_OR_VL) 11135 NODE_NAME_CASE(VECREDUCE_XOR_VL) 11136 NODE_NAME_CASE(VECREDUCE_FADD_VL) 11137 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 11138 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 11139 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 11140 NODE_NAME_CASE(ADD_VL) 11141 NODE_NAME_CASE(AND_VL) 11142 NODE_NAME_CASE(MUL_VL) 11143 NODE_NAME_CASE(OR_VL) 11144 NODE_NAME_CASE(SDIV_VL) 11145 NODE_NAME_CASE(SHL_VL) 11146 NODE_NAME_CASE(SREM_VL) 11147 NODE_NAME_CASE(SRA_VL) 11148 NODE_NAME_CASE(SRL_VL) 11149 NODE_NAME_CASE(SUB_VL) 11150 NODE_NAME_CASE(UDIV_VL) 11151 NODE_NAME_CASE(UREM_VL) 11152 NODE_NAME_CASE(XOR_VL) 11153 NODE_NAME_CASE(SADDSAT_VL) 11154 NODE_NAME_CASE(UADDSAT_VL) 11155 NODE_NAME_CASE(SSUBSAT_VL) 11156 NODE_NAME_CASE(USUBSAT_VL) 11157 NODE_NAME_CASE(FADD_VL) 11158 NODE_NAME_CASE(FSUB_VL) 11159 NODE_NAME_CASE(FMUL_VL) 11160 NODE_NAME_CASE(FDIV_VL) 11161 NODE_NAME_CASE(FNEG_VL) 11162 NODE_NAME_CASE(FABS_VL) 11163 NODE_NAME_CASE(FSQRT_VL) 11164 NODE_NAME_CASE(FMA_VL) 11165 NODE_NAME_CASE(FCOPYSIGN_VL) 11166 NODE_NAME_CASE(SMIN_VL) 11167 NODE_NAME_CASE(SMAX_VL) 11168 NODE_NAME_CASE(UMIN_VL) 11169 NODE_NAME_CASE(UMAX_VL) 11170 NODE_NAME_CASE(FMINNUM_VL) 11171 NODE_NAME_CASE(FMAXNUM_VL) 11172 NODE_NAME_CASE(MULHS_VL) 11173 NODE_NAME_CASE(MULHU_VL) 11174 NODE_NAME_CASE(FP_TO_SINT_VL) 11175 NODE_NAME_CASE(FP_TO_UINT_VL) 11176 NODE_NAME_CASE(SINT_TO_FP_VL) 11177 NODE_NAME_CASE(UINT_TO_FP_VL) 11178 NODE_NAME_CASE(FP_EXTEND_VL) 11179 NODE_NAME_CASE(FP_ROUND_VL) 11180 NODE_NAME_CASE(VWMUL_VL) 11181 NODE_NAME_CASE(VWMULU_VL) 11182 NODE_NAME_CASE(VWMULSU_VL) 11183 NODE_NAME_CASE(VWADD_VL) 11184 NODE_NAME_CASE(VWADDU_VL) 11185 NODE_NAME_CASE(VWSUB_VL) 11186 NODE_NAME_CASE(VWSUBU_VL) 11187 NODE_NAME_CASE(VWADD_W_VL) 11188 NODE_NAME_CASE(VWADDU_W_VL) 11189 NODE_NAME_CASE(VWSUB_W_VL) 11190 NODE_NAME_CASE(VWSUBU_W_VL) 11191 NODE_NAME_CASE(SETCC_VL) 11192 NODE_NAME_CASE(VSELECT_VL) 11193 NODE_NAME_CASE(VP_MERGE_VL) 11194 NODE_NAME_CASE(VMAND_VL) 11195 NODE_NAME_CASE(VMOR_VL) 11196 NODE_NAME_CASE(VMXOR_VL) 11197 NODE_NAME_CASE(VMCLR_VL) 11198 NODE_NAME_CASE(VMSET_VL) 11199 NODE_NAME_CASE(VRGATHER_VX_VL) 11200 NODE_NAME_CASE(VRGATHER_VV_VL) 11201 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 11202 NODE_NAME_CASE(VSEXT_VL) 11203 NODE_NAME_CASE(VZEXT_VL) 11204 NODE_NAME_CASE(VCPOP_VL) 11205 NODE_NAME_CASE(READ_CSR) 11206 NODE_NAME_CASE(WRITE_CSR) 11207 NODE_NAME_CASE(SWAP_CSR) 11208 } 11209 // clang-format on 11210 return nullptr; 11211 #undef NODE_NAME_CASE 11212 } 11213 11214 /// getConstraintType - Given a constraint letter, return the type of 11215 /// constraint it is for this target. 11216 RISCVTargetLowering::ConstraintType 11217 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 11218 if (Constraint.size() == 1) { 11219 switch (Constraint[0]) { 11220 default: 11221 break; 11222 case 'f': 11223 return C_RegisterClass; 11224 case 'I': 11225 case 'J': 11226 case 'K': 11227 return C_Immediate; 11228 case 'A': 11229 return C_Memory; 11230 case 'S': // A symbolic address 11231 return C_Other; 11232 } 11233 } else { 11234 if (Constraint == "vr" || Constraint == "vm") 11235 return C_RegisterClass; 11236 } 11237 return TargetLowering::getConstraintType(Constraint); 11238 } 11239 11240 std::pair<unsigned, const TargetRegisterClass *> 11241 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11242 StringRef Constraint, 11243 MVT VT) const { 11244 // First, see if this is a constraint that directly corresponds to a 11245 // RISCV register class. 11246 if (Constraint.size() == 1) { 11247 switch (Constraint[0]) { 11248 case 'r': 11249 // TODO: Support fixed vectors up to XLen for P extension? 11250 if (VT.isVector()) 11251 break; 11252 return std::make_pair(0U, &RISCV::GPRRegClass); 11253 case 'f': 11254 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 11255 return std::make_pair(0U, &RISCV::FPR16RegClass); 11256 if (Subtarget.hasStdExtF() && VT == MVT::f32) 11257 return std::make_pair(0U, &RISCV::FPR32RegClass); 11258 if (Subtarget.hasStdExtD() && VT == MVT::f64) 11259 return std::make_pair(0U, &RISCV::FPR64RegClass); 11260 break; 11261 default: 11262 break; 11263 } 11264 } else if (Constraint == "vr") { 11265 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 11266 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11267 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 11268 return std::make_pair(0U, RC); 11269 } 11270 } else if (Constraint == "vm") { 11271 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 11272 return std::make_pair(0U, &RISCV::VMV0RegClass); 11273 } 11274 11275 // Clang will correctly decode the usage of register name aliases into their 11276 // official names. However, other frontends like `rustc` do not. This allows 11277 // users of these frontends to use the ABI names for registers in LLVM-style 11278 // register constraints. 11279 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 11280 .Case("{zero}", RISCV::X0) 11281 .Case("{ra}", RISCV::X1) 11282 .Case("{sp}", RISCV::X2) 11283 .Case("{gp}", RISCV::X3) 11284 .Case("{tp}", RISCV::X4) 11285 .Case("{t0}", RISCV::X5) 11286 .Case("{t1}", RISCV::X6) 11287 .Case("{t2}", RISCV::X7) 11288 .Cases("{s0}", "{fp}", RISCV::X8) 11289 .Case("{s1}", RISCV::X9) 11290 .Case("{a0}", RISCV::X10) 11291 .Case("{a1}", RISCV::X11) 11292 .Case("{a2}", RISCV::X12) 11293 .Case("{a3}", RISCV::X13) 11294 .Case("{a4}", RISCV::X14) 11295 .Case("{a5}", RISCV::X15) 11296 .Case("{a6}", RISCV::X16) 11297 .Case("{a7}", RISCV::X17) 11298 .Case("{s2}", RISCV::X18) 11299 .Case("{s3}", RISCV::X19) 11300 .Case("{s4}", RISCV::X20) 11301 .Case("{s5}", RISCV::X21) 11302 .Case("{s6}", RISCV::X22) 11303 .Case("{s7}", RISCV::X23) 11304 .Case("{s8}", RISCV::X24) 11305 .Case("{s9}", RISCV::X25) 11306 .Case("{s10}", RISCV::X26) 11307 .Case("{s11}", RISCV::X27) 11308 .Case("{t3}", RISCV::X28) 11309 .Case("{t4}", RISCV::X29) 11310 .Case("{t5}", RISCV::X30) 11311 .Case("{t6}", RISCV::X31) 11312 .Default(RISCV::NoRegister); 11313 if (XRegFromAlias != RISCV::NoRegister) 11314 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 11315 11316 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 11317 // TableGen record rather than the AsmName to choose registers for InlineAsm 11318 // constraints, plus we want to match those names to the widest floating point 11319 // register type available, manually select floating point registers here. 11320 // 11321 // The second case is the ABI name of the register, so that frontends can also 11322 // use the ABI names in register constraint lists. 11323 if (Subtarget.hasStdExtF()) { 11324 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 11325 .Cases("{f0}", "{ft0}", RISCV::F0_F) 11326 .Cases("{f1}", "{ft1}", RISCV::F1_F) 11327 .Cases("{f2}", "{ft2}", RISCV::F2_F) 11328 .Cases("{f3}", "{ft3}", RISCV::F3_F) 11329 .Cases("{f4}", "{ft4}", RISCV::F4_F) 11330 .Cases("{f5}", "{ft5}", RISCV::F5_F) 11331 .Cases("{f6}", "{ft6}", RISCV::F6_F) 11332 .Cases("{f7}", "{ft7}", RISCV::F7_F) 11333 .Cases("{f8}", "{fs0}", RISCV::F8_F) 11334 .Cases("{f9}", "{fs1}", RISCV::F9_F) 11335 .Cases("{f10}", "{fa0}", RISCV::F10_F) 11336 .Cases("{f11}", "{fa1}", RISCV::F11_F) 11337 .Cases("{f12}", "{fa2}", RISCV::F12_F) 11338 .Cases("{f13}", "{fa3}", RISCV::F13_F) 11339 .Cases("{f14}", "{fa4}", RISCV::F14_F) 11340 .Cases("{f15}", "{fa5}", RISCV::F15_F) 11341 .Cases("{f16}", "{fa6}", RISCV::F16_F) 11342 .Cases("{f17}", "{fa7}", RISCV::F17_F) 11343 .Cases("{f18}", "{fs2}", RISCV::F18_F) 11344 .Cases("{f19}", "{fs3}", RISCV::F19_F) 11345 .Cases("{f20}", "{fs4}", RISCV::F20_F) 11346 .Cases("{f21}", "{fs5}", RISCV::F21_F) 11347 .Cases("{f22}", "{fs6}", RISCV::F22_F) 11348 .Cases("{f23}", "{fs7}", RISCV::F23_F) 11349 .Cases("{f24}", "{fs8}", RISCV::F24_F) 11350 .Cases("{f25}", "{fs9}", RISCV::F25_F) 11351 .Cases("{f26}", "{fs10}", RISCV::F26_F) 11352 .Cases("{f27}", "{fs11}", RISCV::F27_F) 11353 .Cases("{f28}", "{ft8}", RISCV::F28_F) 11354 .Cases("{f29}", "{ft9}", RISCV::F29_F) 11355 .Cases("{f30}", "{ft10}", RISCV::F30_F) 11356 .Cases("{f31}", "{ft11}", RISCV::F31_F) 11357 .Default(RISCV::NoRegister); 11358 if (FReg != RISCV::NoRegister) { 11359 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 11360 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 11361 unsigned RegNo = FReg - RISCV::F0_F; 11362 unsigned DReg = RISCV::F0_D + RegNo; 11363 return std::make_pair(DReg, &RISCV::FPR64RegClass); 11364 } 11365 if (VT == MVT::f32 || VT == MVT::Other) 11366 return std::make_pair(FReg, &RISCV::FPR32RegClass); 11367 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 11368 unsigned RegNo = FReg - RISCV::F0_F; 11369 unsigned HReg = RISCV::F0_H + RegNo; 11370 return std::make_pair(HReg, &RISCV::FPR16RegClass); 11371 } 11372 } 11373 } 11374 11375 if (Subtarget.hasVInstructions()) { 11376 Register VReg = StringSwitch<Register>(Constraint.lower()) 11377 .Case("{v0}", RISCV::V0) 11378 .Case("{v1}", RISCV::V1) 11379 .Case("{v2}", RISCV::V2) 11380 .Case("{v3}", RISCV::V3) 11381 .Case("{v4}", RISCV::V4) 11382 .Case("{v5}", RISCV::V5) 11383 .Case("{v6}", RISCV::V6) 11384 .Case("{v7}", RISCV::V7) 11385 .Case("{v8}", RISCV::V8) 11386 .Case("{v9}", RISCV::V9) 11387 .Case("{v10}", RISCV::V10) 11388 .Case("{v11}", RISCV::V11) 11389 .Case("{v12}", RISCV::V12) 11390 .Case("{v13}", RISCV::V13) 11391 .Case("{v14}", RISCV::V14) 11392 .Case("{v15}", RISCV::V15) 11393 .Case("{v16}", RISCV::V16) 11394 .Case("{v17}", RISCV::V17) 11395 .Case("{v18}", RISCV::V18) 11396 .Case("{v19}", RISCV::V19) 11397 .Case("{v20}", RISCV::V20) 11398 .Case("{v21}", RISCV::V21) 11399 .Case("{v22}", RISCV::V22) 11400 .Case("{v23}", RISCV::V23) 11401 .Case("{v24}", RISCV::V24) 11402 .Case("{v25}", RISCV::V25) 11403 .Case("{v26}", RISCV::V26) 11404 .Case("{v27}", RISCV::V27) 11405 .Case("{v28}", RISCV::V28) 11406 .Case("{v29}", RISCV::V29) 11407 .Case("{v30}", RISCV::V30) 11408 .Case("{v31}", RISCV::V31) 11409 .Default(RISCV::NoRegister); 11410 if (VReg != RISCV::NoRegister) { 11411 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11412 return std::make_pair(VReg, &RISCV::VMRegClass); 11413 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11414 return std::make_pair(VReg, &RISCV::VRRegClass); 11415 for (const auto *RC : 11416 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11417 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11418 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11419 return std::make_pair(VReg, RC); 11420 } 11421 } 11422 } 11423 } 11424 11425 std::pair<Register, const TargetRegisterClass *> Res = 11426 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11427 11428 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11429 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11430 // Subtarget into account. 11431 if (Res.second == &RISCV::GPRF16RegClass || 11432 Res.second == &RISCV::GPRF32RegClass || 11433 Res.second == &RISCV::GPRF64RegClass) 11434 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11435 11436 return Res; 11437 } 11438 11439 unsigned 11440 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11441 // Currently only support length 1 constraints. 11442 if (ConstraintCode.size() == 1) { 11443 switch (ConstraintCode[0]) { 11444 case 'A': 11445 return InlineAsm::Constraint_A; 11446 default: 11447 break; 11448 } 11449 } 11450 11451 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11452 } 11453 11454 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11455 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11456 SelectionDAG &DAG) const { 11457 // Currently only support length 1 constraints. 11458 if (Constraint.length() == 1) { 11459 switch (Constraint[0]) { 11460 case 'I': 11461 // Validate & create a 12-bit signed immediate operand. 11462 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11463 uint64_t CVal = C->getSExtValue(); 11464 if (isInt<12>(CVal)) 11465 Ops.push_back( 11466 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11467 } 11468 return; 11469 case 'J': 11470 // Validate & create an integer zero operand. 11471 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11472 if (C->getZExtValue() == 0) 11473 Ops.push_back( 11474 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11475 return; 11476 case 'K': 11477 // Validate & create a 5-bit unsigned immediate operand. 11478 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11479 uint64_t CVal = C->getZExtValue(); 11480 if (isUInt<5>(CVal)) 11481 Ops.push_back( 11482 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11483 } 11484 return; 11485 case 'S': 11486 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11487 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11488 GA->getValueType(0))); 11489 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11490 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11491 BA->getValueType(0))); 11492 } 11493 return; 11494 default: 11495 break; 11496 } 11497 } 11498 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11499 } 11500 11501 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11502 Instruction *Inst, 11503 AtomicOrdering Ord) const { 11504 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 11505 return Builder.CreateFence(Ord); 11506 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 11507 return Builder.CreateFence(AtomicOrdering::Release); 11508 return nullptr; 11509 } 11510 11511 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11512 Instruction *Inst, 11513 AtomicOrdering Ord) const { 11514 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11515 return Builder.CreateFence(AtomicOrdering::Acquire); 11516 return nullptr; 11517 } 11518 11519 TargetLowering::AtomicExpansionKind 11520 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11521 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11522 // point operations can't be used in an lr/sc sequence without breaking the 11523 // forward-progress guarantee. 11524 if (AI->isFloatingPointOperation()) 11525 return AtomicExpansionKind::CmpXChg; 11526 11527 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11528 if (Size == 8 || Size == 16) 11529 return AtomicExpansionKind::MaskedIntrinsic; 11530 return AtomicExpansionKind::None; 11531 } 11532 11533 static Intrinsic::ID 11534 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11535 if (XLen == 32) { 11536 switch (BinOp) { 11537 default: 11538 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11539 case AtomicRMWInst::Xchg: 11540 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11541 case AtomicRMWInst::Add: 11542 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11543 case AtomicRMWInst::Sub: 11544 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11545 case AtomicRMWInst::Nand: 11546 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11547 case AtomicRMWInst::Max: 11548 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11549 case AtomicRMWInst::Min: 11550 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11551 case AtomicRMWInst::UMax: 11552 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11553 case AtomicRMWInst::UMin: 11554 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11555 } 11556 } 11557 11558 if (XLen == 64) { 11559 switch (BinOp) { 11560 default: 11561 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11562 case AtomicRMWInst::Xchg: 11563 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11564 case AtomicRMWInst::Add: 11565 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11566 case AtomicRMWInst::Sub: 11567 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11568 case AtomicRMWInst::Nand: 11569 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11570 case AtomicRMWInst::Max: 11571 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11572 case AtomicRMWInst::Min: 11573 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11574 case AtomicRMWInst::UMax: 11575 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11576 case AtomicRMWInst::UMin: 11577 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11578 } 11579 } 11580 11581 llvm_unreachable("Unexpected XLen\n"); 11582 } 11583 11584 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11585 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11586 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11587 unsigned XLen = Subtarget.getXLen(); 11588 Value *Ordering = 11589 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11590 Type *Tys[] = {AlignedAddr->getType()}; 11591 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11592 AI->getModule(), 11593 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11594 11595 if (XLen == 64) { 11596 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11597 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11598 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11599 } 11600 11601 Value *Result; 11602 11603 // Must pass the shift amount needed to sign extend the loaded value prior 11604 // to performing a signed comparison for min/max. ShiftAmt is the number of 11605 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11606 // is the number of bits to left+right shift the value in order to 11607 // sign-extend. 11608 if (AI->getOperation() == AtomicRMWInst::Min || 11609 AI->getOperation() == AtomicRMWInst::Max) { 11610 const DataLayout &DL = AI->getModule()->getDataLayout(); 11611 unsigned ValWidth = 11612 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11613 Value *SextShamt = 11614 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11615 Result = Builder.CreateCall(LrwOpScwLoop, 11616 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11617 } else { 11618 Result = 11619 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11620 } 11621 11622 if (XLen == 64) 11623 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11624 return Result; 11625 } 11626 11627 TargetLowering::AtomicExpansionKind 11628 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11629 AtomicCmpXchgInst *CI) const { 11630 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11631 if (Size == 8 || Size == 16) 11632 return AtomicExpansionKind::MaskedIntrinsic; 11633 return AtomicExpansionKind::None; 11634 } 11635 11636 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11637 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11638 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11639 unsigned XLen = Subtarget.getXLen(); 11640 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11641 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11642 if (XLen == 64) { 11643 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11644 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11645 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11646 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11647 } 11648 Type *Tys[] = {AlignedAddr->getType()}; 11649 Function *MaskedCmpXchg = 11650 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11651 Value *Result = Builder.CreateCall( 11652 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11653 if (XLen == 64) 11654 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11655 return Result; 11656 } 11657 11658 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT, 11659 EVT DataVT) const { 11660 return false; 11661 } 11662 11663 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11664 EVT VT) const { 11665 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11666 return false; 11667 11668 switch (FPVT.getSimpleVT().SimpleTy) { 11669 case MVT::f16: 11670 return Subtarget.hasStdExtZfh(); 11671 case MVT::f32: 11672 return Subtarget.hasStdExtF(); 11673 case MVT::f64: 11674 return Subtarget.hasStdExtD(); 11675 default: 11676 return false; 11677 } 11678 } 11679 11680 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11681 // If we are using the small code model, we can reduce size of jump table 11682 // entry to 4 bytes. 11683 if (Subtarget.is64Bit() && !isPositionIndependent() && 11684 getTargetMachine().getCodeModel() == CodeModel::Small) { 11685 return MachineJumpTableInfo::EK_Custom32; 11686 } 11687 return TargetLowering::getJumpTableEncoding(); 11688 } 11689 11690 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 11691 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 11692 unsigned uid, MCContext &Ctx) const { 11693 assert(Subtarget.is64Bit() && !isPositionIndependent() && 11694 getTargetMachine().getCodeModel() == CodeModel::Small); 11695 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 11696 } 11697 11698 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 11699 EVT VT) const { 11700 VT = VT.getScalarType(); 11701 11702 if (!VT.isSimple()) 11703 return false; 11704 11705 switch (VT.getSimpleVT().SimpleTy) { 11706 case MVT::f16: 11707 return Subtarget.hasStdExtZfh(); 11708 case MVT::f32: 11709 return Subtarget.hasStdExtF(); 11710 case MVT::f64: 11711 return Subtarget.hasStdExtD(); 11712 default: 11713 break; 11714 } 11715 11716 return false; 11717 } 11718 11719 Register RISCVTargetLowering::getExceptionPointerRegister( 11720 const Constant *PersonalityFn) const { 11721 return RISCV::X10; 11722 } 11723 11724 Register RISCVTargetLowering::getExceptionSelectorRegister( 11725 const Constant *PersonalityFn) const { 11726 return RISCV::X11; 11727 } 11728 11729 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 11730 // Return false to suppress the unnecessary extensions if the LibCall 11731 // arguments or return value is f32 type for LP64 ABI. 11732 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 11733 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 11734 return false; 11735 11736 return true; 11737 } 11738 11739 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 11740 if (Subtarget.is64Bit() && Type == MVT::i32) 11741 return true; 11742 11743 return IsSigned; 11744 } 11745 11746 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 11747 SDValue C) const { 11748 // Check integral scalar types. 11749 if (VT.isScalarInteger()) { 11750 // Omit the optimization if the sub target has the M extension and the data 11751 // size exceeds XLen. 11752 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 11753 return false; 11754 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 11755 // Break the MUL to a SLLI and an ADD/SUB. 11756 const APInt &Imm = ConstNode->getAPIntValue(); 11757 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 11758 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 11759 return true; 11760 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 11761 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 11762 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 11763 (Imm - 8).isPowerOf2())) 11764 return true; 11765 // Omit the following optimization if the sub target has the M extension 11766 // and the data size >= XLen. 11767 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 11768 return false; 11769 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 11770 // a pair of LUI/ADDI. 11771 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 11772 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 11773 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 11774 (1 - ImmS).isPowerOf2()) 11775 return true; 11776 } 11777 } 11778 } 11779 11780 return false; 11781 } 11782 11783 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 11784 SDValue ConstNode) const { 11785 // Let the DAGCombiner decide for vectors. 11786 EVT VT = AddNode.getValueType(); 11787 if (VT.isVector()) 11788 return true; 11789 11790 // Let the DAGCombiner decide for larger types. 11791 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 11792 return true; 11793 11794 // It is worse if c1 is simm12 while c1*c2 is not. 11795 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 11796 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 11797 const APInt &C1 = C1Node->getAPIntValue(); 11798 const APInt &C2 = C2Node->getAPIntValue(); 11799 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 11800 return false; 11801 11802 // Default to true and let the DAGCombiner decide. 11803 return true; 11804 } 11805 11806 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 11807 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 11808 bool *Fast) const { 11809 if (!VT.isVector()) { 11810 if (Fast) 11811 *Fast = false; 11812 return Subtarget.enableUnalignedScalarMem(); 11813 } 11814 11815 // All vector implementations must support element alignment 11816 EVT ElemVT = VT.getVectorElementType(); 11817 if (Alignment >= ElemVT.getStoreSize()) { 11818 if (Fast) 11819 *Fast = true; 11820 return true; 11821 } 11822 11823 return false; 11824 } 11825 11826 bool RISCVTargetLowering::splitValueIntoRegisterParts( 11827 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 11828 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 11829 bool IsABIRegCopy = CC.hasValue(); 11830 EVT ValueVT = Val.getValueType(); 11831 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11832 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 11833 // and cast to f32. 11834 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 11835 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 11836 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 11837 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 11838 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 11839 Parts[0] = Val; 11840 return true; 11841 } 11842 11843 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11844 LLVMContext &Context = *DAG.getContext(); 11845 EVT ValueEltVT = ValueVT.getVectorElementType(); 11846 EVT PartEltVT = PartVT.getVectorElementType(); 11847 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11848 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11849 if (PartVTBitSize % ValueVTBitSize == 0) { 11850 assert(PartVTBitSize >= ValueVTBitSize); 11851 // If the element types are different, bitcast to the same element type of 11852 // PartVT first. 11853 // Give an example here, we want copy a <vscale x 1 x i8> value to 11854 // <vscale x 4 x i16>. 11855 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 11856 // subvector, then we can bitcast to <vscale x 4 x i16>. 11857 if (ValueEltVT != PartEltVT) { 11858 if (PartVTBitSize > ValueVTBitSize) { 11859 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11860 assert(Count != 0 && "The number of element should not be zero."); 11861 EVT SameEltTypeVT = 11862 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11863 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 11864 DAG.getUNDEF(SameEltTypeVT), Val, 11865 DAG.getVectorIdxConstant(0, DL)); 11866 } 11867 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 11868 } else { 11869 Val = 11870 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 11871 Val, DAG.getVectorIdxConstant(0, DL)); 11872 } 11873 Parts[0] = Val; 11874 return true; 11875 } 11876 } 11877 return false; 11878 } 11879 11880 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 11881 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 11882 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 11883 bool IsABIRegCopy = CC.hasValue(); 11884 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11885 SDValue Val = Parts[0]; 11886 11887 // Cast the f32 to i32, truncate to i16, and cast back to f16. 11888 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 11889 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 11890 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 11891 return Val; 11892 } 11893 11894 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11895 LLVMContext &Context = *DAG.getContext(); 11896 SDValue Val = Parts[0]; 11897 EVT ValueEltVT = ValueVT.getVectorElementType(); 11898 EVT PartEltVT = PartVT.getVectorElementType(); 11899 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11900 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11901 if (PartVTBitSize % ValueVTBitSize == 0) { 11902 assert(PartVTBitSize >= ValueVTBitSize); 11903 EVT SameEltTypeVT = ValueVT; 11904 // If the element types are different, convert it to the same element type 11905 // of PartVT. 11906 // Give an example here, we want copy a <vscale x 1 x i8> value from 11907 // <vscale x 4 x i16>. 11908 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 11909 // then we can extract <vscale x 1 x i8>. 11910 if (ValueEltVT != PartEltVT) { 11911 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11912 assert(Count != 0 && "The number of element should not be zero."); 11913 SameEltTypeVT = 11914 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11915 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 11916 } 11917 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 11918 DAG.getVectorIdxConstant(0, DL)); 11919 return Val; 11920 } 11921 } 11922 return SDValue(); 11923 } 11924 11925 SDValue 11926 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11927 SelectionDAG &DAG, 11928 SmallVectorImpl<SDNode *> &Created) const { 11929 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11930 if (isIntDivCheap(N->getValueType(0), Attr)) 11931 return SDValue(N, 0); // Lower SDIV as SDIV 11932 11933 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 11934 "Unexpected divisor!"); 11935 11936 // Conditional move is needed, so do the transformation iff Zbt is enabled. 11937 if (!Subtarget.hasStdExtZbt()) 11938 return SDValue(); 11939 11940 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 11941 // Besides, more critical path instructions will be generated when dividing 11942 // by 2. So we keep using the original DAGs for these cases. 11943 unsigned Lg2 = Divisor.countTrailingZeros(); 11944 if (Lg2 == 1 || Lg2 >= 12) 11945 return SDValue(); 11946 11947 // fold (sdiv X, pow2) 11948 EVT VT = N->getValueType(0); 11949 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 11950 return SDValue(); 11951 11952 SDLoc DL(N); 11953 SDValue N0 = N->getOperand(0); 11954 SDValue Zero = DAG.getConstant(0, DL, VT); 11955 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11956 11957 // Add (N0 < 0) ? Pow2 - 1 : 0; 11958 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 11959 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11960 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 11961 11962 Created.push_back(Cmp.getNode()); 11963 Created.push_back(Add.getNode()); 11964 Created.push_back(Sel.getNode()); 11965 11966 // Divide by pow2. 11967 SDValue SRA = 11968 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 11969 11970 // If we're dividing by a positive value, we're done. Otherwise, we must 11971 // negate the result. 11972 if (Divisor.isNonNegative()) 11973 return SRA; 11974 11975 Created.push_back(SRA.getNode()); 11976 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11977 } 11978 11979 #define GET_REGISTER_MATCHER 11980 #include "RISCVGenAsmMatcher.inc" 11981 11982 Register 11983 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 11984 const MachineFunction &MF) const { 11985 Register Reg = MatchRegisterAltName(RegName); 11986 if (Reg == RISCV::NoRegister) 11987 Reg = MatchRegisterName(RegName); 11988 if (Reg == RISCV::NoRegister) 11989 report_fatal_error( 11990 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 11991 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 11992 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 11993 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 11994 StringRef(RegName) + "\".")); 11995 return Reg; 11996 } 11997 11998 namespace llvm { 11999 namespace RISCVVIntrinsicsTable { 12000 12001 #define GET_RISCVVIntrinsicsTable_IMPL 12002 #include "RISCVGenSearchableTables.inc" 12003 12004 } // namespace RISCVVIntrinsicsTable 12005 12006 } // namespace llvm 12007