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 if (!Subtarget.hasStdExtZbb()) 191 setOperationAction(ISD::SIGN_EXTEND_INREG, {MVT::i8, MVT::i16}, Expand); 192 193 if (Subtarget.is64Bit()) { 194 setOperationAction({ISD::ADD, ISD::SUB, ISD::SHL, ISD::SRA, ISD::SRL}, 195 MVT::i32, Custom); 196 197 setOperationAction({ISD::UADDO, ISD::USUBO, ISD::UADDSAT, ISD::USUBSAT}, 198 MVT::i32, Custom); 199 } else { 200 setLibcallName( 201 {RTLIB::SHL_I128, RTLIB::SRL_I128, RTLIB::SRA_I128, RTLIB::MUL_I128}, 202 nullptr); 203 setLibcallName(RTLIB::MULO_I64, nullptr); 204 } 205 206 if (!Subtarget.hasStdExtM()) { 207 setOperationAction({ISD::MUL, ISD::MULHS, ISD::MULHU, ISD::SDIV, ISD::UDIV, 208 ISD::SREM, ISD::UREM}, 209 XLenVT, Expand); 210 } else { 211 if (Subtarget.is64Bit()) { 212 setOperationAction(ISD::MUL, {MVT::i32, MVT::i128}, Custom); 213 214 setOperationAction({ISD::SDIV, ISD::UDIV, ISD::UREM}, 215 {MVT::i8, MVT::i16, MVT::i32}, Custom); 216 } else { 217 setOperationAction(ISD::MUL, MVT::i64, Custom); 218 } 219 } 220 221 setOperationAction( 222 {ISD::SDIVREM, ISD::UDIVREM, ISD::SMUL_LOHI, ISD::UMUL_LOHI}, XLenVT, 223 Expand); 224 225 setOperationAction({ISD::SHL_PARTS, ISD::SRL_PARTS, ISD::SRA_PARTS}, XLenVT, 226 Custom); 227 228 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 229 Subtarget.hasStdExtZbkb()) { 230 if (Subtarget.is64Bit()) 231 setOperationAction({ISD::ROTL, ISD::ROTR}, MVT::i32, Custom); 232 } else { 233 setOperationAction({ISD::ROTL, ISD::ROTR}, XLenVT, Expand); 234 } 235 236 if (Subtarget.hasStdExtZbp()) { 237 // Custom lower bswap/bitreverse so we can convert them to GREVI to enable 238 // more combining. 239 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, XLenVT, Custom); 240 241 // BSWAP i8 doesn't exist. 242 setOperationAction(ISD::BITREVERSE, MVT::i8, Custom); 243 244 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i16, Custom); 245 246 if (Subtarget.is64Bit()) 247 setOperationAction({ISD::BITREVERSE, ISD::BSWAP}, MVT::i32, Custom); 248 } else { 249 // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll 250 // pattern match it directly in isel. 251 setOperationAction(ISD::BSWAP, XLenVT, 252 (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) 253 ? Legal 254 : Expand); 255 // Zbkb can use rev8+brev8 to implement bitreverse. 256 setOperationAction(ISD::BITREVERSE, XLenVT, 257 Subtarget.hasStdExtZbkb() ? Custom : Expand); 258 } 259 260 if (Subtarget.hasStdExtZbb()) { 261 setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, XLenVT, 262 Legal); 263 264 if (Subtarget.is64Bit()) 265 setOperationAction( 266 {ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF}, 267 MVT::i32, Custom); 268 } else { 269 setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP}, XLenVT, Expand); 270 271 if (Subtarget.is64Bit()) 272 setOperationAction(ISD::ABS, MVT::i32, Custom); 273 } 274 275 if (Subtarget.hasStdExtZbt()) { 276 setOperationAction({ISD::FSHL, ISD::FSHR}, XLenVT, Custom); 277 setOperationAction(ISD::SELECT, XLenVT, Legal); 278 279 if (Subtarget.is64Bit()) 280 setOperationAction({ISD::FSHL, ISD::FSHR}, MVT::i32, Custom); 281 } else { 282 setOperationAction(ISD::SELECT, XLenVT, Custom); 283 } 284 285 static constexpr ISD::NodeType FPLegalNodeTypes[] = { 286 ISD::FMINNUM, ISD::FMAXNUM, ISD::LRINT, 287 ISD::LLRINT, ISD::LROUND, ISD::LLROUND, 288 ISD::STRICT_LRINT, ISD::STRICT_LLRINT, ISD::STRICT_LROUND, 289 ISD::STRICT_LLROUND, ISD::STRICT_FMA, ISD::STRICT_FADD, 290 ISD::STRICT_FSUB, ISD::STRICT_FMUL, ISD::STRICT_FDIV, 291 ISD::STRICT_FSQRT, ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS}; 292 293 static const ISD::CondCode FPCCToExpand[] = { 294 ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 295 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT, 296 ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO}; 297 298 static const ISD::NodeType FPOpToExpand[] = { 299 ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW, 300 ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16}; 301 302 if (Subtarget.hasStdExtZfh()) 303 setOperationAction(ISD::BITCAST, MVT::i16, Custom); 304 305 if (Subtarget.hasStdExtZfh()) { 306 for (auto NT : FPLegalNodeTypes) 307 setOperationAction(NT, MVT::f16, Legal); 308 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal); 309 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal); 310 for (auto CC : FPCCToExpand) 311 setCondCodeAction(CC, MVT::f16, Expand); 312 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 313 setOperationAction(ISD::SELECT, MVT::f16, Custom); 314 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 315 316 setOperationAction({ISD::FREM, ISD::FCEIL, ISD::FFLOOR, ISD::FNEARBYINT, 317 ISD::FRINT, ISD::FROUND, ISD::FROUNDEVEN, ISD::FTRUNC, 318 ISD::FPOW, ISD::FPOWI, ISD::FCOS, ISD::FSIN, 319 ISD::FSINCOS, ISD::FEXP, ISD::FEXP2, ISD::FLOG, 320 ISD::FLOG2, ISD::FLOG10}, 321 MVT::f16, Promote); 322 323 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 324 // complete support for all operations in LegalizeDAG. 325 326 // We need to custom promote this. 327 if (Subtarget.is64Bit()) 328 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 329 } 330 331 if (Subtarget.hasStdExtF()) { 332 for (auto NT : FPLegalNodeTypes) 333 setOperationAction(NT, MVT::f32, Legal); 334 for (auto CC : FPCCToExpand) 335 setCondCodeAction(CC, MVT::f32, Expand); 336 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 337 setOperationAction(ISD::SELECT, MVT::f32, Custom); 338 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 339 for (auto Op : FPOpToExpand) 340 setOperationAction(Op, MVT::f32, Expand); 341 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 342 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 343 } 344 345 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 346 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 347 348 if (Subtarget.hasStdExtD()) { 349 for (auto NT : FPLegalNodeTypes) 350 setOperationAction(NT, MVT::f64, Legal); 351 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 352 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 353 for (auto CC : FPCCToExpand) 354 setCondCodeAction(CC, MVT::f64, Expand); 355 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 356 setOperationAction(ISD::SELECT, MVT::f64, Custom); 357 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 358 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 359 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 360 for (auto Op : FPOpToExpand) 361 setOperationAction(Op, MVT::f64, Expand); 362 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 363 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 364 } 365 366 if (Subtarget.is64Bit()) 367 setOperationAction({ISD::FP_TO_UINT, ISD::FP_TO_SINT, 368 ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT}, 369 MVT::i32, Custom); 370 371 if (Subtarget.hasStdExtF()) { 372 setOperationAction({ISD::FP_TO_UINT_SAT, ISD::FP_TO_SINT_SAT}, XLenVT, 373 Custom); 374 375 setOperationAction({ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT, 376 ISD::STRICT_UINT_TO_FP, ISD::STRICT_SINT_TO_FP}, 377 XLenVT, Legal); 378 379 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 380 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 381 } 382 383 setOperationAction({ISD::GlobalAddress, ISD::BlockAddress, ISD::ConstantPool, 384 ISD::JumpTable}, 385 XLenVT, Custom); 386 387 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 388 389 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 390 // Unfortunately this can't be determined just from the ISA naming string. 391 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 392 Subtarget.is64Bit() ? Legal : Custom); 393 394 setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Legal); 395 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 396 if (Subtarget.is64Bit()) 397 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 398 399 if (Subtarget.hasStdExtA()) { 400 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 401 setMinCmpXchgSizeInBits(32); 402 } else { 403 setMaxAtomicSizeInBitsSupported(0); 404 } 405 406 setBooleanContents(ZeroOrOneBooleanContent); 407 408 if (Subtarget.hasVInstructions()) { 409 setBooleanVectorContents(ZeroOrOneBooleanContent); 410 411 setOperationAction(ISD::VSCALE, XLenVT, Custom); 412 413 // RVV intrinsics may have illegal operands. 414 // We also need to custom legalize vmv.x.s. 415 setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN}, 416 {MVT::i8, MVT::i16}, Custom); 417 if (Subtarget.is64Bit()) 418 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 419 else 420 setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN}, 421 MVT::i64, Custom); 422 423 setOperationAction({ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID}, 424 MVT::Other, Custom); 425 426 static const unsigned IntegerVPOps[] = { 427 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 428 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 429 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 430 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 431 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 432 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 433 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 434 ISD::VP_MERGE, ISD::VP_SELECT, ISD::VP_FPTOSI, 435 ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_SEXT, 436 ISD::VP_ZEXT, ISD::VP_TRUNC}; 437 438 static const unsigned FloatingPointVPOps[] = { 439 ISD::VP_FADD, ISD::VP_FSUB, 440 ISD::VP_FMUL, ISD::VP_FDIV, 441 ISD::VP_FNEG, ISD::VP_FMA, 442 ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 443 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, 444 ISD::VP_MERGE, ISD::VP_SELECT, 445 ISD::VP_SITOFP, ISD::VP_UITOFP, 446 ISD::VP_SETCC, ISD::VP_FP_ROUND}; 447 448 if (!Subtarget.is64Bit()) { 449 // We must custom-lower certain vXi64 operations on RV32 due to the vector 450 // element type being illegal. 451 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 452 MVT::i64, Custom); 453 454 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, 455 ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR, 456 ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 457 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}, 458 MVT::i64, Custom); 459 460 setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 461 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, 462 ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN, 463 ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN}, 464 MVT::i64, Custom); 465 } 466 467 for (MVT VT : BoolVecVTs) { 468 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 469 470 // Mask VTs are custom-expanded into a series of standard nodes 471 setOperationAction({ISD::TRUNCATE, ISD::CONCAT_VECTORS, 472 ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 473 VT, Custom); 474 475 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 476 Custom); 477 478 setOperationAction(ISD::SELECT, VT, Custom); 479 setOperationAction( 480 {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT, 481 Expand); 482 483 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom); 484 485 setOperationAction( 486 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 487 Custom); 488 489 setOperationAction( 490 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 491 Custom); 492 493 // RVV has native int->float & float->int conversions where the 494 // element type sizes are within one power-of-two of each other. Any 495 // wider distances between type sizes have to be lowered as sequences 496 // which progressively narrow the gap in stages. 497 setOperationAction( 498 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 499 VT, Custom); 500 501 // Expand all extending loads to types larger than this, and truncating 502 // stores from types larger than this. 503 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 504 setTruncStoreAction(OtherVT, VT, Expand); 505 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 506 VT, Expand); 507 } 508 509 setOperationAction( 510 {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_TRUNC, ISD::VP_SETCC}, VT, 511 Custom); 512 } 513 514 for (MVT VT : IntVecVTs) { 515 if (VT.getVectorElementType() == MVT::i64 && 516 !Subtarget.hasVInstructionsI64()) 517 continue; 518 519 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 520 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 521 522 // Vectors implement MULHS/MULHU. 523 setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand); 524 525 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 526 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) 527 setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand); 528 529 setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT, 530 Legal); 531 532 setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand); 533 534 setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP, ISD::BSWAP}, VT, 535 Expand); 536 537 setOperationAction(ISD::BSWAP, VT, Expand); 538 539 // Custom-lower extensions and truncations from/to mask types. 540 setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, 541 VT, Custom); 542 543 // RVV has native int->float & float->int conversions where the 544 // element type sizes are within one power-of-two of each other. Any 545 // wider distances between type sizes have to be lowered as sequences 546 // which progressively narrow the gap in stages. 547 setOperationAction( 548 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 549 VT, Custom); 550 551 setOperationAction( 552 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal); 553 554 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 555 // nodes which truncate by one power of two at a time. 556 setOperationAction(ISD::TRUNCATE, VT, Custom); 557 558 // Custom-lower insert/extract operations to simplify patterns. 559 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 560 Custom); 561 562 // Custom-lower reduction operations to set up the corresponding custom 563 // nodes' operands. 564 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, 565 ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR, 566 ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 567 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}, 568 VT, Custom); 569 570 for (unsigned VPOpc : IntegerVPOps) 571 setOperationAction(VPOpc, VT, Custom); 572 573 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 574 575 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 576 VT, Custom); 577 578 setOperationAction( 579 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 580 Custom); 581 582 setOperationAction( 583 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 584 VT, Custom); 585 586 setOperationAction(ISD::SELECT, VT, Custom); 587 setOperationAction(ISD::SELECT_CC, VT, Expand); 588 589 setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom); 590 591 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 592 setTruncStoreAction(VT, OtherVT, Expand); 593 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 594 VT, Expand); 595 } 596 597 // Splice 598 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 599 600 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 601 // type that can represent the value exactly. 602 if (VT.getVectorElementType() != MVT::i64) { 603 MVT FloatEltVT = 604 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 605 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 606 if (isTypeLegal(FloatVT)) { 607 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 608 Custom); 609 } 610 } 611 } 612 613 // Expand various CCs to best match the RVV ISA, which natively supports UNE 614 // but no other unordered comparisons, and supports all ordered comparisons 615 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 616 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 617 // and we pattern-match those back to the "original", swapping operands once 618 // more. This way we catch both operations and both "vf" and "fv" forms with 619 // fewer patterns. 620 static const ISD::CondCode VFPCCToExpand[] = { 621 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 622 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 623 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 624 }; 625 626 // Sets common operation actions on RVV floating-point vector types. 627 const auto SetCommonVFPActions = [&](MVT VT) { 628 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 629 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 630 // sizes are within one power-of-two of each other. Therefore conversions 631 // between vXf16 and vXf64 must be lowered as sequences which convert via 632 // vXf32. 633 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 634 // Custom-lower insert/extract operations to simplify patterns. 635 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 636 Custom); 637 // Expand various condition codes (explained above). 638 for (auto CC : VFPCCToExpand) 639 setCondCodeAction(CC, VT, Expand); 640 641 setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal); 642 643 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 644 VT, Custom); 645 646 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 647 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 648 VT, Custom); 649 650 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 651 652 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 653 654 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 655 VT, Custom); 656 657 setOperationAction( 658 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 659 Custom); 660 661 setOperationAction(ISD::SELECT, VT, Custom); 662 setOperationAction(ISD::SELECT_CC, VT, Expand); 663 664 setOperationAction( 665 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 666 VT, Custom); 667 668 setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom); 669 670 for (unsigned VPOpc : FloatingPointVPOps) 671 setOperationAction(VPOpc, 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_TRUNC}, 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 for (unsigned VPOpc : IntegerVPOps) 809 setOperationAction(VPOpc, VT, Custom); 810 811 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 812 // type that can represent the value exactly. 813 if (VT.getVectorElementType() != MVT::i64) { 814 MVT FloatEltVT = 815 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 816 EVT FloatVT = 817 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 818 if (isTypeLegal(FloatVT)) 819 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 820 Custom); 821 } 822 } 823 824 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 825 if (!useRVVForFixedLengthVectorVT(VT)) 826 continue; 827 828 // By default everything must be expanded. 829 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 830 setOperationAction(Op, VT, Expand); 831 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 832 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 833 setTruncStoreAction(VT, OtherVT, Expand); 834 } 835 836 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 837 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 838 Custom); 839 840 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS, 841 ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT, 842 ISD::EXTRACT_VECTOR_ELT}, 843 VT, Custom); 844 845 setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE, 846 ISD::MGATHER, ISD::MSCATTER}, 847 VT, Custom); 848 849 setOperationAction( 850 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 851 Custom); 852 853 setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV, 854 ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT, 855 ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM}, 856 VT, Custom); 857 858 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 859 860 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 861 VT, Custom); 862 863 for (auto CC : VFPCCToExpand) 864 setCondCodeAction(CC, VT, Expand); 865 866 setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom); 867 setOperationAction(ISD::SELECT_CC, VT, Expand); 868 869 setOperationAction(ISD::BITCAST, VT, Custom); 870 871 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 872 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 873 VT, Custom); 874 875 for (unsigned VPOpc : FloatingPointVPOps) 876 setOperationAction(VPOpc, VT, Custom); 877 } 878 879 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 880 setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64}, 881 Custom); 882 if (Subtarget.hasStdExtZfh()) 883 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 884 if (Subtarget.hasStdExtF()) 885 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 886 if (Subtarget.hasStdExtD()) 887 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 888 } 889 } 890 891 // Function alignments. 892 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 893 setMinFunctionAlignment(FunctionAlignment); 894 setPrefFunctionAlignment(FunctionAlignment); 895 896 setMinimumJumpTableEntries(5); 897 898 // Jumps are expensive, compared to logic 899 setJumpIsExpensive(); 900 901 setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND, 902 ISD::OR, ISD::XOR}); 903 904 if (Subtarget.hasStdExtZbp()) 905 setTargetDAGCombine({ISD::ROTL, ISD::ROTR}); 906 if (Subtarget.hasStdExtZbkb()) 907 setTargetDAGCombine(ISD::BITREVERSE); 908 if (Subtarget.hasStdExtZfh() || Subtarget.hasStdExtZbb()) 909 setTargetDAGCombine(ISD::SIGN_EXTEND_INREG); 910 if (Subtarget.hasStdExtF()) 911 setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT, 912 ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}); 913 if (Subtarget.hasVInstructions()) 914 setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER, 915 ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL, 916 ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR}); 917 918 setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2"); 919 setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2"); 920 } 921 922 EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL, 923 LLVMContext &Context, 924 EVT VT) const { 925 if (!VT.isVector()) 926 return getPointerTy(DL); 927 if (Subtarget.hasVInstructions() && 928 (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors())) 929 return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount()); 930 return VT.changeVectorElementTypeToInteger(); 931 } 932 933 MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const { 934 return Subtarget.getXLenVT(); 935 } 936 937 bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info, 938 const CallInst &I, 939 MachineFunction &MF, 940 unsigned Intrinsic) const { 941 auto &DL = I.getModule()->getDataLayout(); 942 switch (Intrinsic) { 943 default: 944 return false; 945 case Intrinsic::riscv_masked_atomicrmw_xchg_i32: 946 case Intrinsic::riscv_masked_atomicrmw_add_i32: 947 case Intrinsic::riscv_masked_atomicrmw_sub_i32: 948 case Intrinsic::riscv_masked_atomicrmw_nand_i32: 949 case Intrinsic::riscv_masked_atomicrmw_max_i32: 950 case Intrinsic::riscv_masked_atomicrmw_min_i32: 951 case Intrinsic::riscv_masked_atomicrmw_umax_i32: 952 case Intrinsic::riscv_masked_atomicrmw_umin_i32: 953 case Intrinsic::riscv_masked_cmpxchg_i32: 954 Info.opc = ISD::INTRINSIC_W_CHAIN; 955 Info.memVT = MVT::i32; 956 Info.ptrVal = I.getArgOperand(0); 957 Info.offset = 0; 958 Info.align = Align(4); 959 Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore | 960 MachineMemOperand::MOVolatile; 961 return true; 962 case Intrinsic::riscv_masked_strided_load: 963 Info.opc = ISD::INTRINSIC_W_CHAIN; 964 Info.ptrVal = I.getArgOperand(1); 965 Info.memVT = getValueType(DL, I.getType()->getScalarType()); 966 Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8); 967 Info.size = MemoryLocation::UnknownSize; 968 Info.flags |= MachineMemOperand::MOLoad; 969 return true; 970 case Intrinsic::riscv_masked_strided_store: 971 Info.opc = ISD::INTRINSIC_VOID; 972 Info.ptrVal = I.getArgOperand(1); 973 Info.memVT = 974 getValueType(DL, I.getArgOperand(0)->getType()->getScalarType()); 975 Info.align = Align( 976 DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) / 977 8); 978 Info.size = MemoryLocation::UnknownSize; 979 Info.flags |= MachineMemOperand::MOStore; 980 return true; 981 case Intrinsic::riscv_seg2_load: 982 case Intrinsic::riscv_seg3_load: 983 case Intrinsic::riscv_seg4_load: 984 case Intrinsic::riscv_seg5_load: 985 case Intrinsic::riscv_seg6_load: 986 case Intrinsic::riscv_seg7_load: 987 case Intrinsic::riscv_seg8_load: 988 Info.opc = ISD::INTRINSIC_W_CHAIN; 989 Info.ptrVal = I.getArgOperand(0); 990 Info.memVT = 991 getValueType(DL, I.getType()->getStructElementType(0)->getScalarType()); 992 Info.align = 993 Align(DL.getTypeSizeInBits( 994 I.getType()->getStructElementType(0)->getScalarType()) / 995 8); 996 Info.size = MemoryLocation::UnknownSize; 997 Info.flags |= MachineMemOperand::MOLoad; 998 return true; 999 } 1000 } 1001 1002 bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL, 1003 const AddrMode &AM, Type *Ty, 1004 unsigned AS, 1005 Instruction *I) const { 1006 // No global is ever allowed as a base. 1007 if (AM.BaseGV) 1008 return false; 1009 1010 // Require a 12-bit signed offset. 1011 if (!isInt<12>(AM.BaseOffs)) 1012 return false; 1013 1014 switch (AM.Scale) { 1015 case 0: // "r+i" or just "i", depending on HasBaseReg. 1016 break; 1017 case 1: 1018 if (!AM.HasBaseReg) // allow "r+i". 1019 break; 1020 return false; // disallow "r+r" or "r+r+i". 1021 default: 1022 return false; 1023 } 1024 1025 return true; 1026 } 1027 1028 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1029 return isInt<12>(Imm); 1030 } 1031 1032 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1033 return isInt<12>(Imm); 1034 } 1035 1036 // On RV32, 64-bit integers are split into their high and low parts and held 1037 // in two different registers, so the trunc is free since the low register can 1038 // just be used. 1039 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1040 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1041 return false; 1042 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1043 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1044 return (SrcBits == 64 && DestBits == 32); 1045 } 1046 1047 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1048 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1049 !SrcVT.isInteger() || !DstVT.isInteger()) 1050 return false; 1051 unsigned SrcBits = SrcVT.getSizeInBits(); 1052 unsigned DestBits = DstVT.getSizeInBits(); 1053 return (SrcBits == 64 && DestBits == 32); 1054 } 1055 1056 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1057 // Zexts are free if they can be combined with a load. 1058 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1059 // poorly with type legalization of compares preferring sext. 1060 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1061 EVT MemVT = LD->getMemoryVT(); 1062 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1063 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1064 LD->getExtensionType() == ISD::ZEXTLOAD)) 1065 return true; 1066 } 1067 1068 return TargetLowering::isZExtFree(Val, VT2); 1069 } 1070 1071 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1072 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1073 } 1074 1075 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const { 1076 return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32); 1077 } 1078 1079 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1080 return Subtarget.hasStdExtZbb(); 1081 } 1082 1083 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1084 return Subtarget.hasStdExtZbb(); 1085 } 1086 1087 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1088 EVT VT = Y.getValueType(); 1089 1090 // FIXME: Support vectors once we have tests. 1091 if (VT.isVector()) 1092 return false; 1093 1094 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1095 Subtarget.hasStdExtZbkb()) && 1096 !isa<ConstantSDNode>(Y); 1097 } 1098 1099 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const { 1100 // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position. 1101 auto *C = dyn_cast<ConstantSDNode>(Y); 1102 return C && C->getAPIntValue().ule(10); 1103 } 1104 1105 /// Check if sinking \p I's operands to I's basic block is profitable, because 1106 /// the operands can be folded into a target instruction, e.g. 1107 /// splats of scalars can fold into vector instructions. 1108 bool RISCVTargetLowering::shouldSinkOperands( 1109 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1110 using namespace llvm::PatternMatch; 1111 1112 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1113 return false; 1114 1115 auto IsSinker = [&](Instruction *I, int Operand) { 1116 switch (I->getOpcode()) { 1117 case Instruction::Add: 1118 case Instruction::Sub: 1119 case Instruction::Mul: 1120 case Instruction::And: 1121 case Instruction::Or: 1122 case Instruction::Xor: 1123 case Instruction::FAdd: 1124 case Instruction::FSub: 1125 case Instruction::FMul: 1126 case Instruction::FDiv: 1127 case Instruction::ICmp: 1128 case Instruction::FCmp: 1129 return true; 1130 case Instruction::Shl: 1131 case Instruction::LShr: 1132 case Instruction::AShr: 1133 case Instruction::UDiv: 1134 case Instruction::SDiv: 1135 case Instruction::URem: 1136 case Instruction::SRem: 1137 return Operand == 1; 1138 case Instruction::Call: 1139 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1140 switch (II->getIntrinsicID()) { 1141 case Intrinsic::fma: 1142 case Intrinsic::vp_fma: 1143 return Operand == 0 || Operand == 1; 1144 // FIXME: Our patterns can only match vx/vf instructions when the splat 1145 // it on the RHS, because TableGen doesn't recognize our VP operations 1146 // as commutative. 1147 case Intrinsic::vp_add: 1148 case Intrinsic::vp_mul: 1149 case Intrinsic::vp_and: 1150 case Intrinsic::vp_or: 1151 case Intrinsic::vp_xor: 1152 case Intrinsic::vp_fadd: 1153 case Intrinsic::vp_fmul: 1154 case Intrinsic::vp_shl: 1155 case Intrinsic::vp_lshr: 1156 case Intrinsic::vp_ashr: 1157 case Intrinsic::vp_udiv: 1158 case Intrinsic::vp_sdiv: 1159 case Intrinsic::vp_urem: 1160 case Intrinsic::vp_srem: 1161 return Operand == 1; 1162 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1163 // explicit patterns for both LHS and RHS (as 'vr' versions). 1164 case Intrinsic::vp_sub: 1165 case Intrinsic::vp_fsub: 1166 case Intrinsic::vp_fdiv: 1167 return Operand == 0 || Operand == 1; 1168 default: 1169 return false; 1170 } 1171 } 1172 return false; 1173 default: 1174 return false; 1175 } 1176 }; 1177 1178 for (auto OpIdx : enumerate(I->operands())) { 1179 if (!IsSinker(I, OpIdx.index())) 1180 continue; 1181 1182 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1183 // Make sure we are not already sinking this operand 1184 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1185 continue; 1186 1187 // We are looking for a splat that can be sunk. 1188 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1189 m_Undef(), m_ZeroMask()))) 1190 continue; 1191 1192 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1193 // and vector registers 1194 for (Use &U : Op->uses()) { 1195 Instruction *Insn = cast<Instruction>(U.getUser()); 1196 if (!IsSinker(Insn, U.getOperandNo())) 1197 return false; 1198 } 1199 1200 Ops.push_back(&Op->getOperandUse(0)); 1201 Ops.push_back(&OpIdx.value()); 1202 } 1203 return true; 1204 } 1205 1206 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1207 bool ForCodeSize) const { 1208 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1209 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1210 return false; 1211 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1212 return false; 1213 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1214 return false; 1215 return Imm.isZero(); 1216 } 1217 1218 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1219 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1220 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1221 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1222 } 1223 1224 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1225 CallingConv::ID CC, 1226 EVT VT) const { 1227 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1228 // We might still end up using a GPR but that will be decided based on ABI. 1229 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1230 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1231 return MVT::f32; 1232 1233 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1234 } 1235 1236 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1237 CallingConv::ID CC, 1238 EVT VT) const { 1239 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1240 // We might still end up using a GPR but that will be decided based on ABI. 1241 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1242 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1243 return 1; 1244 1245 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1246 } 1247 1248 // Changes the condition code and swaps operands if necessary, so the SetCC 1249 // operation matches one of the comparisons supported directly by branches 1250 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1251 // with 1/-1. 1252 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1253 ISD::CondCode &CC, SelectionDAG &DAG) { 1254 // Convert X > -1 to X >= 0. 1255 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1256 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1257 CC = ISD::SETGE; 1258 return; 1259 } 1260 // Convert X < 1 to 0 >= X. 1261 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1262 RHS = LHS; 1263 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1264 CC = ISD::SETGE; 1265 return; 1266 } 1267 1268 switch (CC) { 1269 default: 1270 break; 1271 case ISD::SETGT: 1272 case ISD::SETLE: 1273 case ISD::SETUGT: 1274 case ISD::SETULE: 1275 CC = ISD::getSetCCSwappedOperands(CC); 1276 std::swap(LHS, RHS); 1277 break; 1278 } 1279 } 1280 1281 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1282 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1283 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1284 if (VT.getVectorElementType() == MVT::i1) 1285 KnownSize *= 8; 1286 1287 switch (KnownSize) { 1288 default: 1289 llvm_unreachable("Invalid LMUL."); 1290 case 8: 1291 return RISCVII::VLMUL::LMUL_F8; 1292 case 16: 1293 return RISCVII::VLMUL::LMUL_F4; 1294 case 32: 1295 return RISCVII::VLMUL::LMUL_F2; 1296 case 64: 1297 return RISCVII::VLMUL::LMUL_1; 1298 case 128: 1299 return RISCVII::VLMUL::LMUL_2; 1300 case 256: 1301 return RISCVII::VLMUL::LMUL_4; 1302 case 512: 1303 return RISCVII::VLMUL::LMUL_8; 1304 } 1305 } 1306 1307 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1308 switch (LMul) { 1309 default: 1310 llvm_unreachable("Invalid LMUL."); 1311 case RISCVII::VLMUL::LMUL_F8: 1312 case RISCVII::VLMUL::LMUL_F4: 1313 case RISCVII::VLMUL::LMUL_F2: 1314 case RISCVII::VLMUL::LMUL_1: 1315 return RISCV::VRRegClassID; 1316 case RISCVII::VLMUL::LMUL_2: 1317 return RISCV::VRM2RegClassID; 1318 case RISCVII::VLMUL::LMUL_4: 1319 return RISCV::VRM4RegClassID; 1320 case RISCVII::VLMUL::LMUL_8: 1321 return RISCV::VRM8RegClassID; 1322 } 1323 } 1324 1325 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1326 RISCVII::VLMUL LMUL = getLMUL(VT); 1327 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1328 LMUL == RISCVII::VLMUL::LMUL_F4 || 1329 LMUL == RISCVII::VLMUL::LMUL_F2 || 1330 LMUL == RISCVII::VLMUL::LMUL_1) { 1331 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1332 "Unexpected subreg numbering"); 1333 return RISCV::sub_vrm1_0 + Index; 1334 } 1335 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1336 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1337 "Unexpected subreg numbering"); 1338 return RISCV::sub_vrm2_0 + Index; 1339 } 1340 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1341 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1342 "Unexpected subreg numbering"); 1343 return RISCV::sub_vrm4_0 + Index; 1344 } 1345 llvm_unreachable("Invalid vector type."); 1346 } 1347 1348 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1349 if (VT.getVectorElementType() == MVT::i1) 1350 return RISCV::VRRegClassID; 1351 return getRegClassIDForLMUL(getLMUL(VT)); 1352 } 1353 1354 // Attempt to decompose a subvector insert/extract between VecVT and 1355 // SubVecVT via subregister indices. Returns the subregister index that 1356 // can perform the subvector insert/extract with the given element index, as 1357 // well as the index corresponding to any leftover subvectors that must be 1358 // further inserted/extracted within the register class for SubVecVT. 1359 std::pair<unsigned, unsigned> 1360 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1361 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1362 const RISCVRegisterInfo *TRI) { 1363 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1364 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1365 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1366 "Register classes not ordered"); 1367 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1368 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1369 // Try to compose a subregister index that takes us from the incoming 1370 // LMUL>1 register class down to the outgoing one. At each step we half 1371 // the LMUL: 1372 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1373 // Note that this is not guaranteed to find a subregister index, such as 1374 // when we are extracting from one VR type to another. 1375 unsigned SubRegIdx = RISCV::NoSubRegister; 1376 for (const unsigned RCID : 1377 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1378 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1379 VecVT = VecVT.getHalfNumVectorElementsVT(); 1380 bool IsHi = 1381 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1382 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1383 getSubregIndexByMVT(VecVT, IsHi)); 1384 if (IsHi) 1385 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1386 } 1387 return {SubRegIdx, InsertExtractIdx}; 1388 } 1389 1390 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1391 // stores for those types. 1392 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1393 return !Subtarget.useRVVForFixedLengthVectors() || 1394 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1395 } 1396 1397 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1398 if (ScalarTy->isPointerTy()) 1399 return true; 1400 1401 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1402 ScalarTy->isIntegerTy(32)) 1403 return true; 1404 1405 if (ScalarTy->isIntegerTy(64)) 1406 return Subtarget.hasVInstructionsI64(); 1407 1408 if (ScalarTy->isHalfTy()) 1409 return Subtarget.hasVInstructionsF16(); 1410 if (ScalarTy->isFloatTy()) 1411 return Subtarget.hasVInstructionsF32(); 1412 if (ScalarTy->isDoubleTy()) 1413 return Subtarget.hasVInstructionsF64(); 1414 1415 return false; 1416 } 1417 1418 static SDValue getVLOperand(SDValue Op) { 1419 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1420 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1421 "Unexpected opcode"); 1422 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1423 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1424 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1425 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1426 if (!II) 1427 return SDValue(); 1428 return Op.getOperand(II->VLOperand + 1 + HasChain); 1429 } 1430 1431 static bool useRVVForFixedLengthVectorVT(MVT VT, 1432 const RISCVSubtarget &Subtarget) { 1433 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1434 if (!Subtarget.useRVVForFixedLengthVectors()) 1435 return false; 1436 1437 // We only support a set of vector types with a consistent maximum fixed size 1438 // across all supported vector element types to avoid legalization issues. 1439 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1440 // fixed-length vector type we support is 1024 bytes. 1441 if (VT.getFixedSizeInBits() > 1024 * 8) 1442 return false; 1443 1444 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1445 1446 MVT EltVT = VT.getVectorElementType(); 1447 1448 // Don't use RVV for vectors we cannot scalarize if required. 1449 switch (EltVT.SimpleTy) { 1450 // i1 is supported but has different rules. 1451 default: 1452 return false; 1453 case MVT::i1: 1454 // Masks can only use a single register. 1455 if (VT.getVectorNumElements() > MinVLen) 1456 return false; 1457 MinVLen /= 8; 1458 break; 1459 case MVT::i8: 1460 case MVT::i16: 1461 case MVT::i32: 1462 break; 1463 case MVT::i64: 1464 if (!Subtarget.hasVInstructionsI64()) 1465 return false; 1466 break; 1467 case MVT::f16: 1468 if (!Subtarget.hasVInstructionsF16()) 1469 return false; 1470 break; 1471 case MVT::f32: 1472 if (!Subtarget.hasVInstructionsF32()) 1473 return false; 1474 break; 1475 case MVT::f64: 1476 if (!Subtarget.hasVInstructionsF64()) 1477 return false; 1478 break; 1479 } 1480 1481 // Reject elements larger than ELEN. 1482 if (EltVT.getSizeInBits() > Subtarget.getELEN()) 1483 return false; 1484 1485 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1486 // Don't use RVV for types that don't fit. 1487 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1488 return false; 1489 1490 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1491 // the base fixed length RVV support in place. 1492 if (!VT.isPow2VectorType()) 1493 return false; 1494 1495 return true; 1496 } 1497 1498 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1499 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1500 } 1501 1502 // Return the largest legal scalable vector type that matches VT's element type. 1503 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1504 const RISCVSubtarget &Subtarget) { 1505 // This may be called before legal types are setup. 1506 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1507 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1508 "Expected legal fixed length vector!"); 1509 1510 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1511 unsigned MaxELen = Subtarget.getELEN(); 1512 1513 MVT EltVT = VT.getVectorElementType(); 1514 switch (EltVT.SimpleTy) { 1515 default: 1516 llvm_unreachable("unexpected element type for RVV container"); 1517 case MVT::i1: 1518 case MVT::i8: 1519 case MVT::i16: 1520 case MVT::i32: 1521 case MVT::i64: 1522 case MVT::f16: 1523 case MVT::f32: 1524 case MVT::f64: { 1525 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1526 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1527 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1528 unsigned NumElts = 1529 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1530 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1531 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1532 return MVT::getScalableVectorVT(EltVT, NumElts); 1533 } 1534 } 1535 } 1536 1537 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1538 const RISCVSubtarget &Subtarget) { 1539 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1540 Subtarget); 1541 } 1542 1543 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1544 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1545 } 1546 1547 // Grow V to consume an entire RVV register. 1548 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1549 const RISCVSubtarget &Subtarget) { 1550 assert(VT.isScalableVector() && 1551 "Expected to convert into a scalable vector!"); 1552 assert(V.getValueType().isFixedLengthVector() && 1553 "Expected a fixed length vector operand!"); 1554 SDLoc DL(V); 1555 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1556 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1557 } 1558 1559 // Shrink V so it's just big enough to maintain a VT's worth of data. 1560 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1561 const RISCVSubtarget &Subtarget) { 1562 assert(VT.isFixedLengthVector() && 1563 "Expected to convert into a fixed length vector!"); 1564 assert(V.getValueType().isScalableVector() && 1565 "Expected a scalable vector operand!"); 1566 SDLoc DL(V); 1567 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1568 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1569 } 1570 1571 /// Return the type of the mask type suitable for masking the provided 1572 /// vector type. This is simply an i1 element type vector of the same 1573 /// (possibly scalable) length. 1574 static MVT getMaskTypeFor(EVT VecVT) { 1575 assert(VecVT.isVector()); 1576 ElementCount EC = VecVT.getVectorElementCount(); 1577 return MVT::getVectorVT(MVT::i1, EC); 1578 } 1579 1580 /// Creates an all ones mask suitable for masking a vector of type VecTy with 1581 /// vector length VL. . 1582 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL, 1583 SelectionDAG &DAG) { 1584 MVT MaskVT = getMaskTypeFor(VecVT); 1585 return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1586 } 1587 1588 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1589 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1590 // the vector type that it is contained in. 1591 static std::pair<SDValue, SDValue> 1592 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1593 const RISCVSubtarget &Subtarget) { 1594 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1595 MVT XLenVT = Subtarget.getXLenVT(); 1596 SDValue VL = VecVT.isFixedLengthVector() 1597 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1598 : DAG.getRegister(RISCV::X0, XLenVT); 1599 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 1600 return {Mask, VL}; 1601 } 1602 1603 // As above but assuming the given type is a scalable vector type. 1604 static std::pair<SDValue, SDValue> 1605 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1606 const RISCVSubtarget &Subtarget) { 1607 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1608 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1609 } 1610 1611 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1612 // of either is (currently) supported. This can get us into an infinite loop 1613 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1614 // as a ..., etc. 1615 // Until either (or both) of these can reliably lower any node, reporting that 1616 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1617 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1618 // which is not desirable. 1619 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1620 EVT VT, unsigned DefinedValues) const { 1621 return false; 1622 } 1623 1624 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1625 const RISCVSubtarget &Subtarget) { 1626 // RISCV FP-to-int conversions saturate to the destination register size, but 1627 // don't produce 0 for nan. We can use a conversion instruction and fix the 1628 // nan case with a compare and a select. 1629 SDValue Src = Op.getOperand(0); 1630 1631 EVT DstVT = Op.getValueType(); 1632 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1633 1634 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1635 unsigned Opc; 1636 if (SatVT == DstVT) 1637 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1638 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1639 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1640 else 1641 return SDValue(); 1642 // FIXME: Support other SatVTs by clamping before or after the conversion. 1643 1644 SDLoc DL(Op); 1645 SDValue FpToInt = DAG.getNode( 1646 Opc, DL, DstVT, Src, 1647 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1648 1649 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1650 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1651 } 1652 1653 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1654 // and back. Taking care to avoid converting values that are nan or already 1655 // correct. 1656 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1657 // have FRM dependencies modeled yet. 1658 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1659 MVT VT = Op.getSimpleValueType(); 1660 assert(VT.isVector() && "Unexpected type"); 1661 1662 SDLoc DL(Op); 1663 1664 // Freeze the source since we are increasing the number of uses. 1665 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1666 1667 // Truncate to integer and convert back to FP. 1668 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1669 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1670 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1671 1672 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1673 1674 if (Op.getOpcode() == ISD::FCEIL) { 1675 // If the truncated value is the greater than or equal to the original 1676 // value, we've computed the ceil. Otherwise, we went the wrong way and 1677 // need to increase by 1. 1678 // FIXME: This should use a masked operation. Handle here or in isel? 1679 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1680 DAG.getConstantFP(1.0, DL, VT)); 1681 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1682 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1683 } else if (Op.getOpcode() == ISD::FFLOOR) { 1684 // If the truncated value is the less than or equal to the original value, 1685 // we've computed the floor. Otherwise, we went the wrong way and need to 1686 // decrease by 1. 1687 // FIXME: This should use a masked operation. Handle here or in isel? 1688 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1689 DAG.getConstantFP(1.0, DL, VT)); 1690 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1691 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1692 } 1693 1694 // Restore the original sign so that -0.0 is preserved. 1695 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1696 1697 // Determine the largest integer that can be represented exactly. This and 1698 // values larger than it don't have any fractional bits so don't need to 1699 // be converted. 1700 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1701 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1702 APFloat MaxVal = APFloat(FltSem); 1703 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1704 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1705 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1706 1707 // If abs(Src) was larger than MaxVal or nan, keep it. 1708 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1709 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1710 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1711 } 1712 1713 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1714 // This mode isn't supported in vector hardware on RISCV. But as long as we 1715 // aren't compiling with trapping math, we can emulate this with 1716 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1717 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1718 // dependencies modeled yet. 1719 // FIXME: Use masked operations to avoid final merge. 1720 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1721 MVT VT = Op.getSimpleValueType(); 1722 assert(VT.isVector() && "Unexpected type"); 1723 1724 SDLoc DL(Op); 1725 1726 // Freeze the source since we are increasing the number of uses. 1727 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1728 1729 // We do the conversion on the absolute value and fix the sign at the end. 1730 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1731 1732 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1733 bool Ignored; 1734 APFloat Point5Pred = APFloat(0.5f); 1735 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1736 Point5Pred.next(/*nextDown*/ true); 1737 1738 // Add the adjustment. 1739 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1740 DAG.getConstantFP(Point5Pred, DL, VT)); 1741 1742 // Truncate to integer and convert back to fp. 1743 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1744 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1745 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1746 1747 // Restore the original sign. 1748 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1749 1750 // Determine the largest integer that can be represented exactly. This and 1751 // values larger than it don't have any fractional bits so don't need to 1752 // be converted. 1753 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1754 APFloat MaxVal = APFloat(FltSem); 1755 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1756 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1757 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1758 1759 // If abs(Src) was larger than MaxVal or nan, keep it. 1760 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1761 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1762 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1763 } 1764 1765 struct VIDSequence { 1766 int64_t StepNumerator; 1767 unsigned StepDenominator; 1768 int64_t Addend; 1769 }; 1770 1771 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1772 // to the (non-zero) step S and start value X. This can be then lowered as the 1773 // RVV sequence (VID * S) + X, for example. 1774 // The step S is represented as an integer numerator divided by a positive 1775 // denominator. Note that the implementation currently only identifies 1776 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1777 // cannot detect 2/3, for example. 1778 // Note that this method will also match potentially unappealing index 1779 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1780 // determine whether this is worth generating code for. 1781 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1782 unsigned NumElts = Op.getNumOperands(); 1783 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1784 if (!Op.getValueType().isInteger()) 1785 return None; 1786 1787 Optional<unsigned> SeqStepDenom; 1788 Optional<int64_t> SeqStepNum, SeqAddend; 1789 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1790 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1791 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1792 // Assume undef elements match the sequence; we just have to be careful 1793 // when interpolating across them. 1794 if (Op.getOperand(Idx).isUndef()) 1795 continue; 1796 // The BUILD_VECTOR must be all constants. 1797 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1798 return None; 1799 1800 uint64_t Val = Op.getConstantOperandVal(Idx) & 1801 maskTrailingOnes<uint64_t>(EltSizeInBits); 1802 1803 if (PrevElt) { 1804 // Calculate the step since the last non-undef element, and ensure 1805 // it's consistent across the entire sequence. 1806 unsigned IdxDiff = Idx - PrevElt->second; 1807 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1808 1809 // A zero-value value difference means that we're somewhere in the middle 1810 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1811 // step change before evaluating the sequence. 1812 if (ValDiff == 0) 1813 continue; 1814 1815 int64_t Remainder = ValDiff % IdxDiff; 1816 // Normalize the step if it's greater than 1. 1817 if (Remainder != ValDiff) { 1818 // The difference must cleanly divide the element span. 1819 if (Remainder != 0) 1820 return None; 1821 ValDiff /= IdxDiff; 1822 IdxDiff = 1; 1823 } 1824 1825 if (!SeqStepNum) 1826 SeqStepNum = ValDiff; 1827 else if (ValDiff != SeqStepNum) 1828 return None; 1829 1830 if (!SeqStepDenom) 1831 SeqStepDenom = IdxDiff; 1832 else if (IdxDiff != *SeqStepDenom) 1833 return None; 1834 } 1835 1836 // Record this non-undef element for later. 1837 if (!PrevElt || PrevElt->first != Val) 1838 PrevElt = std::make_pair(Val, Idx); 1839 } 1840 1841 // We need to have logged a step for this to count as a legal index sequence. 1842 if (!SeqStepNum || !SeqStepDenom) 1843 return None; 1844 1845 // Loop back through the sequence and validate elements we might have skipped 1846 // while waiting for a valid step. While doing this, log any sequence addend. 1847 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1848 if (Op.getOperand(Idx).isUndef()) 1849 continue; 1850 uint64_t Val = Op.getConstantOperandVal(Idx) & 1851 maskTrailingOnes<uint64_t>(EltSizeInBits); 1852 uint64_t ExpectedVal = 1853 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1854 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1855 if (!SeqAddend) 1856 SeqAddend = Addend; 1857 else if (Addend != SeqAddend) 1858 return None; 1859 } 1860 1861 assert(SeqAddend && "Must have an addend if we have a step"); 1862 1863 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1864 } 1865 1866 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1867 // and lower it as a VRGATHER_VX_VL from the source vector. 1868 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 1869 SelectionDAG &DAG, 1870 const RISCVSubtarget &Subtarget) { 1871 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1872 return SDValue(); 1873 SDValue Vec = SplatVal.getOperand(0); 1874 // Only perform this optimization on vectors of the same size for simplicity. 1875 if (Vec.getValueType() != VT) 1876 return SDValue(); 1877 SDValue Idx = SplatVal.getOperand(1); 1878 // The index must be a legal type. 1879 if (Idx.getValueType() != Subtarget.getXLenVT()) 1880 return SDValue(); 1881 1882 MVT ContainerVT = VT; 1883 if (VT.isFixedLengthVector()) { 1884 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1885 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 1886 } 1887 1888 SDValue Mask, VL; 1889 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1890 1891 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 1892 Idx, Mask, VL); 1893 1894 if (!VT.isFixedLengthVector()) 1895 return Gather; 1896 1897 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 1898 } 1899 1900 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1901 const RISCVSubtarget &Subtarget) { 1902 MVT VT = Op.getSimpleValueType(); 1903 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1904 1905 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1906 1907 SDLoc DL(Op); 1908 SDValue Mask, VL; 1909 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1910 1911 MVT XLenVT = Subtarget.getXLenVT(); 1912 unsigned NumElts = Op.getNumOperands(); 1913 1914 if (VT.getVectorElementType() == MVT::i1) { 1915 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 1916 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 1917 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 1918 } 1919 1920 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 1921 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 1922 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 1923 } 1924 1925 // Lower constant mask BUILD_VECTORs via an integer vector type, in 1926 // scalar integer chunks whose bit-width depends on the number of mask 1927 // bits and XLEN. 1928 // First, determine the most appropriate scalar integer type to use. This 1929 // is at most XLenVT, but may be shrunk to a smaller vector element type 1930 // according to the size of the final vector - use i8 chunks rather than 1931 // XLenVT if we're producing a v8i1. This results in more consistent 1932 // codegen across RV32 and RV64. 1933 unsigned NumViaIntegerBits = 1934 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 1935 NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN()); 1936 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 1937 // If we have to use more than one INSERT_VECTOR_ELT then this 1938 // optimization is likely to increase code size; avoid peforming it in 1939 // such a case. We can use a load from a constant pool in this case. 1940 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 1941 return SDValue(); 1942 // Now we can create our integer vector type. Note that it may be larger 1943 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 1944 MVT IntegerViaVecVT = 1945 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 1946 divideCeil(NumElts, NumViaIntegerBits)); 1947 1948 uint64_t Bits = 0; 1949 unsigned BitPos = 0, IntegerEltIdx = 0; 1950 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 1951 1952 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 1953 // Once we accumulate enough bits to fill our scalar type, insert into 1954 // our vector and clear our accumulated data. 1955 if (I != 0 && I % NumViaIntegerBits == 0) { 1956 if (NumViaIntegerBits <= 32) 1957 Bits = SignExtend64(Bits, 32); 1958 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1959 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 1960 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1961 Bits = 0; 1962 BitPos = 0; 1963 IntegerEltIdx++; 1964 } 1965 SDValue V = Op.getOperand(I); 1966 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 1967 Bits |= ((uint64_t)BitValue << BitPos); 1968 } 1969 1970 // Insert the (remaining) scalar value into position in our integer 1971 // vector type. 1972 if (NumViaIntegerBits <= 32) 1973 Bits = SignExtend64(Bits, 32); 1974 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1975 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 1976 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1977 1978 if (NumElts < NumViaIntegerBits) { 1979 // If we're producing a smaller vector than our minimum legal integer 1980 // type, bitcast to the equivalent (known-legal) mask type, and extract 1981 // our final mask. 1982 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 1983 Vec = DAG.getBitcast(MVT::v8i1, Vec); 1984 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 1985 DAG.getConstant(0, DL, XLenVT)); 1986 } else { 1987 // Else we must have produced an integer type with the same size as the 1988 // mask type; bitcast for the final result. 1989 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 1990 Vec = DAG.getBitcast(VT, Vec); 1991 } 1992 1993 return Vec; 1994 } 1995 1996 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 1997 // vector type, we have a legal equivalently-sized i8 type, so we can use 1998 // that. 1999 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2000 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2001 2002 SDValue WideVec; 2003 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2004 // For a splat, perform a scalar truncate before creating the wider 2005 // vector. 2006 assert(Splat.getValueType() == XLenVT && 2007 "Unexpected type for i1 splat value"); 2008 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2009 DAG.getConstant(1, DL, XLenVT)); 2010 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2011 } else { 2012 SmallVector<SDValue, 8> Ops(Op->op_values()); 2013 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2014 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2015 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2016 } 2017 2018 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2019 } 2020 2021 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2022 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2023 return Gather; 2024 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2025 : RISCVISD::VMV_V_X_VL; 2026 Splat = 2027 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2028 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2029 } 2030 2031 // Try and match index sequences, which we can lower to the vid instruction 2032 // with optional modifications. An all-undef vector is matched by 2033 // getSplatValue, above. 2034 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2035 int64_t StepNumerator = SimpleVID->StepNumerator; 2036 unsigned StepDenominator = SimpleVID->StepDenominator; 2037 int64_t Addend = SimpleVID->Addend; 2038 2039 assert(StepNumerator != 0 && "Invalid step"); 2040 bool Negate = false; 2041 int64_t SplatStepVal = StepNumerator; 2042 unsigned StepOpcode = ISD::MUL; 2043 if (StepNumerator != 1) { 2044 if (isPowerOf2_64(std::abs(StepNumerator))) { 2045 Negate = StepNumerator < 0; 2046 StepOpcode = ISD::SHL; 2047 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2048 } 2049 } 2050 2051 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2052 // threshold since it's the immediate value many RVV instructions accept. 2053 // There is no vmul.vi instruction so ensure multiply constant can fit in 2054 // a single addi instruction. 2055 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2056 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2057 isPowerOf2_32(StepDenominator) && 2058 (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) { 2059 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2060 // Convert right out of the scalable type so we can use standard ISD 2061 // nodes for the rest of the computation. If we used scalable types with 2062 // these, we'd lose the fixed-length vector info and generate worse 2063 // vsetvli code. 2064 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2065 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2066 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2067 SDValue SplatStep = DAG.getSplatBuildVector( 2068 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2069 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2070 } 2071 if (StepDenominator != 1) { 2072 SDValue SplatStep = DAG.getSplatBuildVector( 2073 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2074 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2075 } 2076 if (Addend != 0 || Negate) { 2077 SDValue SplatAddend = DAG.getSplatBuildVector( 2078 VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2079 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2080 } 2081 return VID; 2082 } 2083 } 2084 2085 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2086 // when re-interpreted as a vector with a larger element type. For example, 2087 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2088 // could be instead splat as 2089 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2090 // TODO: This optimization could also work on non-constant splats, but it 2091 // would require bit-manipulation instructions to construct the splat value. 2092 SmallVector<SDValue> Sequence; 2093 unsigned EltBitSize = VT.getScalarSizeInBits(); 2094 const auto *BV = cast<BuildVectorSDNode>(Op); 2095 if (VT.isInteger() && EltBitSize < 64 && 2096 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2097 BV->getRepeatedSequence(Sequence) && 2098 (Sequence.size() * EltBitSize) <= 64) { 2099 unsigned SeqLen = Sequence.size(); 2100 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2101 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2102 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2103 ViaIntVT == MVT::i64) && 2104 "Unexpected sequence type"); 2105 2106 unsigned EltIdx = 0; 2107 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2108 uint64_t SplatValue = 0; 2109 // Construct the amalgamated value which can be splatted as this larger 2110 // vector type. 2111 for (const auto &SeqV : Sequence) { 2112 if (!SeqV.isUndef()) 2113 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2114 << (EltIdx * EltBitSize)); 2115 EltIdx++; 2116 } 2117 2118 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2119 // achieve better constant materializion. 2120 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2121 SplatValue = SignExtend64(SplatValue, 32); 2122 2123 // Since we can't introduce illegal i64 types at this stage, we can only 2124 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2125 // way we can use RVV instructions to splat. 2126 assert((ViaIntVT.bitsLE(XLenVT) || 2127 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2128 "Unexpected bitcast sequence"); 2129 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2130 SDValue ViaVL = 2131 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2132 MVT ViaContainerVT = 2133 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2134 SDValue Splat = 2135 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2136 DAG.getUNDEF(ViaContainerVT), 2137 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2138 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2139 return DAG.getBitcast(VT, Splat); 2140 } 2141 } 2142 2143 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2144 // which constitute a large proportion of the elements. In such cases we can 2145 // splat a vector with the dominant element and make up the shortfall with 2146 // INSERT_VECTOR_ELTs. 2147 // Note that this includes vectors of 2 elements by association. The 2148 // upper-most element is the "dominant" one, allowing us to use a splat to 2149 // "insert" the upper element, and an insert of the lower element at position 2150 // 0, which improves codegen. 2151 SDValue DominantValue; 2152 unsigned MostCommonCount = 0; 2153 DenseMap<SDValue, unsigned> ValueCounts; 2154 unsigned NumUndefElts = 2155 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2156 2157 // Track the number of scalar loads we know we'd be inserting, estimated as 2158 // any non-zero floating-point constant. Other kinds of element are either 2159 // already in registers or are materialized on demand. The threshold at which 2160 // a vector load is more desirable than several scalar materializion and 2161 // vector-insertion instructions is not known. 2162 unsigned NumScalarLoads = 0; 2163 2164 for (SDValue V : Op->op_values()) { 2165 if (V.isUndef()) 2166 continue; 2167 2168 ValueCounts.insert(std::make_pair(V, 0)); 2169 unsigned &Count = ValueCounts[V]; 2170 2171 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2172 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2173 2174 // Is this value dominant? In case of a tie, prefer the highest element as 2175 // it's cheaper to insert near the beginning of a vector than it is at the 2176 // end. 2177 if (++Count >= MostCommonCount) { 2178 DominantValue = V; 2179 MostCommonCount = Count; 2180 } 2181 } 2182 2183 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2184 unsigned NumDefElts = NumElts - NumUndefElts; 2185 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2186 2187 // Don't perform this optimization when optimizing for size, since 2188 // materializing elements and inserting them tends to cause code bloat. 2189 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2190 ((MostCommonCount > DominantValueCountThreshold) || 2191 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2192 // Start by splatting the most common element. 2193 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2194 2195 DenseSet<SDValue> Processed{DominantValue}; 2196 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2197 for (const auto &OpIdx : enumerate(Op->ops())) { 2198 const SDValue &V = OpIdx.value(); 2199 if (V.isUndef() || !Processed.insert(V).second) 2200 continue; 2201 if (ValueCounts[V] == 1) { 2202 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2203 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2204 } else { 2205 // Blend in all instances of this value using a VSELECT, using a 2206 // mask where each bit signals whether that element is the one 2207 // we're after. 2208 SmallVector<SDValue> Ops; 2209 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2210 return DAG.getConstant(V == V1, DL, XLenVT); 2211 }); 2212 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2213 DAG.getBuildVector(SelMaskTy, DL, Ops), 2214 DAG.getSplatBuildVector(VT, DL, V), Vec); 2215 } 2216 } 2217 2218 return Vec; 2219 } 2220 2221 return SDValue(); 2222 } 2223 2224 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2225 SDValue Lo, SDValue Hi, SDValue VL, 2226 SelectionDAG &DAG) { 2227 if (!Passthru) 2228 Passthru = DAG.getUNDEF(VT); 2229 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2230 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2231 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2232 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2233 // node in order to try and match RVV vector/scalar instructions. 2234 if ((LoC >> 31) == HiC) 2235 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2236 2237 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2238 // vmv.v.x whose EEW = 32 to lower it. 2239 auto *Const = dyn_cast<ConstantSDNode>(VL); 2240 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2241 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2242 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2243 // access the subtarget here now. 2244 auto InterVec = DAG.getNode( 2245 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2246 DAG.getRegister(RISCV::X0, MVT::i32)); 2247 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2248 } 2249 } 2250 2251 // Fall back to a stack store and stride x0 vector load. 2252 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2253 Hi, VL); 2254 } 2255 2256 // Called by type legalization to handle splat of i64 on RV32. 2257 // FIXME: We can optimize this when the type has sign or zero bits in one 2258 // of the halves. 2259 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2260 SDValue Scalar, SDValue VL, 2261 SelectionDAG &DAG) { 2262 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2263 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2264 DAG.getConstant(0, DL, MVT::i32)); 2265 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2266 DAG.getConstant(1, DL, MVT::i32)); 2267 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2268 } 2269 2270 // This function lowers a splat of a scalar operand Splat with the vector 2271 // length VL. It ensures the final sequence is type legal, which is useful when 2272 // lowering a splat after type legalization. 2273 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2274 MVT VT, SDLoc DL, SelectionDAG &DAG, 2275 const RISCVSubtarget &Subtarget) { 2276 bool HasPassthru = Passthru && !Passthru.isUndef(); 2277 if (!HasPassthru && !Passthru) 2278 Passthru = DAG.getUNDEF(VT); 2279 if (VT.isFloatingPoint()) { 2280 // If VL is 1, we could use vfmv.s.f. 2281 if (isOneConstant(VL)) 2282 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2283 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2284 } 2285 2286 MVT XLenVT = Subtarget.getXLenVT(); 2287 2288 // Simplest case is that the operand needs to be promoted to XLenVT. 2289 if (Scalar.getValueType().bitsLE(XLenVT)) { 2290 // If the operand is a constant, sign extend to increase our chances 2291 // of being able to use a .vi instruction. ANY_EXTEND would become a 2292 // a zero extend and the simm5 check in isel would fail. 2293 // FIXME: Should we ignore the upper bits in isel instead? 2294 unsigned ExtOpc = 2295 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2296 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2297 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2298 // If VL is 1 and the scalar value won't benefit from immediate, we could 2299 // use vmv.s.x. 2300 if (isOneConstant(VL) && 2301 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2302 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2303 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2304 } 2305 2306 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2307 "Unexpected scalar for splat lowering!"); 2308 2309 if (isOneConstant(VL) && isNullConstant(Scalar)) 2310 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2311 DAG.getConstant(0, DL, XLenVT), VL); 2312 2313 // Otherwise use the more complicated splatting algorithm. 2314 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2315 } 2316 2317 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2318 const RISCVSubtarget &Subtarget) { 2319 // We need to be able to widen elements to the next larger integer type. 2320 if (VT.getScalarSizeInBits() >= Subtarget.getELEN()) 2321 return false; 2322 2323 int Size = Mask.size(); 2324 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2325 2326 int Srcs[] = {-1, -1}; 2327 for (int i = 0; i != Size; ++i) { 2328 // Ignore undef elements. 2329 if (Mask[i] < 0) 2330 continue; 2331 2332 // Is this an even or odd element. 2333 int Pol = i % 2; 2334 2335 // Ensure we consistently use the same source for this element polarity. 2336 int Src = Mask[i] / Size; 2337 if (Srcs[Pol] < 0) 2338 Srcs[Pol] = Src; 2339 if (Srcs[Pol] != Src) 2340 return false; 2341 2342 // Make sure the element within the source is appropriate for this element 2343 // in the destination. 2344 int Elt = Mask[i] % Size; 2345 if (Elt != i / 2) 2346 return false; 2347 } 2348 2349 // We need to find a source for each polarity and they can't be the same. 2350 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2351 return false; 2352 2353 // Swap the sources if the second source was in the even polarity. 2354 SwapSources = Srcs[0] > Srcs[1]; 2355 2356 return true; 2357 } 2358 2359 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2360 /// and then extract the original number of elements from the rotated result. 2361 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2362 /// returned rotation amount is for a rotate right, where elements move from 2363 /// higher elements to lower elements. \p LoSrc indicates the first source 2364 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2365 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2366 /// 0 or 1 if a rotation is found. 2367 /// 2368 /// NOTE: We talk about rotate to the right which matches how bit shift and 2369 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2370 /// and the table below write vectors with the lowest elements on the left. 2371 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2372 int Size = Mask.size(); 2373 2374 // We need to detect various ways of spelling a rotation: 2375 // [11, 12, 13, 14, 15, 0, 1, 2] 2376 // [-1, 12, 13, 14, -1, -1, 1, -1] 2377 // [-1, -1, -1, -1, -1, -1, 1, 2] 2378 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2379 // [-1, 4, 5, 6, -1, -1, 9, -1] 2380 // [-1, 4, 5, 6, -1, -1, -1, -1] 2381 int Rotation = 0; 2382 LoSrc = -1; 2383 HiSrc = -1; 2384 for (int i = 0; i != Size; ++i) { 2385 int M = Mask[i]; 2386 if (M < 0) 2387 continue; 2388 2389 // Determine where a rotate vector would have started. 2390 int StartIdx = i - (M % Size); 2391 // The identity rotation isn't interesting, stop. 2392 if (StartIdx == 0) 2393 return -1; 2394 2395 // If we found the tail of a vector the rotation must be the missing 2396 // front. If we found the head of a vector, it must be how much of the 2397 // head. 2398 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2399 2400 if (Rotation == 0) 2401 Rotation = CandidateRotation; 2402 else if (Rotation != CandidateRotation) 2403 // The rotations don't match, so we can't match this mask. 2404 return -1; 2405 2406 // Compute which value this mask is pointing at. 2407 int MaskSrc = M < Size ? 0 : 1; 2408 2409 // Compute which of the two target values this index should be assigned to. 2410 // This reflects whether the high elements are remaining or the low elemnts 2411 // are remaining. 2412 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2413 2414 // Either set up this value if we've not encountered it before, or check 2415 // that it remains consistent. 2416 if (TargetSrc < 0) 2417 TargetSrc = MaskSrc; 2418 else if (TargetSrc != MaskSrc) 2419 // This may be a rotation, but it pulls from the inputs in some 2420 // unsupported interleaving. 2421 return -1; 2422 } 2423 2424 // Check that we successfully analyzed the mask, and normalize the results. 2425 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2426 assert((LoSrc >= 0 || HiSrc >= 0) && 2427 "Failed to find a rotated input vector!"); 2428 2429 return Rotation; 2430 } 2431 2432 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2433 const RISCVSubtarget &Subtarget) { 2434 SDValue V1 = Op.getOperand(0); 2435 SDValue V2 = Op.getOperand(1); 2436 SDLoc DL(Op); 2437 MVT XLenVT = Subtarget.getXLenVT(); 2438 MVT VT = Op.getSimpleValueType(); 2439 unsigned NumElts = VT.getVectorNumElements(); 2440 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2441 2442 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2443 2444 SDValue TrueMask, VL; 2445 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2446 2447 if (SVN->isSplat()) { 2448 const int Lane = SVN->getSplatIndex(); 2449 if (Lane >= 0) { 2450 MVT SVT = VT.getVectorElementType(); 2451 2452 // Turn splatted vector load into a strided load with an X0 stride. 2453 SDValue V = V1; 2454 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2455 // with undef. 2456 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2457 int Offset = Lane; 2458 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2459 int OpElements = 2460 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2461 V = V.getOperand(Offset / OpElements); 2462 Offset %= OpElements; 2463 } 2464 2465 // We need to ensure the load isn't atomic or volatile. 2466 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2467 auto *Ld = cast<LoadSDNode>(V); 2468 Offset *= SVT.getStoreSize(); 2469 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2470 TypeSize::Fixed(Offset), DL); 2471 2472 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2473 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2474 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2475 SDValue IntID = 2476 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2477 SDValue Ops[] = {Ld->getChain(), 2478 IntID, 2479 DAG.getUNDEF(ContainerVT), 2480 NewAddr, 2481 DAG.getRegister(RISCV::X0, XLenVT), 2482 VL}; 2483 SDValue NewLoad = DAG.getMemIntrinsicNode( 2484 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2485 DAG.getMachineFunction().getMachineMemOperand( 2486 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2487 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2488 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2489 } 2490 2491 // Otherwise use a scalar load and splat. This will give the best 2492 // opportunity to fold a splat into the operation. ISel can turn it into 2493 // the x0 strided load if we aren't able to fold away the select. 2494 if (SVT.isFloatingPoint()) 2495 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2496 Ld->getPointerInfo().getWithOffset(Offset), 2497 Ld->getOriginalAlign(), 2498 Ld->getMemOperand()->getFlags()); 2499 else 2500 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2501 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2502 Ld->getOriginalAlign(), 2503 Ld->getMemOperand()->getFlags()); 2504 DAG.makeEquivalentMemoryOrdering(Ld, V); 2505 2506 unsigned Opc = 2507 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2508 SDValue Splat = 2509 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2510 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2511 } 2512 2513 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2514 assert(Lane < (int)NumElts && "Unexpected lane!"); 2515 SDValue Gather = 2516 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2517 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2518 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2519 } 2520 } 2521 2522 ArrayRef<int> Mask = SVN->getMask(); 2523 2524 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2525 // be undef which can be handled with a single SLIDEDOWN/UP. 2526 int LoSrc, HiSrc; 2527 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2528 if (Rotation > 0) { 2529 SDValue LoV, HiV; 2530 if (LoSrc >= 0) { 2531 LoV = LoSrc == 0 ? V1 : V2; 2532 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2533 } 2534 if (HiSrc >= 0) { 2535 HiV = HiSrc == 0 ? V1 : V2; 2536 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2537 } 2538 2539 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2540 // to slide LoV up by (NumElts - Rotation). 2541 unsigned InvRotate = NumElts - Rotation; 2542 2543 SDValue Res = DAG.getUNDEF(ContainerVT); 2544 if (HiV) { 2545 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2546 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2547 // causes multiple vsetvlis in some test cases such as lowering 2548 // reduce.mul 2549 SDValue DownVL = VL; 2550 if (LoV) 2551 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2552 Res = 2553 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2554 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2555 } 2556 if (LoV) 2557 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2558 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2559 2560 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2561 } 2562 2563 // Detect an interleave shuffle and lower to 2564 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2565 bool SwapSources; 2566 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2567 // Swap sources if needed. 2568 if (SwapSources) 2569 std::swap(V1, V2); 2570 2571 // Extract the lower half of the vectors. 2572 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2573 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2574 DAG.getConstant(0, DL, XLenVT)); 2575 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2576 DAG.getConstant(0, DL, XLenVT)); 2577 2578 // Double the element width and halve the number of elements in an int type. 2579 unsigned EltBits = VT.getScalarSizeInBits(); 2580 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2581 MVT WideIntVT = 2582 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2583 // Convert this to a scalable vector. We need to base this on the 2584 // destination size to ensure there's always a type with a smaller LMUL. 2585 MVT WideIntContainerVT = 2586 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2587 2588 // Convert sources to scalable vectors with the same element count as the 2589 // larger type. 2590 MVT HalfContainerVT = MVT::getVectorVT( 2591 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2592 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2593 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2594 2595 // Cast sources to integer. 2596 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2597 MVT IntHalfVT = 2598 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2599 V1 = DAG.getBitcast(IntHalfVT, V1); 2600 V2 = DAG.getBitcast(IntHalfVT, V2); 2601 2602 // Freeze V2 since we use it twice and we need to be sure that the add and 2603 // multiply see the same value. 2604 V2 = DAG.getFreeze(V2); 2605 2606 // Recreate TrueMask using the widened type's element count. 2607 TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG); 2608 2609 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2610 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2611 V2, TrueMask, VL); 2612 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2613 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2614 DAG.getUNDEF(IntHalfVT), 2615 DAG.getAllOnesConstant(DL, XLenVT)); 2616 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2617 V2, Multiplier, TrueMask, VL); 2618 // Add the new copies to our previous addition giving us 2^eltbits copies of 2619 // V2. This is equivalent to shifting V2 left by eltbits. This should 2620 // combine with the vwmulu.vv above to form vwmaccu.vv. 2621 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2622 TrueMask, VL); 2623 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2624 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2625 // vector VT. 2626 ContainerVT = 2627 MVT::getVectorVT(VT.getVectorElementType(), 2628 WideIntContainerVT.getVectorElementCount() * 2); 2629 Add = DAG.getBitcast(ContainerVT, Add); 2630 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2631 } 2632 2633 // Detect shuffles which can be re-expressed as vector selects; these are 2634 // shuffles in which each element in the destination is taken from an element 2635 // at the corresponding index in either source vectors. 2636 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2637 int MaskIndex = MaskIdx.value(); 2638 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2639 }); 2640 2641 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2642 2643 SmallVector<SDValue> MaskVals; 2644 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2645 // merged with a second vrgather. 2646 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2647 2648 // By default we preserve the original operand order, and use a mask to 2649 // select LHS as true and RHS as false. However, since RVV vector selects may 2650 // feature splats but only on the LHS, we may choose to invert our mask and 2651 // instead select between RHS and LHS. 2652 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2653 bool InvertMask = IsSelect == SwapOps; 2654 2655 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2656 // half. 2657 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2658 2659 // Now construct the mask that will be used by the vselect or blended 2660 // vrgather operation. For vrgathers, construct the appropriate indices into 2661 // each vector. 2662 for (int MaskIndex : Mask) { 2663 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2664 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2665 if (!IsSelect) { 2666 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2667 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2668 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2669 : DAG.getUNDEF(XLenVT)); 2670 GatherIndicesRHS.push_back( 2671 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2672 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2673 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2674 ++LHSIndexCounts[MaskIndex]; 2675 if (!IsLHSOrUndefIndex) 2676 ++RHSIndexCounts[MaskIndex - NumElts]; 2677 } 2678 } 2679 2680 if (SwapOps) { 2681 std::swap(V1, V2); 2682 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2683 } 2684 2685 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2686 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2687 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2688 2689 if (IsSelect) 2690 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2691 2692 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2693 // On such a large vector we're unable to use i8 as the index type. 2694 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2695 // may involve vector splitting if we're already at LMUL=8, or our 2696 // user-supplied maximum fixed-length LMUL. 2697 return SDValue(); 2698 } 2699 2700 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2701 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2702 MVT IndexVT = VT.changeTypeToInteger(); 2703 // Since we can't introduce illegal index types at this stage, use i16 and 2704 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2705 // than XLenVT. 2706 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2707 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2708 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2709 } 2710 2711 MVT IndexContainerVT = 2712 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2713 2714 SDValue Gather; 2715 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2716 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2717 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2718 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2719 Subtarget); 2720 } else { 2721 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2722 // If only one index is used, we can use a "splat" vrgather. 2723 // TODO: We can splat the most-common index and fix-up any stragglers, if 2724 // that's beneficial. 2725 if (LHSIndexCounts.size() == 1) { 2726 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2727 Gather = 2728 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2729 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2730 } else { 2731 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2732 LHSIndices = 2733 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2734 2735 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2736 TrueMask, VL); 2737 } 2738 } 2739 2740 // If a second vector operand is used by this shuffle, blend it in with an 2741 // additional vrgather. 2742 if (!V2.isUndef()) { 2743 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2744 // If only one index is used, we can use a "splat" vrgather. 2745 // TODO: We can splat the most-common index and fix-up any stragglers, if 2746 // that's beneficial. 2747 if (RHSIndexCounts.size() == 1) { 2748 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2749 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2750 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2751 } else { 2752 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2753 RHSIndices = 2754 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2755 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2756 VL); 2757 } 2758 2759 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2760 SelectMask = 2761 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2762 2763 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2764 Gather, VL); 2765 } 2766 2767 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2768 } 2769 2770 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2771 // Support splats for any type. These should type legalize well. 2772 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2773 return true; 2774 2775 // Only support legal VTs for other shuffles for now. 2776 if (!isTypeLegal(VT)) 2777 return false; 2778 2779 MVT SVT = VT.getSimpleVT(); 2780 2781 bool SwapSources; 2782 int LoSrc, HiSrc; 2783 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2784 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2785 } 2786 2787 static SDValue getRVVFPExtendOrRound(SDValue Op, MVT VT, MVT ContainerVT, 2788 SDLoc DL, SelectionDAG &DAG, 2789 const RISCVSubtarget &Subtarget) { 2790 if (VT.isScalableVector()) 2791 return DAG.getFPExtendOrRound(Op, DL, VT); 2792 assert(VT.isFixedLengthVector() && 2793 "Unexpected value type for RVV FP extend/round lowering"); 2794 SDValue Mask, VL; 2795 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2796 unsigned RVVOpc = ContainerVT.bitsGT(Op.getSimpleValueType()) 2797 ? RISCVISD::FP_EXTEND_VL 2798 : RISCVISD::FP_ROUND_VL; 2799 return DAG.getNode(RVVOpc, DL, ContainerVT, Op, Mask, VL); 2800 } 2801 2802 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2803 // the exponent. 2804 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2805 MVT VT = Op.getSimpleValueType(); 2806 unsigned EltSize = VT.getScalarSizeInBits(); 2807 SDValue Src = Op.getOperand(0); 2808 SDLoc DL(Op); 2809 2810 // We need a FP type that can represent the value. 2811 // TODO: Use f16 for i8 when possible? 2812 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2813 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2814 2815 // Legal types should have been checked in the RISCVTargetLowering 2816 // constructor. 2817 // TODO: Splitting may make sense in some cases. 2818 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2819 "Expected legal float type!"); 2820 2821 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2822 // The trailing zero count is equal to log2 of this single bit value. 2823 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2824 SDValue Neg = 2825 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2826 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2827 } 2828 2829 // We have a legal FP type, convert to it. 2830 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2831 // Bitcast to integer and shift the exponent to the LSB. 2832 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2833 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2834 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2835 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2836 DAG.getConstant(ShiftAmt, DL, IntVT)); 2837 // Truncate back to original type to allow vnsrl. 2838 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2839 // The exponent contains log2 of the value in biased form. 2840 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2841 2842 // For trailing zeros, we just need to subtract the bias. 2843 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2844 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2845 DAG.getConstant(ExponentBias, DL, VT)); 2846 2847 // For leading zeros, we need to remove the bias and convert from log2 to 2848 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2849 unsigned Adjust = ExponentBias + (EltSize - 1); 2850 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2851 } 2852 2853 // While RVV has alignment restrictions, we should always be able to load as a 2854 // legal equivalently-sized byte-typed vector instead. This method is 2855 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2856 // the load is already correctly-aligned, it returns SDValue(). 2857 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2858 SelectionDAG &DAG) const { 2859 auto *Load = cast<LoadSDNode>(Op); 2860 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2861 2862 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2863 Load->getMemoryVT(), 2864 *Load->getMemOperand())) 2865 return SDValue(); 2866 2867 SDLoc DL(Op); 2868 MVT VT = Op.getSimpleValueType(); 2869 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2870 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2871 "Unexpected unaligned RVV load type"); 2872 MVT NewVT = 2873 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2874 assert(NewVT.isValid() && 2875 "Expecting equally-sized RVV vector types to be legal"); 2876 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2877 Load->getPointerInfo(), Load->getOriginalAlign(), 2878 Load->getMemOperand()->getFlags()); 2879 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2880 } 2881 2882 // While RVV has alignment restrictions, we should always be able to store as a 2883 // legal equivalently-sized byte-typed vector instead. This method is 2884 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2885 // returns SDValue() if the store is already correctly aligned. 2886 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2887 SelectionDAG &DAG) const { 2888 auto *Store = cast<StoreSDNode>(Op); 2889 assert(Store && Store->getValue().getValueType().isVector() && 2890 "Expected vector store"); 2891 2892 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2893 Store->getMemoryVT(), 2894 *Store->getMemOperand())) 2895 return SDValue(); 2896 2897 SDLoc DL(Op); 2898 SDValue StoredVal = Store->getValue(); 2899 MVT VT = StoredVal.getSimpleValueType(); 2900 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2901 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2902 "Unexpected unaligned RVV store type"); 2903 MVT NewVT = 2904 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2905 assert(NewVT.isValid() && 2906 "Expecting equally-sized RVV vector types to be legal"); 2907 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2908 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2909 Store->getPointerInfo(), Store->getOriginalAlign(), 2910 Store->getMemOperand()->getFlags()); 2911 } 2912 2913 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 2914 SelectionDAG &DAG) const { 2915 switch (Op.getOpcode()) { 2916 default: 2917 report_fatal_error("unimplemented operand"); 2918 case ISD::GlobalAddress: 2919 return lowerGlobalAddress(Op, DAG); 2920 case ISD::BlockAddress: 2921 return lowerBlockAddress(Op, DAG); 2922 case ISD::ConstantPool: 2923 return lowerConstantPool(Op, DAG); 2924 case ISD::JumpTable: 2925 return lowerJumpTable(Op, DAG); 2926 case ISD::GlobalTLSAddress: 2927 return lowerGlobalTLSAddress(Op, DAG); 2928 case ISD::SELECT: 2929 return lowerSELECT(Op, DAG); 2930 case ISD::BRCOND: 2931 return lowerBRCOND(Op, DAG); 2932 case ISD::VASTART: 2933 return lowerVASTART(Op, DAG); 2934 case ISD::FRAMEADDR: 2935 return lowerFRAMEADDR(Op, DAG); 2936 case ISD::RETURNADDR: 2937 return lowerRETURNADDR(Op, DAG); 2938 case ISD::SHL_PARTS: 2939 return lowerShiftLeftParts(Op, DAG); 2940 case ISD::SRA_PARTS: 2941 return lowerShiftRightParts(Op, DAG, true); 2942 case ISD::SRL_PARTS: 2943 return lowerShiftRightParts(Op, DAG, false); 2944 case ISD::BITCAST: { 2945 SDLoc DL(Op); 2946 EVT VT = Op.getValueType(); 2947 SDValue Op0 = Op.getOperand(0); 2948 EVT Op0VT = Op0.getValueType(); 2949 MVT XLenVT = Subtarget.getXLenVT(); 2950 if (VT.isFixedLengthVector()) { 2951 // We can handle fixed length vector bitcasts with a simple replacement 2952 // in isel. 2953 if (Op0VT.isFixedLengthVector()) 2954 return Op; 2955 // When bitcasting from scalar to fixed-length vector, insert the scalar 2956 // into a one-element vector of the result type, and perform a vector 2957 // bitcast. 2958 if (!Op0VT.isVector()) { 2959 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 2960 if (!isTypeLegal(BVT)) 2961 return SDValue(); 2962 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 2963 DAG.getUNDEF(BVT), Op0, 2964 DAG.getConstant(0, DL, XLenVT))); 2965 } 2966 return SDValue(); 2967 } 2968 // Custom-legalize bitcasts from fixed-length vector types to scalar types 2969 // thus: bitcast the vector to a one-element vector type whose element type 2970 // is the same as the result type, and extract the first element. 2971 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 2972 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 2973 if (!isTypeLegal(BVT)) 2974 return SDValue(); 2975 SDValue BVec = DAG.getBitcast(BVT, Op0); 2976 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 2977 DAG.getConstant(0, DL, XLenVT)); 2978 } 2979 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 2980 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 2981 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 2982 return FPConv; 2983 } 2984 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 2985 Subtarget.hasStdExtF()) { 2986 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 2987 SDValue FPConv = 2988 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 2989 return FPConv; 2990 } 2991 return SDValue(); 2992 } 2993 case ISD::INTRINSIC_WO_CHAIN: 2994 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 2995 case ISD::INTRINSIC_W_CHAIN: 2996 return LowerINTRINSIC_W_CHAIN(Op, DAG); 2997 case ISD::INTRINSIC_VOID: 2998 return LowerINTRINSIC_VOID(Op, DAG); 2999 case ISD::BSWAP: 3000 case ISD::BITREVERSE: { 3001 MVT VT = Op.getSimpleValueType(); 3002 SDLoc DL(Op); 3003 if (Subtarget.hasStdExtZbp()) { 3004 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3005 // Start with the maximum immediate value which is the bitwidth - 1. 3006 unsigned Imm = VT.getSizeInBits() - 1; 3007 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3008 if (Op.getOpcode() == ISD::BSWAP) 3009 Imm &= ~0x7U; 3010 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3011 DAG.getConstant(Imm, DL, VT)); 3012 } 3013 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3014 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3015 // Expand bitreverse to a bswap(rev8) followed by brev8. 3016 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3017 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3018 // as brev8 by an isel pattern. 3019 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3020 DAG.getConstant(7, DL, VT)); 3021 } 3022 case ISD::FSHL: 3023 case ISD::FSHR: { 3024 MVT VT = Op.getSimpleValueType(); 3025 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3026 SDLoc DL(Op); 3027 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3028 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3029 // accidentally setting the extra bit. 3030 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3031 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3032 DAG.getConstant(ShAmtWidth, DL, VT)); 3033 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3034 // instruction use different orders. fshl will return its first operand for 3035 // shift of zero, fshr will return its second operand. fsl and fsr both 3036 // return rs1 so the ISD nodes need to have different operand orders. 3037 // Shift amount is in rs2. 3038 SDValue Op0 = Op.getOperand(0); 3039 SDValue Op1 = Op.getOperand(1); 3040 unsigned Opc = RISCVISD::FSL; 3041 if (Op.getOpcode() == ISD::FSHR) { 3042 std::swap(Op0, Op1); 3043 Opc = RISCVISD::FSR; 3044 } 3045 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3046 } 3047 case ISD::TRUNCATE: 3048 // Only custom-lower vector truncates 3049 if (!Op.getSimpleValueType().isVector()) 3050 return Op; 3051 return lowerVectorTruncLike(Op, DAG); 3052 case ISD::ANY_EXTEND: 3053 case ISD::ZERO_EXTEND: 3054 if (Op.getOperand(0).getValueType().isVector() && 3055 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3056 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3057 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3058 case ISD::SIGN_EXTEND: 3059 if (Op.getOperand(0).getValueType().isVector() && 3060 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3061 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3062 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3063 case ISD::SPLAT_VECTOR_PARTS: 3064 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3065 case ISD::INSERT_VECTOR_ELT: 3066 return lowerINSERT_VECTOR_ELT(Op, DAG); 3067 case ISD::EXTRACT_VECTOR_ELT: 3068 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3069 case ISD::VSCALE: { 3070 MVT VT = Op.getSimpleValueType(); 3071 SDLoc DL(Op); 3072 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3073 // We define our scalable vector types for lmul=1 to use a 64 bit known 3074 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3075 // vscale as VLENB / 8. 3076 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3077 if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock) 3078 report_fatal_error("Support for VLEN==32 is incomplete."); 3079 if (isa<ConstantSDNode>(Op.getOperand(0))) { 3080 // We assume VLENB is a multiple of 8. We manually choose the best shift 3081 // here because SimplifyDemandedBits isn't always able to simplify it. 3082 uint64_t Val = Op.getConstantOperandVal(0); 3083 if (isPowerOf2_64(Val)) { 3084 uint64_t Log2 = Log2_64(Val); 3085 if (Log2 < 3) 3086 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3087 DAG.getConstant(3 - Log2, DL, VT)); 3088 if (Log2 > 3) 3089 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3090 DAG.getConstant(Log2 - 3, DL, VT)); 3091 return VLENB; 3092 } 3093 // If the multiplier is a multiple of 8, scale it down to avoid needing 3094 // to shift the VLENB value. 3095 if ((Val % 8) == 0) 3096 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3097 DAG.getConstant(Val / 8, DL, VT)); 3098 } 3099 3100 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3101 DAG.getConstant(3, DL, VT)); 3102 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3103 } 3104 case ISD::FPOWI: { 3105 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3106 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3107 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3108 Op.getOperand(1).getValueType() == MVT::i32) { 3109 SDLoc DL(Op); 3110 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3111 SDValue Powi = 3112 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3113 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3114 DAG.getIntPtrConstant(0, DL)); 3115 } 3116 return SDValue(); 3117 } 3118 case ISD::FP_EXTEND: { 3119 // RVV can only do fp_extend to types double the size as the source. We 3120 // custom-lower f16->f64 extensions to two hops of ISD::FP_EXTEND, going 3121 // via f32. 3122 SDLoc DL(Op); 3123 MVT VT = Op.getSimpleValueType(); 3124 SDValue Src = Op.getOperand(0); 3125 MVT SrcVT = Src.getSimpleValueType(); 3126 3127 // Prepare any fixed-length vector operands. 3128 MVT ContainerVT = VT; 3129 if (SrcVT.isFixedLengthVector()) { 3130 ContainerVT = getContainerForFixedLengthVector(VT); 3131 MVT SrcContainerVT = 3132 ContainerVT.changeVectorElementType(SrcVT.getVectorElementType()); 3133 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3134 } 3135 3136 if (!VT.isVector() || VT.getVectorElementType() != MVT::f64 || 3137 SrcVT.getVectorElementType() != MVT::f16) { 3138 // For scalable vectors, we only need to close the gap between 3139 // vXf16->vXf64. 3140 if (!VT.isFixedLengthVector()) 3141 return Op; 3142 // For fixed-length vectors, lower the FP_EXTEND to a custom "VL" version. 3143 Src = getRVVFPExtendOrRound(Src, VT, ContainerVT, DL, DAG, Subtarget); 3144 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3145 } 3146 3147 MVT InterVT = VT.changeVectorElementType(MVT::f32); 3148 MVT InterContainerVT = ContainerVT.changeVectorElementType(MVT::f32); 3149 SDValue IntermediateExtend = getRVVFPExtendOrRound( 3150 Src, InterVT, InterContainerVT, DL, DAG, Subtarget); 3151 3152 SDValue Extend = getRVVFPExtendOrRound(IntermediateExtend, VT, ContainerVT, 3153 DL, DAG, Subtarget); 3154 if (VT.isFixedLengthVector()) 3155 return convertFromScalableVector(VT, Extend, DAG, Subtarget); 3156 return Extend; 3157 } 3158 case ISD::FP_ROUND: 3159 if (!Op.getValueType().isVector()) 3160 return Op; 3161 return lowerVectorFPRoundLike(Op, DAG); 3162 case ISD::FP_TO_SINT: 3163 case ISD::FP_TO_UINT: 3164 case ISD::SINT_TO_FP: 3165 case ISD::UINT_TO_FP: { 3166 // RVV can only do fp<->int conversions to types half/double the size as 3167 // the source. We custom-lower any conversions that do two hops into 3168 // sequences. 3169 MVT VT = Op.getSimpleValueType(); 3170 if (!VT.isVector()) 3171 return Op; 3172 SDLoc DL(Op); 3173 SDValue Src = Op.getOperand(0); 3174 MVT EltVT = VT.getVectorElementType(); 3175 MVT SrcVT = Src.getSimpleValueType(); 3176 MVT SrcEltVT = SrcVT.getVectorElementType(); 3177 unsigned EltSize = EltVT.getSizeInBits(); 3178 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3179 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3180 "Unexpected vector element types"); 3181 3182 bool IsInt2FP = SrcEltVT.isInteger(); 3183 // Widening conversions 3184 if (EltSize > (2 * SrcEltSize)) { 3185 if (IsInt2FP) { 3186 // Do a regular integer sign/zero extension then convert to float. 3187 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), 3188 VT.getVectorElementCount()); 3189 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3190 ? ISD::ZERO_EXTEND 3191 : ISD::SIGN_EXTEND; 3192 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3193 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3194 } 3195 // FP2Int 3196 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3197 // Do one doubling fp_extend then complete the operation by converting 3198 // to int. 3199 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3200 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3201 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3202 } 3203 3204 // Narrowing conversions 3205 if (SrcEltSize > (2 * EltSize)) { 3206 if (IsInt2FP) { 3207 // One narrowing int_to_fp, then an fp_round. 3208 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3209 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3210 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3211 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3212 } 3213 // FP2Int 3214 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3215 // representable by the integer, the result is poison. 3216 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 3217 VT.getVectorElementCount()); 3218 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3219 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3220 } 3221 3222 // Scalable vectors can exit here. Patterns will handle equally-sized 3223 // conversions halving/doubling ones. 3224 if (!VT.isFixedLengthVector()) 3225 return Op; 3226 3227 // For fixed-length vectors we lower to a custom "VL" node. 3228 unsigned RVVOpc = 0; 3229 switch (Op.getOpcode()) { 3230 default: 3231 llvm_unreachable("Impossible opcode"); 3232 case ISD::FP_TO_SINT: 3233 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3234 break; 3235 case ISD::FP_TO_UINT: 3236 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3237 break; 3238 case ISD::SINT_TO_FP: 3239 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3240 break; 3241 case ISD::UINT_TO_FP: 3242 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3243 break; 3244 } 3245 3246 MVT ContainerVT, SrcContainerVT; 3247 // Derive the reference container type from the larger vector type. 3248 if (SrcEltSize > EltSize) { 3249 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3250 ContainerVT = 3251 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3252 } else { 3253 ContainerVT = getContainerForFixedLengthVector(VT); 3254 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3255 } 3256 3257 SDValue Mask, VL; 3258 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3259 3260 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3261 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3262 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3263 } 3264 case ISD::FP_TO_SINT_SAT: 3265 case ISD::FP_TO_UINT_SAT: 3266 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3267 case ISD::FTRUNC: 3268 case ISD::FCEIL: 3269 case ISD::FFLOOR: 3270 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3271 case ISD::FROUND: 3272 return lowerFROUND(Op, DAG); 3273 case ISD::VECREDUCE_ADD: 3274 case ISD::VECREDUCE_UMAX: 3275 case ISD::VECREDUCE_SMAX: 3276 case ISD::VECREDUCE_UMIN: 3277 case ISD::VECREDUCE_SMIN: 3278 return lowerVECREDUCE(Op, DAG); 3279 case ISD::VECREDUCE_AND: 3280 case ISD::VECREDUCE_OR: 3281 case ISD::VECREDUCE_XOR: 3282 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3283 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3284 return lowerVECREDUCE(Op, DAG); 3285 case ISD::VECREDUCE_FADD: 3286 case ISD::VECREDUCE_SEQ_FADD: 3287 case ISD::VECREDUCE_FMIN: 3288 case ISD::VECREDUCE_FMAX: 3289 return lowerFPVECREDUCE(Op, DAG); 3290 case ISD::VP_REDUCE_ADD: 3291 case ISD::VP_REDUCE_UMAX: 3292 case ISD::VP_REDUCE_SMAX: 3293 case ISD::VP_REDUCE_UMIN: 3294 case ISD::VP_REDUCE_SMIN: 3295 case ISD::VP_REDUCE_FADD: 3296 case ISD::VP_REDUCE_SEQ_FADD: 3297 case ISD::VP_REDUCE_FMIN: 3298 case ISD::VP_REDUCE_FMAX: 3299 return lowerVPREDUCE(Op, DAG); 3300 case ISD::VP_REDUCE_AND: 3301 case ISD::VP_REDUCE_OR: 3302 case ISD::VP_REDUCE_XOR: 3303 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3304 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3305 return lowerVPREDUCE(Op, DAG); 3306 case ISD::INSERT_SUBVECTOR: 3307 return lowerINSERT_SUBVECTOR(Op, DAG); 3308 case ISD::EXTRACT_SUBVECTOR: 3309 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3310 case ISD::STEP_VECTOR: 3311 return lowerSTEP_VECTOR(Op, DAG); 3312 case ISD::VECTOR_REVERSE: 3313 return lowerVECTOR_REVERSE(Op, DAG); 3314 case ISD::VECTOR_SPLICE: 3315 return lowerVECTOR_SPLICE(Op, DAG); 3316 case ISD::BUILD_VECTOR: 3317 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3318 case ISD::SPLAT_VECTOR: 3319 if (Op.getValueType().getVectorElementType() == MVT::i1) 3320 return lowerVectorMaskSplat(Op, DAG); 3321 return SDValue(); 3322 case ISD::VECTOR_SHUFFLE: 3323 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3324 case ISD::CONCAT_VECTORS: { 3325 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3326 // better than going through the stack, as the default expansion does. 3327 SDLoc DL(Op); 3328 MVT VT = Op.getSimpleValueType(); 3329 unsigned NumOpElts = 3330 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3331 SDValue Vec = DAG.getUNDEF(VT); 3332 for (const auto &OpIdx : enumerate(Op->ops())) { 3333 SDValue SubVec = OpIdx.value(); 3334 // Don't insert undef subvectors. 3335 if (SubVec.isUndef()) 3336 continue; 3337 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3338 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3339 } 3340 return Vec; 3341 } 3342 case ISD::LOAD: 3343 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3344 return V; 3345 if (Op.getValueType().isFixedLengthVector()) 3346 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3347 return Op; 3348 case ISD::STORE: 3349 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3350 return V; 3351 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3352 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3353 return Op; 3354 case ISD::MLOAD: 3355 case ISD::VP_LOAD: 3356 return lowerMaskedLoad(Op, DAG); 3357 case ISD::MSTORE: 3358 case ISD::VP_STORE: 3359 return lowerMaskedStore(Op, DAG); 3360 case ISD::SETCC: 3361 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3362 case ISD::ADD: 3363 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3364 case ISD::SUB: 3365 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3366 case ISD::MUL: 3367 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3368 case ISD::MULHS: 3369 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3370 case ISD::MULHU: 3371 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3372 case ISD::AND: 3373 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3374 RISCVISD::AND_VL); 3375 case ISD::OR: 3376 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3377 RISCVISD::OR_VL); 3378 case ISD::XOR: 3379 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3380 RISCVISD::XOR_VL); 3381 case ISD::SDIV: 3382 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3383 case ISD::SREM: 3384 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3385 case ISD::UDIV: 3386 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3387 case ISD::UREM: 3388 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3389 case ISD::SHL: 3390 case ISD::SRA: 3391 case ISD::SRL: 3392 if (Op.getSimpleValueType().isFixedLengthVector()) 3393 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3394 // This can be called for an i32 shift amount that needs to be promoted. 3395 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3396 "Unexpected custom legalisation"); 3397 return SDValue(); 3398 case ISD::SADDSAT: 3399 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3400 case ISD::UADDSAT: 3401 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3402 case ISD::SSUBSAT: 3403 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3404 case ISD::USUBSAT: 3405 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3406 case ISD::FADD: 3407 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3408 case ISD::FSUB: 3409 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3410 case ISD::FMUL: 3411 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3412 case ISD::FDIV: 3413 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3414 case ISD::FNEG: 3415 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3416 case ISD::FABS: 3417 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3418 case ISD::FSQRT: 3419 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3420 case ISD::FMA: 3421 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3422 case ISD::SMIN: 3423 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3424 case ISD::SMAX: 3425 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3426 case ISD::UMIN: 3427 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3428 case ISD::UMAX: 3429 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3430 case ISD::FMINNUM: 3431 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3432 case ISD::FMAXNUM: 3433 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3434 case ISD::ABS: 3435 return lowerABS(Op, DAG); 3436 case ISD::CTLZ_ZERO_UNDEF: 3437 case ISD::CTTZ_ZERO_UNDEF: 3438 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3439 case ISD::VSELECT: 3440 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3441 case ISD::FCOPYSIGN: 3442 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3443 case ISD::MGATHER: 3444 case ISD::VP_GATHER: 3445 return lowerMaskedGather(Op, DAG); 3446 case ISD::MSCATTER: 3447 case ISD::VP_SCATTER: 3448 return lowerMaskedScatter(Op, DAG); 3449 case ISD::FLT_ROUNDS_: 3450 return lowerGET_ROUNDING(Op, DAG); 3451 case ISD::SET_ROUNDING: 3452 return lowerSET_ROUNDING(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_SEXT: 3496 case ISD::VP_ZEXT: 3497 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3498 return lowerVPExtMaskOp(Op, DAG); 3499 return lowerVPOp(Op, DAG, 3500 Op.getOpcode() == ISD::VP_SEXT ? RISCVISD::VSEXT_VL 3501 : RISCVISD::VZEXT_VL); 3502 case ISD::VP_TRUNC: 3503 return lowerVectorTruncLike(Op, DAG); 3504 case ISD::VP_FP_ROUND: 3505 return lowerVectorFPRoundLike(Op, DAG); 3506 case ISD::VP_FPTOSI: 3507 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL); 3508 case ISD::VP_FPTOUI: 3509 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL); 3510 case ISD::VP_SITOFP: 3511 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL); 3512 case ISD::VP_UITOFP: 3513 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL); 3514 case ISD::VP_SETCC: 3515 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3516 return lowerVPSetCCMaskOp(Op, DAG); 3517 return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL); 3518 } 3519 } 3520 3521 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3522 SelectionDAG &DAG, unsigned Flags) { 3523 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3524 } 3525 3526 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3527 SelectionDAG &DAG, unsigned Flags) { 3528 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3529 Flags); 3530 } 3531 3532 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3533 SelectionDAG &DAG, unsigned Flags) { 3534 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3535 N->getOffset(), Flags); 3536 } 3537 3538 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3539 SelectionDAG &DAG, unsigned Flags) { 3540 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3541 } 3542 3543 template <class NodeTy> 3544 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3545 bool IsLocal) const { 3546 SDLoc DL(N); 3547 EVT Ty = getPointerTy(DAG.getDataLayout()); 3548 3549 if (isPositionIndependent()) { 3550 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3551 if (IsLocal) 3552 // Use PC-relative addressing to access the symbol. This generates the 3553 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3554 // %pcrel_lo(auipc)). 3555 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3556 3557 // Use PC-relative addressing to access the GOT for this symbol, then load 3558 // the address from the GOT. This generates the pattern (PseudoLA sym), 3559 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3560 SDValue Load = 3561 SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3562 MachineFunction &MF = DAG.getMachineFunction(); 3563 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3564 MachinePointerInfo::getGOT(MF), 3565 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3566 MachineMemOperand::MOInvariant, 3567 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3568 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3569 return Load; 3570 } 3571 3572 switch (getTargetMachine().getCodeModel()) { 3573 default: 3574 report_fatal_error("Unsupported code model for lowering"); 3575 case CodeModel::Small: { 3576 // Generate a sequence for accessing addresses within the first 2 GiB of 3577 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3578 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3579 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3580 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3581 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3582 } 3583 case CodeModel::Medium: { 3584 // Generate a sequence for accessing addresses within any 2GiB range within 3585 // the address space. This generates the pattern (PseudoLLA sym), which 3586 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3587 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3588 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3589 } 3590 } 3591 } 3592 3593 template SDValue RISCVTargetLowering::getAddr<GlobalAddressSDNode>( 3594 GlobalAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3595 template SDValue RISCVTargetLowering::getAddr<BlockAddressSDNode>( 3596 BlockAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3597 template SDValue RISCVTargetLowering::getAddr<ConstantPoolSDNode>( 3598 ConstantPoolSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3599 template SDValue RISCVTargetLowering::getAddr<JumpTableSDNode>( 3600 JumpTableSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3601 3602 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3603 SelectionDAG &DAG) const { 3604 SDLoc DL(Op); 3605 EVT Ty = Op.getValueType(); 3606 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3607 int64_t Offset = N->getOffset(); 3608 MVT XLenVT = Subtarget.getXLenVT(); 3609 3610 const GlobalValue *GV = N->getGlobal(); 3611 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3612 SDValue Addr = getAddr(N, DAG, IsLocal); 3613 3614 // In order to maximise the opportunity for common subexpression elimination, 3615 // emit a separate ADD node for the global address offset instead of folding 3616 // it in the global address node. Later peephole optimisations may choose to 3617 // fold it back in when profitable. 3618 if (Offset != 0) 3619 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3620 DAG.getConstant(Offset, DL, XLenVT)); 3621 return Addr; 3622 } 3623 3624 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3625 SelectionDAG &DAG) const { 3626 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3627 3628 return getAddr(N, DAG); 3629 } 3630 3631 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3632 SelectionDAG &DAG) const { 3633 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3634 3635 return getAddr(N, DAG); 3636 } 3637 3638 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3639 SelectionDAG &DAG) const { 3640 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3641 3642 return getAddr(N, DAG); 3643 } 3644 3645 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3646 SelectionDAG &DAG, 3647 bool UseGOT) const { 3648 SDLoc DL(N); 3649 EVT Ty = getPointerTy(DAG.getDataLayout()); 3650 const GlobalValue *GV = N->getGlobal(); 3651 MVT XLenVT = Subtarget.getXLenVT(); 3652 3653 if (UseGOT) { 3654 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3655 // load the address from the GOT and add the thread pointer. This generates 3656 // the pattern (PseudoLA_TLS_IE sym), which expands to 3657 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3658 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3659 SDValue Load = 3660 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3661 MachineFunction &MF = DAG.getMachineFunction(); 3662 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3663 MachinePointerInfo::getGOT(MF), 3664 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3665 MachineMemOperand::MOInvariant, 3666 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3667 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3668 3669 // Add the thread pointer. 3670 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3671 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3672 } 3673 3674 // Generate a sequence for accessing the address relative to the thread 3675 // pointer, with the appropriate adjustment for the thread pointer offset. 3676 // This generates the pattern 3677 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3678 SDValue AddrHi = 3679 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3680 SDValue AddrAdd = 3681 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3682 SDValue AddrLo = 3683 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3684 3685 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3686 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3687 SDValue MNAdd = SDValue( 3688 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3689 0); 3690 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3691 } 3692 3693 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3694 SelectionDAG &DAG) const { 3695 SDLoc DL(N); 3696 EVT Ty = getPointerTy(DAG.getDataLayout()); 3697 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3698 const GlobalValue *GV = N->getGlobal(); 3699 3700 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3701 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3702 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3703 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3704 SDValue Load = 3705 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3706 3707 // Prepare argument list to generate call. 3708 ArgListTy Args; 3709 ArgListEntry Entry; 3710 Entry.Node = Load; 3711 Entry.Ty = CallTy; 3712 Args.push_back(Entry); 3713 3714 // Setup call to __tls_get_addr. 3715 TargetLowering::CallLoweringInfo CLI(DAG); 3716 CLI.setDebugLoc(DL) 3717 .setChain(DAG.getEntryNode()) 3718 .setLibCallee(CallingConv::C, CallTy, 3719 DAG.getExternalSymbol("__tls_get_addr", Ty), 3720 std::move(Args)); 3721 3722 return LowerCallTo(CLI).first; 3723 } 3724 3725 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3726 SelectionDAG &DAG) const { 3727 SDLoc DL(Op); 3728 EVT Ty = Op.getValueType(); 3729 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3730 int64_t Offset = N->getOffset(); 3731 MVT XLenVT = Subtarget.getXLenVT(); 3732 3733 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3734 3735 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3736 CallingConv::GHC) 3737 report_fatal_error("In GHC calling convention TLS is not supported"); 3738 3739 SDValue Addr; 3740 switch (Model) { 3741 case TLSModel::LocalExec: 3742 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3743 break; 3744 case TLSModel::InitialExec: 3745 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3746 break; 3747 case TLSModel::LocalDynamic: 3748 case TLSModel::GeneralDynamic: 3749 Addr = getDynamicTLSAddr(N, DAG); 3750 break; 3751 } 3752 3753 // In order to maximise the opportunity for common subexpression elimination, 3754 // emit a separate ADD node for the global address offset instead of folding 3755 // it in the global address node. Later peephole optimisations may choose to 3756 // fold it back in when profitable. 3757 if (Offset != 0) 3758 return DAG.getNode(ISD::ADD, DL, Ty, Addr, 3759 DAG.getConstant(Offset, DL, XLenVT)); 3760 return Addr; 3761 } 3762 3763 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3764 SDValue CondV = Op.getOperand(0); 3765 SDValue TrueV = Op.getOperand(1); 3766 SDValue FalseV = Op.getOperand(2); 3767 SDLoc DL(Op); 3768 MVT VT = Op.getSimpleValueType(); 3769 MVT XLenVT = Subtarget.getXLenVT(); 3770 3771 // Lower vector SELECTs to VSELECTs by splatting the condition. 3772 if (VT.isVector()) { 3773 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3774 SDValue CondSplat = VT.isScalableVector() 3775 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3776 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3777 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3778 } 3779 3780 // If the result type is XLenVT and CondV is the output of a SETCC node 3781 // which also operated on XLenVT inputs, then merge the SETCC node into the 3782 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3783 // compare+branch instructions. i.e.: 3784 // (select (setcc lhs, rhs, cc), truev, falsev) 3785 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3786 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3787 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3788 SDValue LHS = CondV.getOperand(0); 3789 SDValue RHS = CondV.getOperand(1); 3790 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3791 ISD::CondCode CCVal = CC->get(); 3792 3793 // Special case for a select of 2 constants that have a diffence of 1. 3794 // Normally this is done by DAGCombine, but if the select is introduced by 3795 // type legalization or op legalization, we miss it. Restricting to SETLT 3796 // case for now because that is what signed saturating add/sub need. 3797 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3798 // but we would probably want to swap the true/false values if the condition 3799 // is SETGE/SETLE to avoid an XORI. 3800 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3801 CCVal == ISD::SETLT) { 3802 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3803 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3804 if (TrueVal - 1 == FalseVal) 3805 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3806 if (TrueVal + 1 == FalseVal) 3807 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3808 } 3809 3810 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3811 3812 SDValue TargetCC = DAG.getCondCode(CCVal); 3813 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3814 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3815 } 3816 3817 // Otherwise: 3818 // (select condv, truev, falsev) 3819 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3820 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3821 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3822 3823 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3824 3825 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3826 } 3827 3828 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3829 SDValue CondV = Op.getOperand(1); 3830 SDLoc DL(Op); 3831 MVT XLenVT = Subtarget.getXLenVT(); 3832 3833 if (CondV.getOpcode() == ISD::SETCC && 3834 CondV.getOperand(0).getValueType() == XLenVT) { 3835 SDValue LHS = CondV.getOperand(0); 3836 SDValue RHS = CondV.getOperand(1); 3837 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3838 3839 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3840 3841 SDValue TargetCC = DAG.getCondCode(CCVal); 3842 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3843 LHS, RHS, TargetCC, Op.getOperand(2)); 3844 } 3845 3846 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3847 CondV, DAG.getConstant(0, DL, XLenVT), 3848 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3849 } 3850 3851 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3852 MachineFunction &MF = DAG.getMachineFunction(); 3853 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3854 3855 SDLoc DL(Op); 3856 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3857 getPointerTy(MF.getDataLayout())); 3858 3859 // vastart just stores the address of the VarArgsFrameIndex slot into the 3860 // memory location argument. 3861 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3862 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3863 MachinePointerInfo(SV)); 3864 } 3865 3866 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3867 SelectionDAG &DAG) const { 3868 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3869 MachineFunction &MF = DAG.getMachineFunction(); 3870 MachineFrameInfo &MFI = MF.getFrameInfo(); 3871 MFI.setFrameAddressIsTaken(true); 3872 Register FrameReg = RI.getFrameRegister(MF); 3873 int XLenInBytes = Subtarget.getXLen() / 8; 3874 3875 EVT VT = Op.getValueType(); 3876 SDLoc DL(Op); 3877 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3878 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3879 while (Depth--) { 3880 int Offset = -(XLenInBytes * 2); 3881 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3882 DAG.getIntPtrConstant(Offset, DL)); 3883 FrameAddr = 3884 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3885 } 3886 return FrameAddr; 3887 } 3888 3889 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3890 SelectionDAG &DAG) const { 3891 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3892 MachineFunction &MF = DAG.getMachineFunction(); 3893 MachineFrameInfo &MFI = MF.getFrameInfo(); 3894 MFI.setReturnAddressIsTaken(true); 3895 MVT XLenVT = Subtarget.getXLenVT(); 3896 int XLenInBytes = Subtarget.getXLen() / 8; 3897 3898 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3899 return SDValue(); 3900 3901 EVT VT = Op.getValueType(); 3902 SDLoc DL(Op); 3903 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3904 if (Depth) { 3905 int Off = -XLenInBytes; 3906 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3907 SDValue Offset = DAG.getConstant(Off, DL, VT); 3908 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3909 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3910 MachinePointerInfo()); 3911 } 3912 3913 // Return the value of the return address register, marking it an implicit 3914 // live-in. 3915 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3916 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3917 } 3918 3919 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3920 SelectionDAG &DAG) const { 3921 SDLoc DL(Op); 3922 SDValue Lo = Op.getOperand(0); 3923 SDValue Hi = Op.getOperand(1); 3924 SDValue Shamt = Op.getOperand(2); 3925 EVT VT = Lo.getValueType(); 3926 3927 // if Shamt-XLEN < 0: // Shamt < XLEN 3928 // Lo = Lo << Shamt 3929 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 3930 // else: 3931 // Lo = 0 3932 // Hi = Lo << (Shamt-XLEN) 3933 3934 SDValue Zero = DAG.getConstant(0, DL, VT); 3935 SDValue One = DAG.getConstant(1, DL, VT); 3936 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3937 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3938 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3939 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 3940 3941 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3942 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3943 SDValue ShiftRightLo = 3944 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3945 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3946 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3947 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3948 3949 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3950 3951 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3952 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3953 3954 SDValue Parts[2] = {Lo, Hi}; 3955 return DAG.getMergeValues(Parts, DL); 3956 } 3957 3958 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 3959 bool IsSRA) const { 3960 SDLoc DL(Op); 3961 SDValue Lo = Op.getOperand(0); 3962 SDValue Hi = Op.getOperand(1); 3963 SDValue Shamt = Op.getOperand(2); 3964 EVT VT = Lo.getValueType(); 3965 3966 // SRA expansion: 3967 // if Shamt-XLEN < 0: // Shamt < XLEN 3968 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 3969 // Hi = Hi >>s Shamt 3970 // else: 3971 // Lo = Hi >>s (Shamt-XLEN); 3972 // Hi = Hi >>s (XLEN-1) 3973 // 3974 // SRL expansion: 3975 // if Shamt-XLEN < 0: // Shamt < XLEN 3976 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 3977 // Hi = Hi >>u Shamt 3978 // else: 3979 // Lo = Hi >>u (Shamt-XLEN); 3980 // Hi = 0; 3981 3982 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 3983 3984 SDValue Zero = DAG.getConstant(0, DL, VT); 3985 SDValue One = DAG.getConstant(1, DL, VT); 3986 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3987 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3988 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3989 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 3990 3991 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 3992 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 3993 SDValue ShiftLeftHi = 3994 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 3995 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 3996 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 3997 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 3998 SDValue HiFalse = 3999 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 4000 4001 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 4002 4003 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 4004 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 4005 4006 SDValue Parts[2] = {Lo, Hi}; 4007 return DAG.getMergeValues(Parts, DL); 4008 } 4009 4010 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 4011 // legal equivalently-sized i8 type, so we can use that as a go-between. 4012 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 4013 SelectionDAG &DAG) const { 4014 SDLoc DL(Op); 4015 MVT VT = Op.getSimpleValueType(); 4016 SDValue SplatVal = Op.getOperand(0); 4017 // All-zeros or all-ones splats are handled specially. 4018 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 4019 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4020 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 4021 } 4022 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 4023 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 4024 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4025 } 4026 MVT XLenVT = Subtarget.getXLenVT(); 4027 assert(SplatVal.getValueType() == XLenVT && 4028 "Unexpected type for i1 splat value"); 4029 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4030 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4031 DAG.getConstant(1, DL, XLenVT)); 4032 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4033 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4034 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4035 } 4036 4037 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4038 // illegal (currently only vXi64 RV32). 4039 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4040 // them to VMV_V_X_VL. 4041 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4042 SelectionDAG &DAG) const { 4043 SDLoc DL(Op); 4044 MVT VecVT = Op.getSimpleValueType(); 4045 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4046 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4047 4048 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4049 SDValue Lo = Op.getOperand(0); 4050 SDValue Hi = Op.getOperand(1); 4051 4052 if (VecVT.isFixedLengthVector()) { 4053 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4054 SDLoc DL(Op); 4055 SDValue Mask, VL; 4056 std::tie(Mask, VL) = 4057 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4058 4059 SDValue Res = 4060 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4061 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4062 } 4063 4064 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4065 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4066 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4067 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4068 // node in order to try and match RVV vector/scalar instructions. 4069 if ((LoC >> 31) == HiC) 4070 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4071 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4072 } 4073 4074 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4075 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4076 isa<ConstantSDNode>(Hi.getOperand(1)) && 4077 Hi.getConstantOperandVal(1) == 31) 4078 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4079 DAG.getRegister(RISCV::X0, MVT::i32)); 4080 4081 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4082 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4083 DAG.getUNDEF(VecVT), Lo, Hi, 4084 DAG.getRegister(RISCV::X0, MVT::i32)); 4085 } 4086 4087 // Custom-lower extensions from mask vectors by using a vselect either with 1 4088 // for zero/any-extension or -1 for sign-extension: 4089 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4090 // Note that any-extension is lowered identically to zero-extension. 4091 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4092 int64_t ExtTrueVal) const { 4093 SDLoc DL(Op); 4094 MVT VecVT = Op.getSimpleValueType(); 4095 SDValue Src = Op.getOperand(0); 4096 // Only custom-lower extensions from mask types 4097 assert(Src.getValueType().isVector() && 4098 Src.getValueType().getVectorElementType() == MVT::i1); 4099 4100 if (VecVT.isScalableVector()) { 4101 SDValue SplatZero = DAG.getConstant(0, DL, VecVT); 4102 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT); 4103 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4104 } 4105 4106 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4107 MVT I1ContainerVT = 4108 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4109 4110 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4111 4112 SDValue Mask, VL; 4113 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4114 4115 MVT XLenVT = Subtarget.getXLenVT(); 4116 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4117 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4118 4119 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4120 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4121 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4122 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4123 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4124 SplatTrueVal, SplatZero, VL); 4125 4126 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4127 } 4128 4129 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4130 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4131 MVT ExtVT = Op.getSimpleValueType(); 4132 // Only custom-lower extensions from fixed-length vector types. 4133 if (!ExtVT.isFixedLengthVector()) 4134 return Op; 4135 MVT VT = Op.getOperand(0).getSimpleValueType(); 4136 // Grab the canonical container type for the extended type. Infer the smaller 4137 // type from that to ensure the same number of vector elements, as we know 4138 // the LMUL will be sufficient to hold the smaller type. 4139 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4140 // Get the extended container type manually to ensure the same number of 4141 // vector elements between source and dest. 4142 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4143 ContainerExtVT.getVectorElementCount()); 4144 4145 SDValue Op1 = 4146 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4147 4148 SDLoc DL(Op); 4149 SDValue Mask, VL; 4150 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4151 4152 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4153 4154 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4155 } 4156 4157 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4158 // setcc operation: 4159 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4160 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op, 4161 SelectionDAG &DAG) const { 4162 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNC; 4163 SDLoc DL(Op); 4164 EVT MaskVT = Op.getValueType(); 4165 // Only expect to custom-lower truncations to mask types 4166 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4167 "Unexpected type for vector mask lowering"); 4168 SDValue Src = Op.getOperand(0); 4169 MVT VecVT = Src.getSimpleValueType(); 4170 SDValue Mask, VL; 4171 if (IsVPTrunc) { 4172 Mask = Op.getOperand(1); 4173 VL = Op.getOperand(2); 4174 } 4175 // If this is a fixed vector, we need to convert it to a scalable vector. 4176 MVT ContainerVT = VecVT; 4177 4178 if (VecVT.isFixedLengthVector()) { 4179 ContainerVT = getContainerForFixedLengthVector(VecVT); 4180 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4181 if (IsVPTrunc) { 4182 MVT MaskContainerVT = 4183 getContainerForFixedLengthVector(Mask.getSimpleValueType()); 4184 Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget); 4185 } 4186 } 4187 4188 if (!IsVPTrunc) { 4189 std::tie(Mask, VL) = 4190 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4191 } 4192 4193 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4194 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4195 4196 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4197 DAG.getUNDEF(ContainerVT), SplatOne, VL); 4198 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4199 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4200 4201 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4202 SDValue Trunc = 4203 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4204 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4205 DAG.getCondCode(ISD::SETNE), Mask, VL); 4206 if (MaskVT.isFixedLengthVector()) 4207 Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4208 return Trunc; 4209 } 4210 4211 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op, 4212 SelectionDAG &DAG) const { 4213 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNC; 4214 SDLoc DL(Op); 4215 4216 MVT VT = Op.getSimpleValueType(); 4217 // Only custom-lower vector truncates 4218 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4219 4220 // Truncates to mask types are handled differently 4221 if (VT.getVectorElementType() == MVT::i1) 4222 return lowerVectorMaskTruncLike(Op, DAG); 4223 4224 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 4225 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 4226 // truncate by one power of two at a time. 4227 MVT DstEltVT = VT.getVectorElementType(); 4228 4229 SDValue Src = Op.getOperand(0); 4230 MVT SrcVT = Src.getSimpleValueType(); 4231 MVT SrcEltVT = SrcVT.getVectorElementType(); 4232 4233 assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) && 4234 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 4235 "Unexpected vector truncate lowering"); 4236 4237 MVT ContainerVT = SrcVT; 4238 SDValue Mask, VL; 4239 if (IsVPTrunc) { 4240 Mask = Op.getOperand(1); 4241 VL = Op.getOperand(2); 4242 } 4243 if (SrcVT.isFixedLengthVector()) { 4244 ContainerVT = getContainerForFixedLengthVector(SrcVT); 4245 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4246 if (IsVPTrunc) { 4247 MVT MaskVT = getMaskTypeFor(ContainerVT); 4248 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4249 } 4250 } 4251 4252 SDValue Result = Src; 4253 if (!IsVPTrunc) { 4254 std::tie(Mask, VL) = 4255 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4256 } 4257 4258 LLVMContext &Context = *DAG.getContext(); 4259 const ElementCount Count = ContainerVT.getVectorElementCount(); 4260 do { 4261 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 4262 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 4263 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 4264 Mask, VL); 4265 } while (SrcEltVT != DstEltVT); 4266 4267 if (SrcVT.isFixedLengthVector()) 4268 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4269 4270 return Result; 4271 } 4272 4273 SDValue RISCVTargetLowering::lowerVectorFPRoundLike(SDValue Op, 4274 SelectionDAG &DAG) const { 4275 bool IsVPFPTrunc = Op.getOpcode() == ISD::VP_FP_ROUND; 4276 // RVV can only do truncate fp to types half the size as the source. We 4277 // custom-lower f64->f16 rounds via RVV's round-to-odd float 4278 // conversion instruction. 4279 SDLoc DL(Op); 4280 MVT VT = Op.getSimpleValueType(); 4281 4282 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4283 4284 SDValue Src = Op.getOperand(0); 4285 MVT SrcVT = Src.getSimpleValueType(); 4286 4287 bool IsDirectConv = VT.getVectorElementType() != MVT::f16 || 4288 SrcVT.getVectorElementType() != MVT::f64; 4289 4290 // For FP_ROUND of scalable vectors, leave it to the pattern. 4291 if (!VT.isFixedLengthVector() && !IsVPFPTrunc && IsDirectConv) 4292 return Op; 4293 4294 // Prepare any fixed-length vector operands. 4295 MVT ContainerVT = VT; 4296 SDValue Mask, VL; 4297 if (IsVPFPTrunc) { 4298 Mask = Op.getOperand(1); 4299 VL = Op.getOperand(2); 4300 } 4301 if (VT.isFixedLengthVector()) { 4302 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 4303 ContainerVT = 4304 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 4305 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 4306 if (IsVPFPTrunc) { 4307 MVT MaskVT = getMaskTypeFor(ContainerVT); 4308 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4309 } 4310 } 4311 4312 if (!IsVPFPTrunc) 4313 std::tie(Mask, VL) = 4314 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4315 4316 if (IsDirectConv) { 4317 Src = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, ContainerVT, Src, Mask, VL); 4318 if (VT.isFixedLengthVector()) 4319 Src = convertFromScalableVector(VT, Src, DAG, Subtarget); 4320 return Src; 4321 } 4322 4323 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 4324 SDValue IntermediateRound = 4325 DAG.getNode(RISCVISD::VFNCVT_ROD_VL, DL, InterVT, Src, Mask, VL); 4326 SDValue Round = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, ContainerVT, 4327 IntermediateRound, Mask, VL); 4328 if (VT.isFixedLengthVector()) 4329 return convertFromScalableVector(VT, Round, DAG, Subtarget); 4330 return Round; 4331 } 4332 4333 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4334 // first position of a vector, and that vector is slid up to the insert index. 4335 // By limiting the active vector length to index+1 and merging with the 4336 // original vector (with an undisturbed tail policy for elements >= VL), we 4337 // achieve the desired result of leaving all elements untouched except the one 4338 // at VL-1, which is replaced with the desired value. 4339 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4340 SelectionDAG &DAG) const { 4341 SDLoc DL(Op); 4342 MVT VecVT = Op.getSimpleValueType(); 4343 SDValue Vec = Op.getOperand(0); 4344 SDValue Val = Op.getOperand(1); 4345 SDValue Idx = Op.getOperand(2); 4346 4347 if (VecVT.getVectorElementType() == MVT::i1) { 4348 // FIXME: For now we just promote to an i8 vector and insert into that, 4349 // but this is probably not optimal. 4350 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4351 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4352 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4353 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4354 } 4355 4356 MVT ContainerVT = VecVT; 4357 // If the operand is a fixed-length vector, convert to a scalable one. 4358 if (VecVT.isFixedLengthVector()) { 4359 ContainerVT = getContainerForFixedLengthVector(VecVT); 4360 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4361 } 4362 4363 MVT XLenVT = Subtarget.getXLenVT(); 4364 4365 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4366 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4367 // Even i64-element vectors on RV32 can be lowered without scalar 4368 // legalization if the most-significant 32 bits of the value are not affected 4369 // by the sign-extension of the lower 32 bits. 4370 // TODO: We could also catch sign extensions of a 32-bit value. 4371 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4372 const auto *CVal = cast<ConstantSDNode>(Val); 4373 if (isInt<32>(CVal->getSExtValue())) { 4374 IsLegalInsert = true; 4375 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4376 } 4377 } 4378 4379 SDValue Mask, VL; 4380 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4381 4382 SDValue ValInVec; 4383 4384 if (IsLegalInsert) { 4385 unsigned Opc = 4386 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4387 if (isNullConstant(Idx)) { 4388 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4389 if (!VecVT.isFixedLengthVector()) 4390 return Vec; 4391 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4392 } 4393 ValInVec = 4394 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4395 } else { 4396 // On RV32, i64-element vectors must be specially handled to place the 4397 // value at element 0, by using two vslide1up instructions in sequence on 4398 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4399 // this. 4400 SDValue One = DAG.getConstant(1, DL, XLenVT); 4401 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4402 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4403 MVT I32ContainerVT = 4404 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4405 SDValue I32Mask = 4406 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4407 // Limit the active VL to two. 4408 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4409 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4410 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4411 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4412 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4413 // First slide in the hi value, then the lo in underneath it. 4414 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4415 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4416 I32Mask, InsertI64VL); 4417 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4418 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4419 I32Mask, InsertI64VL); 4420 // Bitcast back to the right container type. 4421 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4422 } 4423 4424 // Now that the value is in a vector, slide it into position. 4425 SDValue InsertVL = 4426 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4427 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4428 ValInVec, Idx, Mask, InsertVL); 4429 if (!VecVT.isFixedLengthVector()) 4430 return Slideup; 4431 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4432 } 4433 4434 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4435 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4436 // types this is done using VMV_X_S to allow us to glean information about the 4437 // sign bits of the result. 4438 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4439 SelectionDAG &DAG) const { 4440 SDLoc DL(Op); 4441 SDValue Idx = Op.getOperand(1); 4442 SDValue Vec = Op.getOperand(0); 4443 EVT EltVT = Op.getValueType(); 4444 MVT VecVT = Vec.getSimpleValueType(); 4445 MVT XLenVT = Subtarget.getXLenVT(); 4446 4447 if (VecVT.getVectorElementType() == MVT::i1) { 4448 if (VecVT.isFixedLengthVector()) { 4449 unsigned NumElts = VecVT.getVectorNumElements(); 4450 if (NumElts >= 8) { 4451 MVT WideEltVT; 4452 unsigned WidenVecLen; 4453 SDValue ExtractElementIdx; 4454 SDValue ExtractBitIdx; 4455 unsigned MaxEEW = Subtarget.getELEN(); 4456 MVT LargestEltVT = MVT::getIntegerVT( 4457 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4458 if (NumElts <= LargestEltVT.getSizeInBits()) { 4459 assert(isPowerOf2_32(NumElts) && 4460 "the number of elements should be power of 2"); 4461 WideEltVT = MVT::getIntegerVT(NumElts); 4462 WidenVecLen = 1; 4463 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4464 ExtractBitIdx = Idx; 4465 } else { 4466 WideEltVT = LargestEltVT; 4467 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4468 // extract element index = index / element width 4469 ExtractElementIdx = DAG.getNode( 4470 ISD::SRL, DL, XLenVT, Idx, 4471 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4472 // mask bit index = index % element width 4473 ExtractBitIdx = DAG.getNode( 4474 ISD::AND, DL, XLenVT, Idx, 4475 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4476 } 4477 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4478 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4479 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4480 Vec, ExtractElementIdx); 4481 // Extract the bit from GPR. 4482 SDValue ShiftRight = 4483 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4484 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4485 DAG.getConstant(1, DL, XLenVT)); 4486 } 4487 } 4488 // Otherwise, promote to an i8 vector and extract from that. 4489 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4490 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4491 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4492 } 4493 4494 // If this is a fixed vector, we need to convert it to a scalable vector. 4495 MVT ContainerVT = VecVT; 4496 if (VecVT.isFixedLengthVector()) { 4497 ContainerVT = getContainerForFixedLengthVector(VecVT); 4498 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4499 } 4500 4501 // If the index is 0, the vector is already in the right position. 4502 if (!isNullConstant(Idx)) { 4503 // Use a VL of 1 to avoid processing more elements than we need. 4504 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4505 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 4506 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4507 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4508 } 4509 4510 if (!EltVT.isInteger()) { 4511 // Floating-point extracts are handled in TableGen. 4512 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4513 DAG.getConstant(0, DL, XLenVT)); 4514 } 4515 4516 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4517 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4518 } 4519 4520 // Some RVV intrinsics may claim that they want an integer operand to be 4521 // promoted or expanded. 4522 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG, 4523 const RISCVSubtarget &Subtarget) { 4524 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4525 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4526 "Unexpected opcode"); 4527 4528 if (!Subtarget.hasVInstructions()) 4529 return SDValue(); 4530 4531 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4532 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4533 SDLoc DL(Op); 4534 4535 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4536 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4537 if (!II || !II->hasScalarOperand()) 4538 return SDValue(); 4539 4540 unsigned SplatOp = II->ScalarOperand + 1 + HasChain; 4541 assert(SplatOp < Op.getNumOperands()); 4542 4543 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4544 SDValue &ScalarOp = Operands[SplatOp]; 4545 MVT OpVT = ScalarOp.getSimpleValueType(); 4546 MVT XLenVT = Subtarget.getXLenVT(); 4547 4548 // If this isn't a scalar, or its type is XLenVT we're done. 4549 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4550 return SDValue(); 4551 4552 // Simplest case is that the operand needs to be promoted to XLenVT. 4553 if (OpVT.bitsLT(XLenVT)) { 4554 // If the operand is a constant, sign extend to increase our chances 4555 // of being able to use a .vi instruction. ANY_EXTEND would become a 4556 // a zero extend and the simm5 check in isel would fail. 4557 // FIXME: Should we ignore the upper bits in isel instead? 4558 unsigned ExtOpc = 4559 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4560 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4561 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4562 } 4563 4564 // Use the previous operand to get the vXi64 VT. The result might be a mask 4565 // VT for compares. Using the previous operand assumes that the previous 4566 // operand will never have a smaller element size than a scalar operand and 4567 // that a widening operation never uses SEW=64. 4568 // NOTE: If this fails the below assert, we can probably just find the 4569 // element count from any operand or result and use it to construct the VT. 4570 assert(II->ScalarOperand > 0 && "Unexpected splat operand!"); 4571 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4572 4573 // The more complex case is when the scalar is larger than XLenVT. 4574 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4575 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4576 4577 // If this is a sign-extended 32-bit value, we can truncate it and rely on the 4578 // instruction to sign-extend since SEW>XLEN. 4579 if (DAG.ComputeNumSignBits(ScalarOp) > 32) { 4580 ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp); 4581 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4582 } 4583 4584 switch (IntNo) { 4585 case Intrinsic::riscv_vslide1up: 4586 case Intrinsic::riscv_vslide1down: 4587 case Intrinsic::riscv_vslide1up_mask: 4588 case Intrinsic::riscv_vslide1down_mask: { 4589 // We need to special case these when the scalar is larger than XLen. 4590 unsigned NumOps = Op.getNumOperands(); 4591 bool IsMasked = NumOps == 7; 4592 4593 // Convert the vector source to the equivalent nxvXi32 vector. 4594 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4595 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4596 4597 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4598 DAG.getConstant(0, DL, XLenVT)); 4599 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4600 DAG.getConstant(1, DL, XLenVT)); 4601 4602 // Double the VL since we halved SEW. 4603 SDValue AVL = getVLOperand(Op); 4604 SDValue I32VL; 4605 4606 // Optimize for constant AVL 4607 if (isa<ConstantSDNode>(AVL)) { 4608 unsigned EltSize = VT.getScalarSizeInBits(); 4609 unsigned MinSize = VT.getSizeInBits().getKnownMinValue(); 4610 4611 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 4612 unsigned MaxVLMAX = 4613 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 4614 4615 unsigned VectorBitsMin = Subtarget.getRealMinVLen(); 4616 unsigned MinVLMAX = 4617 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize); 4618 4619 uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue(); 4620 if (AVLInt <= MinVLMAX) { 4621 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT); 4622 } else if (AVLInt >= 2 * MaxVLMAX) { 4623 // Just set vl to VLMAX in this situation 4624 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT); 4625 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4626 unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits()); 4627 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4628 SDValue SETVLMAX = DAG.getTargetConstant( 4629 Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32); 4630 I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW, 4631 LMUL); 4632 } else { 4633 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl 4634 // is related to the hardware implementation. 4635 // So let the following code handle 4636 } 4637 } 4638 if (!I32VL) { 4639 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT); 4640 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4641 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits()); 4642 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4643 SDValue SETVL = 4644 DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32); 4645 // Using vsetvli instruction to get actually used length which related to 4646 // the hardware implementation 4647 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL, 4648 SEW, LMUL); 4649 I32VL = 4650 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4651 } 4652 4653 SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG); 4654 4655 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4656 // instructions. 4657 SDValue Passthru; 4658 if (IsMasked) 4659 Passthru = DAG.getUNDEF(I32VT); 4660 else 4661 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4662 4663 if (IntNo == Intrinsic::riscv_vslide1up || 4664 IntNo == Intrinsic::riscv_vslide1up_mask) { 4665 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4666 ScalarHi, I32Mask, I32VL); 4667 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4668 ScalarLo, I32Mask, I32VL); 4669 } else { 4670 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4671 ScalarLo, I32Mask, I32VL); 4672 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4673 ScalarHi, I32Mask, I32VL); 4674 } 4675 4676 // Convert back to nxvXi64. 4677 Vec = DAG.getBitcast(VT, Vec); 4678 4679 if (!IsMasked) 4680 return Vec; 4681 // Apply mask after the operation. 4682 SDValue Mask = Operands[NumOps - 3]; 4683 SDValue MaskedOff = Operands[1]; 4684 // Assume Policy operand is the last operand. 4685 uint64_t Policy = 4686 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4687 // We don't need to select maskedoff if it's undef. 4688 if (MaskedOff.isUndef()) 4689 return Vec; 4690 // TAMU 4691 if (Policy == RISCVII::TAIL_AGNOSTIC) 4692 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4693 AVL); 4694 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4695 // It's fine because vmerge does not care mask policy. 4696 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, 4697 AVL); 4698 } 4699 } 4700 4701 // We need to convert the scalar to a splat vector. 4702 SDValue VL = getVLOperand(Op); 4703 assert(VL.getValueType() == XLenVT); 4704 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4705 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4706 } 4707 4708 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4709 SelectionDAG &DAG) const { 4710 unsigned IntNo = Op.getConstantOperandVal(0); 4711 SDLoc DL(Op); 4712 MVT XLenVT = Subtarget.getXLenVT(); 4713 4714 switch (IntNo) { 4715 default: 4716 break; // Don't custom lower most intrinsics. 4717 case Intrinsic::thread_pointer: { 4718 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4719 return DAG.getRegister(RISCV::X4, PtrVT); 4720 } 4721 case Intrinsic::riscv_orc_b: 4722 case Intrinsic::riscv_brev8: { 4723 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4724 unsigned Opc = 4725 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4726 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4727 DAG.getConstant(7, DL, XLenVT)); 4728 } 4729 case Intrinsic::riscv_grev: 4730 case Intrinsic::riscv_gorc: { 4731 unsigned Opc = 4732 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4733 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4734 } 4735 case Intrinsic::riscv_zip: 4736 case Intrinsic::riscv_unzip: { 4737 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4738 // For i32 the immediate is 15. For i64 the immediate is 31. 4739 unsigned Opc = 4740 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4741 unsigned BitWidth = Op.getValueSizeInBits(); 4742 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4743 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4744 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4745 } 4746 case Intrinsic::riscv_shfl: 4747 case Intrinsic::riscv_unshfl: { 4748 unsigned Opc = 4749 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4750 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4751 } 4752 case Intrinsic::riscv_bcompress: 4753 case Intrinsic::riscv_bdecompress: { 4754 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4755 : RISCVISD::BDECOMPRESS; 4756 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4757 } 4758 case Intrinsic::riscv_bfp: 4759 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4760 Op.getOperand(2)); 4761 case Intrinsic::riscv_fsl: 4762 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4763 Op.getOperand(2), Op.getOperand(3)); 4764 case Intrinsic::riscv_fsr: 4765 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4766 Op.getOperand(2), Op.getOperand(3)); 4767 case Intrinsic::riscv_vmv_x_s: 4768 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4769 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4770 Op.getOperand(1)); 4771 case Intrinsic::riscv_vmv_v_x: 4772 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4773 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4774 Subtarget); 4775 case Intrinsic::riscv_vfmv_v_f: 4776 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4777 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4778 case Intrinsic::riscv_vmv_s_x: { 4779 SDValue Scalar = Op.getOperand(2); 4780 4781 if (Scalar.getValueType().bitsLE(XLenVT)) { 4782 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4783 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4784 Op.getOperand(1), Scalar, Op.getOperand(3)); 4785 } 4786 4787 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4788 4789 // This is an i64 value that lives in two scalar registers. We have to 4790 // insert this in a convoluted way. First we build vXi64 splat containing 4791 // the two values that we assemble using some bit math. Next we'll use 4792 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4793 // to merge element 0 from our splat into the source vector. 4794 // FIXME: This is probably not the best way to do this, but it is 4795 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4796 // point. 4797 // sw lo, (a0) 4798 // sw hi, 4(a0) 4799 // vlse vX, (a0) 4800 // 4801 // vid.v vVid 4802 // vmseq.vx mMask, vVid, 0 4803 // vmerge.vvm vDest, vSrc, vVal, mMask 4804 MVT VT = Op.getSimpleValueType(); 4805 SDValue Vec = Op.getOperand(1); 4806 SDValue VL = getVLOperand(Op); 4807 4808 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4809 if (Op.getOperand(1).isUndef()) 4810 return SplattedVal; 4811 SDValue SplattedIdx = 4812 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4813 DAG.getConstant(0, DL, MVT::i32), VL); 4814 4815 MVT MaskVT = getMaskTypeFor(VT); 4816 SDValue Mask = getAllOnesMask(VT, VL, DL, DAG); 4817 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4818 SDValue SelectCond = 4819 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4820 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4821 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4822 Vec, VL); 4823 } 4824 } 4825 4826 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4827 } 4828 4829 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4830 SelectionDAG &DAG) const { 4831 unsigned IntNo = Op.getConstantOperandVal(1); 4832 switch (IntNo) { 4833 default: 4834 break; 4835 case Intrinsic::riscv_masked_strided_load: { 4836 SDLoc DL(Op); 4837 MVT XLenVT = Subtarget.getXLenVT(); 4838 4839 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4840 // the selection of the masked intrinsics doesn't do this for us. 4841 SDValue Mask = Op.getOperand(5); 4842 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4843 4844 MVT VT = Op->getSimpleValueType(0); 4845 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4846 4847 SDValue PassThru = Op.getOperand(2); 4848 if (!IsUnmasked) { 4849 MVT MaskVT = getMaskTypeFor(ContainerVT); 4850 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4851 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4852 } 4853 4854 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4855 4856 SDValue IntID = DAG.getTargetConstant( 4857 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4858 XLenVT); 4859 4860 auto *Load = cast<MemIntrinsicSDNode>(Op); 4861 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4862 if (IsUnmasked) 4863 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4864 else 4865 Ops.push_back(PassThru); 4866 Ops.push_back(Op.getOperand(3)); // Ptr 4867 Ops.push_back(Op.getOperand(4)); // Stride 4868 if (!IsUnmasked) 4869 Ops.push_back(Mask); 4870 Ops.push_back(VL); 4871 if (!IsUnmasked) { 4872 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4873 Ops.push_back(Policy); 4874 } 4875 4876 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4877 SDValue Result = 4878 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4879 Load->getMemoryVT(), Load->getMemOperand()); 4880 SDValue Chain = Result.getValue(1); 4881 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4882 return DAG.getMergeValues({Result, Chain}, DL); 4883 } 4884 case Intrinsic::riscv_seg2_load: 4885 case Intrinsic::riscv_seg3_load: 4886 case Intrinsic::riscv_seg4_load: 4887 case Intrinsic::riscv_seg5_load: 4888 case Intrinsic::riscv_seg6_load: 4889 case Intrinsic::riscv_seg7_load: 4890 case Intrinsic::riscv_seg8_load: { 4891 SDLoc DL(Op); 4892 static const Intrinsic::ID VlsegInts[7] = { 4893 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 4894 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 4895 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 4896 Intrinsic::riscv_vlseg8}; 4897 unsigned NF = Op->getNumValues() - 1; 4898 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 4899 MVT XLenVT = Subtarget.getXLenVT(); 4900 MVT VT = Op->getSimpleValueType(0); 4901 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4902 4903 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4904 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 4905 auto *Load = cast<MemIntrinsicSDNode>(Op); 4906 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 4907 ContainerVTs.push_back(MVT::Other); 4908 SDVTList VTs = DAG.getVTList(ContainerVTs); 4909 SDValue Result = 4910 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, 4911 {Load->getChain(), IntID, Op.getOperand(2), VL}, 4912 Load->getMemoryVT(), Load->getMemOperand()); 4913 SmallVector<SDValue, 9> Results; 4914 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 4915 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 4916 DAG, Subtarget)); 4917 Results.push_back(Result.getValue(NF)); 4918 return DAG.getMergeValues(Results, DL); 4919 } 4920 } 4921 4922 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4923 } 4924 4925 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4926 SelectionDAG &DAG) const { 4927 unsigned IntNo = Op.getConstantOperandVal(1); 4928 switch (IntNo) { 4929 default: 4930 break; 4931 case Intrinsic::riscv_masked_strided_store: { 4932 SDLoc DL(Op); 4933 MVT XLenVT = Subtarget.getXLenVT(); 4934 4935 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4936 // the selection of the masked intrinsics doesn't do this for us. 4937 SDValue Mask = Op.getOperand(5); 4938 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4939 4940 SDValue Val = Op.getOperand(2); 4941 MVT VT = Val.getSimpleValueType(); 4942 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4943 4944 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4945 if (!IsUnmasked) { 4946 MVT MaskVT = getMaskTypeFor(ContainerVT); 4947 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4948 } 4949 4950 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4951 4952 SDValue IntID = DAG.getTargetConstant( 4953 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4954 XLenVT); 4955 4956 auto *Store = cast<MemIntrinsicSDNode>(Op); 4957 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4958 Ops.push_back(Val); 4959 Ops.push_back(Op.getOperand(3)); // Ptr 4960 Ops.push_back(Op.getOperand(4)); // Stride 4961 if (!IsUnmasked) 4962 Ops.push_back(Mask); 4963 Ops.push_back(VL); 4964 4965 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4966 Ops, Store->getMemoryVT(), 4967 Store->getMemOperand()); 4968 } 4969 } 4970 4971 return SDValue(); 4972 } 4973 4974 static MVT getLMUL1VT(MVT VT) { 4975 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4976 "Unexpected vector MVT"); 4977 return MVT::getScalableVectorVT( 4978 VT.getVectorElementType(), 4979 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4980 } 4981 4982 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4983 switch (ISDOpcode) { 4984 default: 4985 llvm_unreachable("Unhandled reduction"); 4986 case ISD::VECREDUCE_ADD: 4987 return RISCVISD::VECREDUCE_ADD_VL; 4988 case ISD::VECREDUCE_UMAX: 4989 return RISCVISD::VECREDUCE_UMAX_VL; 4990 case ISD::VECREDUCE_SMAX: 4991 return RISCVISD::VECREDUCE_SMAX_VL; 4992 case ISD::VECREDUCE_UMIN: 4993 return RISCVISD::VECREDUCE_UMIN_VL; 4994 case ISD::VECREDUCE_SMIN: 4995 return RISCVISD::VECREDUCE_SMIN_VL; 4996 case ISD::VECREDUCE_AND: 4997 return RISCVISD::VECREDUCE_AND_VL; 4998 case ISD::VECREDUCE_OR: 4999 return RISCVISD::VECREDUCE_OR_VL; 5000 case ISD::VECREDUCE_XOR: 5001 return RISCVISD::VECREDUCE_XOR_VL; 5002 } 5003 } 5004 5005 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 5006 SelectionDAG &DAG, 5007 bool IsVP) const { 5008 SDLoc DL(Op); 5009 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 5010 MVT VecVT = Vec.getSimpleValueType(); 5011 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 5012 Op.getOpcode() == ISD::VECREDUCE_OR || 5013 Op.getOpcode() == ISD::VECREDUCE_XOR || 5014 Op.getOpcode() == ISD::VP_REDUCE_AND || 5015 Op.getOpcode() == ISD::VP_REDUCE_OR || 5016 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5017 "Unexpected reduction lowering"); 5018 5019 MVT XLenVT = Subtarget.getXLenVT(); 5020 assert(Op.getValueType() == XLenVT && 5021 "Expected reduction output to be legalized to XLenVT"); 5022 5023 MVT ContainerVT = VecVT; 5024 if (VecVT.isFixedLengthVector()) { 5025 ContainerVT = getContainerForFixedLengthVector(VecVT); 5026 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5027 } 5028 5029 SDValue Mask, VL; 5030 if (IsVP) { 5031 Mask = Op.getOperand(2); 5032 VL = Op.getOperand(3); 5033 } else { 5034 std::tie(Mask, VL) = 5035 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5036 } 5037 5038 unsigned BaseOpc; 5039 ISD::CondCode CC; 5040 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5041 5042 switch (Op.getOpcode()) { 5043 default: 5044 llvm_unreachable("Unhandled reduction"); 5045 case ISD::VECREDUCE_AND: 5046 case ISD::VP_REDUCE_AND: { 5047 // vcpop ~x == 0 5048 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5049 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5050 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5051 CC = ISD::SETEQ; 5052 BaseOpc = ISD::AND; 5053 break; 5054 } 5055 case ISD::VECREDUCE_OR: 5056 case ISD::VP_REDUCE_OR: 5057 // vcpop x != 0 5058 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5059 CC = ISD::SETNE; 5060 BaseOpc = ISD::OR; 5061 break; 5062 case ISD::VECREDUCE_XOR: 5063 case ISD::VP_REDUCE_XOR: { 5064 // ((vcpop x) & 1) != 0 5065 SDValue One = DAG.getConstant(1, DL, XLenVT); 5066 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5067 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5068 CC = ISD::SETNE; 5069 BaseOpc = ISD::XOR; 5070 break; 5071 } 5072 } 5073 5074 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5075 5076 if (!IsVP) 5077 return SetCC; 5078 5079 // Now include the start value in the operation. 5080 // Note that we must return the start value when no elements are operated 5081 // upon. The vcpop instructions we've emitted in each case above will return 5082 // 0 for an inactive vector, and so we've already received the neutral value: 5083 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5084 // can simply include the start value. 5085 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5086 } 5087 5088 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5089 SelectionDAG &DAG) const { 5090 SDLoc DL(Op); 5091 SDValue Vec = Op.getOperand(0); 5092 EVT VecEVT = Vec.getValueType(); 5093 5094 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5095 5096 // Due to ordering in legalize types we may have a vector type that needs to 5097 // be split. Do that manually so we can get down to a legal type. 5098 while (getTypeAction(*DAG.getContext(), VecEVT) == 5099 TargetLowering::TypeSplitVector) { 5100 SDValue Lo, Hi; 5101 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5102 VecEVT = Lo.getValueType(); 5103 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5104 } 5105 5106 // TODO: The type may need to be widened rather than split. Or widened before 5107 // it can be split. 5108 if (!isTypeLegal(VecEVT)) 5109 return SDValue(); 5110 5111 MVT VecVT = VecEVT.getSimpleVT(); 5112 MVT VecEltVT = VecVT.getVectorElementType(); 5113 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5114 5115 MVT ContainerVT = VecVT; 5116 if (VecVT.isFixedLengthVector()) { 5117 ContainerVT = getContainerForFixedLengthVector(VecVT); 5118 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5119 } 5120 5121 MVT M1VT = getLMUL1VT(ContainerVT); 5122 MVT XLenVT = Subtarget.getXLenVT(); 5123 5124 SDValue Mask, VL; 5125 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5126 5127 SDValue NeutralElem = 5128 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5129 SDValue IdentitySplat = 5130 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5131 M1VT, DL, DAG, Subtarget); 5132 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5133 IdentitySplat, Mask, VL); 5134 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5135 DAG.getConstant(0, DL, XLenVT)); 5136 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5137 } 5138 5139 // Given a reduction op, this function returns the matching reduction opcode, 5140 // the vector SDValue and the scalar SDValue required to lower this to a 5141 // RISCVISD node. 5142 static std::tuple<unsigned, SDValue, SDValue> 5143 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5144 SDLoc DL(Op); 5145 auto Flags = Op->getFlags(); 5146 unsigned Opcode = Op.getOpcode(); 5147 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5148 switch (Opcode) { 5149 default: 5150 llvm_unreachable("Unhandled reduction"); 5151 case ISD::VECREDUCE_FADD: { 5152 // Use positive zero if we can. It is cheaper to materialize. 5153 SDValue Zero = 5154 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5155 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5156 } 5157 case ISD::VECREDUCE_SEQ_FADD: 5158 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5159 Op.getOperand(0)); 5160 case ISD::VECREDUCE_FMIN: 5161 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5162 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5163 case ISD::VECREDUCE_FMAX: 5164 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5165 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5166 } 5167 } 5168 5169 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5170 SelectionDAG &DAG) const { 5171 SDLoc DL(Op); 5172 MVT VecEltVT = Op.getSimpleValueType(); 5173 5174 unsigned RVVOpcode; 5175 SDValue VectorVal, ScalarVal; 5176 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5177 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5178 MVT VecVT = VectorVal.getSimpleValueType(); 5179 5180 MVT ContainerVT = VecVT; 5181 if (VecVT.isFixedLengthVector()) { 5182 ContainerVT = getContainerForFixedLengthVector(VecVT); 5183 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5184 } 5185 5186 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5187 MVT XLenVT = Subtarget.getXLenVT(); 5188 5189 SDValue Mask, VL; 5190 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5191 5192 SDValue ScalarSplat = 5193 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5194 M1VT, DL, DAG, Subtarget); 5195 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5196 VectorVal, ScalarSplat, Mask, VL); 5197 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5198 DAG.getConstant(0, DL, XLenVT)); 5199 } 5200 5201 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5202 switch (ISDOpcode) { 5203 default: 5204 llvm_unreachable("Unhandled reduction"); 5205 case ISD::VP_REDUCE_ADD: 5206 return RISCVISD::VECREDUCE_ADD_VL; 5207 case ISD::VP_REDUCE_UMAX: 5208 return RISCVISD::VECREDUCE_UMAX_VL; 5209 case ISD::VP_REDUCE_SMAX: 5210 return RISCVISD::VECREDUCE_SMAX_VL; 5211 case ISD::VP_REDUCE_UMIN: 5212 return RISCVISD::VECREDUCE_UMIN_VL; 5213 case ISD::VP_REDUCE_SMIN: 5214 return RISCVISD::VECREDUCE_SMIN_VL; 5215 case ISD::VP_REDUCE_AND: 5216 return RISCVISD::VECREDUCE_AND_VL; 5217 case ISD::VP_REDUCE_OR: 5218 return RISCVISD::VECREDUCE_OR_VL; 5219 case ISD::VP_REDUCE_XOR: 5220 return RISCVISD::VECREDUCE_XOR_VL; 5221 case ISD::VP_REDUCE_FADD: 5222 return RISCVISD::VECREDUCE_FADD_VL; 5223 case ISD::VP_REDUCE_SEQ_FADD: 5224 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5225 case ISD::VP_REDUCE_FMAX: 5226 return RISCVISD::VECREDUCE_FMAX_VL; 5227 case ISD::VP_REDUCE_FMIN: 5228 return RISCVISD::VECREDUCE_FMIN_VL; 5229 } 5230 } 5231 5232 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5233 SelectionDAG &DAG) const { 5234 SDLoc DL(Op); 5235 SDValue Vec = Op.getOperand(1); 5236 EVT VecEVT = Vec.getValueType(); 5237 5238 // TODO: The type may need to be widened rather than split. Or widened before 5239 // it can be split. 5240 if (!isTypeLegal(VecEVT)) 5241 return SDValue(); 5242 5243 MVT VecVT = VecEVT.getSimpleVT(); 5244 MVT VecEltVT = VecVT.getVectorElementType(); 5245 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5246 5247 MVT ContainerVT = VecVT; 5248 if (VecVT.isFixedLengthVector()) { 5249 ContainerVT = getContainerForFixedLengthVector(VecVT); 5250 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5251 } 5252 5253 SDValue VL = Op.getOperand(3); 5254 SDValue Mask = Op.getOperand(2); 5255 5256 MVT M1VT = getLMUL1VT(ContainerVT); 5257 MVT XLenVT = Subtarget.getXLenVT(); 5258 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5259 5260 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5261 DAG.getConstant(1, DL, XLenVT), M1VT, 5262 DL, DAG, Subtarget); 5263 SDValue Reduction = 5264 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5265 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5266 DAG.getConstant(0, DL, XLenVT)); 5267 if (!VecVT.isInteger()) 5268 return Elt0; 5269 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5270 } 5271 5272 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5273 SelectionDAG &DAG) const { 5274 SDValue Vec = Op.getOperand(0); 5275 SDValue SubVec = Op.getOperand(1); 5276 MVT VecVT = Vec.getSimpleValueType(); 5277 MVT SubVecVT = SubVec.getSimpleValueType(); 5278 5279 SDLoc DL(Op); 5280 MVT XLenVT = Subtarget.getXLenVT(); 5281 unsigned OrigIdx = Op.getConstantOperandVal(2); 5282 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5283 5284 // We don't have the ability to slide mask vectors up indexed by their i1 5285 // elements; the smallest we can do is i8. Often we are able to bitcast to 5286 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5287 // into a scalable one, we might not necessarily have enough scalable 5288 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5289 if (SubVecVT.getVectorElementType() == MVT::i1 && 5290 (OrigIdx != 0 || !Vec.isUndef())) { 5291 if (VecVT.getVectorMinNumElements() >= 8 && 5292 SubVecVT.getVectorMinNumElements() >= 8) { 5293 assert(OrigIdx % 8 == 0 && "Invalid index"); 5294 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5295 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5296 "Unexpected mask vector lowering"); 5297 OrigIdx /= 8; 5298 SubVecVT = 5299 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5300 SubVecVT.isScalableVector()); 5301 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5302 VecVT.isScalableVector()); 5303 Vec = DAG.getBitcast(VecVT, Vec); 5304 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5305 } else { 5306 // We can't slide this mask vector up indexed by its i1 elements. 5307 // This poses a problem when we wish to insert a scalable vector which 5308 // can't be re-expressed as a larger type. Just choose the slow path and 5309 // extend to a larger type, then truncate back down. 5310 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5311 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5312 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5313 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5314 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5315 Op.getOperand(2)); 5316 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5317 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5318 } 5319 } 5320 5321 // If the subvector vector is a fixed-length type, we cannot use subregister 5322 // manipulation to simplify the codegen; we don't know which register of a 5323 // LMUL group contains the specific subvector as we only know the minimum 5324 // register size. Therefore we must slide the vector group up the full 5325 // amount. 5326 if (SubVecVT.isFixedLengthVector()) { 5327 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5328 return Op; 5329 MVT ContainerVT = VecVT; 5330 if (VecVT.isFixedLengthVector()) { 5331 ContainerVT = getContainerForFixedLengthVector(VecVT); 5332 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5333 } 5334 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5335 DAG.getUNDEF(ContainerVT), SubVec, 5336 DAG.getConstant(0, DL, XLenVT)); 5337 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5338 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5339 return DAG.getBitcast(Op.getValueType(), SubVec); 5340 } 5341 SDValue Mask = 5342 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5343 // Set the vector length to only the number of elements we care about. Note 5344 // that for slideup this includes the offset. 5345 SDValue VL = 5346 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5347 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5348 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5349 SubVec, SlideupAmt, Mask, VL); 5350 if (VecVT.isFixedLengthVector()) 5351 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5352 return DAG.getBitcast(Op.getValueType(), Slideup); 5353 } 5354 5355 unsigned SubRegIdx, RemIdx; 5356 std::tie(SubRegIdx, RemIdx) = 5357 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5358 VecVT, SubVecVT, OrigIdx, TRI); 5359 5360 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5361 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5362 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5363 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5364 5365 // 1. If the Idx has been completely eliminated and this subvector's size is 5366 // a vector register or a multiple thereof, or the surrounding elements are 5367 // undef, then this is a subvector insert which naturally aligns to a vector 5368 // register. These can easily be handled using subregister manipulation. 5369 // 2. If the subvector is smaller than a vector register, then the insertion 5370 // must preserve the undisturbed elements of the register. We do this by 5371 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5372 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5373 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5374 // LMUL=1 type back into the larger vector (resolving to another subregister 5375 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5376 // to avoid allocating a large register group to hold our subvector. 5377 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5378 return Op; 5379 5380 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5381 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5382 // (in our case undisturbed). This means we can set up a subvector insertion 5383 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5384 // size of the subvector. 5385 MVT InterSubVT = VecVT; 5386 SDValue AlignedExtract = Vec; 5387 unsigned AlignedIdx = OrigIdx - RemIdx; 5388 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5389 InterSubVT = getLMUL1VT(VecVT); 5390 // Extract a subvector equal to the nearest full vector register type. This 5391 // should resolve to a EXTRACT_SUBREG instruction. 5392 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5393 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5394 } 5395 5396 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5397 // For scalable vectors this must be further multiplied by vscale. 5398 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5399 5400 SDValue Mask, VL; 5401 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5402 5403 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5404 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5405 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5406 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5407 5408 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5409 DAG.getUNDEF(InterSubVT), SubVec, 5410 DAG.getConstant(0, DL, XLenVT)); 5411 5412 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5413 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5414 5415 // If required, insert this subvector back into the correct vector register. 5416 // This should resolve to an INSERT_SUBREG instruction. 5417 if (VecVT.bitsGT(InterSubVT)) 5418 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5419 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5420 5421 // We might have bitcast from a mask type: cast back to the original type if 5422 // required. 5423 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5424 } 5425 5426 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5427 SelectionDAG &DAG) const { 5428 SDValue Vec = Op.getOperand(0); 5429 MVT SubVecVT = Op.getSimpleValueType(); 5430 MVT VecVT = Vec.getSimpleValueType(); 5431 5432 SDLoc DL(Op); 5433 MVT XLenVT = Subtarget.getXLenVT(); 5434 unsigned OrigIdx = Op.getConstantOperandVal(1); 5435 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5436 5437 // We don't have the ability to slide mask vectors down indexed by their i1 5438 // elements; the smallest we can do is i8. Often we are able to bitcast to 5439 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5440 // from a scalable one, we might not necessarily have enough scalable 5441 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5442 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5443 if (VecVT.getVectorMinNumElements() >= 8 && 5444 SubVecVT.getVectorMinNumElements() >= 8) { 5445 assert(OrigIdx % 8 == 0 && "Invalid index"); 5446 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5447 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5448 "Unexpected mask vector lowering"); 5449 OrigIdx /= 8; 5450 SubVecVT = 5451 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5452 SubVecVT.isScalableVector()); 5453 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5454 VecVT.isScalableVector()); 5455 Vec = DAG.getBitcast(VecVT, Vec); 5456 } else { 5457 // We can't slide this mask vector down, indexed by its i1 elements. 5458 // This poses a problem when we wish to extract a scalable vector which 5459 // can't be re-expressed as a larger type. Just choose the slow path and 5460 // extend to a larger type, then truncate back down. 5461 // TODO: We could probably improve this when extracting certain fixed 5462 // from fixed, where we can extract as i8 and shift the correct element 5463 // right to reach the desired subvector? 5464 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5465 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5466 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5467 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5468 Op.getOperand(1)); 5469 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5470 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5471 } 5472 } 5473 5474 // If the subvector vector is a fixed-length type, we cannot use subregister 5475 // manipulation to simplify the codegen; we don't know which register of a 5476 // LMUL group contains the specific subvector as we only know the minimum 5477 // register size. Therefore we must slide the vector group down the full 5478 // amount. 5479 if (SubVecVT.isFixedLengthVector()) { 5480 // With an index of 0 this is a cast-like subvector, which can be performed 5481 // with subregister operations. 5482 if (OrigIdx == 0) 5483 return Op; 5484 MVT ContainerVT = VecVT; 5485 if (VecVT.isFixedLengthVector()) { 5486 ContainerVT = getContainerForFixedLengthVector(VecVT); 5487 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5488 } 5489 SDValue Mask = 5490 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5491 // Set the vector length to only the number of elements we care about. This 5492 // avoids sliding down elements we're going to discard straight away. 5493 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5494 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5495 SDValue Slidedown = 5496 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5497 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5498 // Now we can use a cast-like subvector extract to get the result. 5499 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5500 DAG.getConstant(0, DL, XLenVT)); 5501 return DAG.getBitcast(Op.getValueType(), Slidedown); 5502 } 5503 5504 unsigned SubRegIdx, RemIdx; 5505 std::tie(SubRegIdx, RemIdx) = 5506 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5507 VecVT, SubVecVT, OrigIdx, TRI); 5508 5509 // If the Idx has been completely eliminated then this is a subvector extract 5510 // which naturally aligns to a vector register. These can easily be handled 5511 // using subregister manipulation. 5512 if (RemIdx == 0) 5513 return Op; 5514 5515 // Else we must shift our vector register directly to extract the subvector. 5516 // Do this using VSLIDEDOWN. 5517 5518 // If the vector type is an LMUL-group type, extract a subvector equal to the 5519 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5520 // instruction. 5521 MVT InterSubVT = VecVT; 5522 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5523 InterSubVT = getLMUL1VT(VecVT); 5524 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5525 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5526 } 5527 5528 // Slide this vector register down by the desired number of elements in order 5529 // to place the desired subvector starting at element 0. 5530 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5531 // For scalable vectors this must be further multiplied by vscale. 5532 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5533 5534 SDValue Mask, VL; 5535 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5536 SDValue Slidedown = 5537 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5538 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5539 5540 // Now the vector is in the right position, extract our final subvector. This 5541 // should resolve to a COPY. 5542 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5543 DAG.getConstant(0, DL, XLenVT)); 5544 5545 // We might have bitcast from a mask type: cast back to the original type if 5546 // required. 5547 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5548 } 5549 5550 // Lower step_vector to the vid instruction. Any non-identity step value must 5551 // be accounted for my manual expansion. 5552 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5553 SelectionDAG &DAG) const { 5554 SDLoc DL(Op); 5555 MVT VT = Op.getSimpleValueType(); 5556 MVT XLenVT = Subtarget.getXLenVT(); 5557 SDValue Mask, VL; 5558 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5559 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5560 uint64_t StepValImm = Op.getConstantOperandVal(0); 5561 if (StepValImm != 1) { 5562 if (isPowerOf2_64(StepValImm)) { 5563 SDValue StepVal = 5564 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5565 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5566 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5567 } else { 5568 SDValue StepVal = lowerScalarSplat( 5569 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5570 VL, VT, DL, DAG, Subtarget); 5571 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5572 } 5573 } 5574 return StepVec; 5575 } 5576 5577 // Implement vector_reverse using vrgather.vv with indices determined by 5578 // subtracting the id of each element from (VLMAX-1). This will convert 5579 // the indices like so: 5580 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5581 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5582 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5583 SelectionDAG &DAG) const { 5584 SDLoc DL(Op); 5585 MVT VecVT = Op.getSimpleValueType(); 5586 unsigned EltSize = VecVT.getScalarSizeInBits(); 5587 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5588 5589 unsigned MaxVLMAX = 0; 5590 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5591 if (VectorBitsMax != 0) 5592 MaxVLMAX = 5593 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 5594 5595 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5596 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5597 5598 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5599 // to use vrgatherei16.vv. 5600 // TODO: It's also possible to use vrgatherei16.vv for other types to 5601 // decrease register width for the index calculation. 5602 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5603 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5604 // Reverse each half, then reassemble them in reverse order. 5605 // NOTE: It's also possible that after splitting that VLMAX no longer 5606 // requires vrgatherei16.vv. 5607 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5608 SDValue Lo, Hi; 5609 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5610 EVT LoVT, HiVT; 5611 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5612 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5613 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5614 // Reassemble the low and high pieces reversed. 5615 // FIXME: This is a CONCAT_VECTORS. 5616 SDValue Res = 5617 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5618 DAG.getIntPtrConstant(0, DL)); 5619 return DAG.getNode( 5620 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5621 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5622 } 5623 5624 // Just promote the int type to i16 which will double the LMUL. 5625 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5626 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5627 } 5628 5629 MVT XLenVT = Subtarget.getXLenVT(); 5630 SDValue Mask, VL; 5631 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5632 5633 // Calculate VLMAX-1 for the desired SEW. 5634 unsigned MinElts = VecVT.getVectorMinNumElements(); 5635 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5636 DAG.getConstant(MinElts, DL, XLenVT)); 5637 SDValue VLMinus1 = 5638 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5639 5640 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5641 bool IsRV32E64 = 5642 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5643 SDValue SplatVL; 5644 if (!IsRV32E64) 5645 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5646 else 5647 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5648 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5649 5650 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5651 SDValue Indices = 5652 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5653 5654 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5655 } 5656 5657 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5658 SelectionDAG &DAG) const { 5659 SDLoc DL(Op); 5660 SDValue V1 = Op.getOperand(0); 5661 SDValue V2 = Op.getOperand(1); 5662 MVT XLenVT = Subtarget.getXLenVT(); 5663 MVT VecVT = Op.getSimpleValueType(); 5664 5665 unsigned MinElts = VecVT.getVectorMinNumElements(); 5666 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5667 DAG.getConstant(MinElts, DL, XLenVT)); 5668 5669 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5670 SDValue DownOffset, UpOffset; 5671 if (ImmValue >= 0) { 5672 // The operand is a TargetConstant, we need to rebuild it as a regular 5673 // constant. 5674 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5675 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5676 } else { 5677 // The operand is a TargetConstant, we need to rebuild it as a regular 5678 // constant rather than negating the original operand. 5679 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5680 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5681 } 5682 5683 SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG); 5684 5685 SDValue SlideDown = 5686 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5687 DownOffset, TrueMask, UpOffset); 5688 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5689 TrueMask, 5690 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 5691 } 5692 5693 SDValue 5694 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5695 SelectionDAG &DAG) const { 5696 SDLoc DL(Op); 5697 auto *Load = cast<LoadSDNode>(Op); 5698 5699 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5700 Load->getMemoryVT(), 5701 *Load->getMemOperand()) && 5702 "Expecting a correctly-aligned load"); 5703 5704 MVT VT = Op.getSimpleValueType(); 5705 MVT XLenVT = Subtarget.getXLenVT(); 5706 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5707 5708 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5709 5710 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5711 SDValue IntID = DAG.getTargetConstant( 5712 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 5713 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 5714 if (!IsMaskOp) 5715 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5716 Ops.push_back(Load->getBasePtr()); 5717 Ops.push_back(VL); 5718 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5719 SDValue NewLoad = 5720 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5721 Load->getMemoryVT(), Load->getMemOperand()); 5722 5723 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5724 return DAG.getMergeValues({Result, Load->getChain()}, DL); 5725 } 5726 5727 SDValue 5728 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5729 SelectionDAG &DAG) const { 5730 SDLoc DL(Op); 5731 auto *Store = cast<StoreSDNode>(Op); 5732 5733 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5734 Store->getMemoryVT(), 5735 *Store->getMemOperand()) && 5736 "Expecting a correctly-aligned store"); 5737 5738 SDValue StoreVal = Store->getValue(); 5739 MVT VT = StoreVal.getSimpleValueType(); 5740 MVT XLenVT = Subtarget.getXLenVT(); 5741 5742 // If the size less than a byte, we need to pad with zeros to make a byte. 5743 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5744 VT = MVT::v8i1; 5745 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5746 DAG.getConstant(0, DL, VT), StoreVal, 5747 DAG.getIntPtrConstant(0, DL)); 5748 } 5749 5750 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5751 5752 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5753 5754 SDValue NewValue = 5755 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5756 5757 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5758 SDValue IntID = DAG.getTargetConstant( 5759 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 5760 return DAG.getMemIntrinsicNode( 5761 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 5762 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 5763 Store->getMemoryVT(), Store->getMemOperand()); 5764 } 5765 5766 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5767 SelectionDAG &DAG) const { 5768 SDLoc DL(Op); 5769 MVT VT = Op.getSimpleValueType(); 5770 5771 const auto *MemSD = cast<MemSDNode>(Op); 5772 EVT MemVT = MemSD->getMemoryVT(); 5773 MachineMemOperand *MMO = MemSD->getMemOperand(); 5774 SDValue Chain = MemSD->getChain(); 5775 SDValue BasePtr = MemSD->getBasePtr(); 5776 5777 SDValue Mask, PassThru, VL; 5778 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5779 Mask = VPLoad->getMask(); 5780 PassThru = DAG.getUNDEF(VT); 5781 VL = VPLoad->getVectorLength(); 5782 } else { 5783 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5784 Mask = MLoad->getMask(); 5785 PassThru = MLoad->getPassThru(); 5786 } 5787 5788 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5789 5790 MVT XLenVT = Subtarget.getXLenVT(); 5791 5792 MVT ContainerVT = VT; 5793 if (VT.isFixedLengthVector()) { 5794 ContainerVT = getContainerForFixedLengthVector(VT); 5795 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5796 if (!IsUnmasked) { 5797 MVT MaskVT = getMaskTypeFor(ContainerVT); 5798 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5799 } 5800 } 5801 5802 if (!VL) 5803 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5804 5805 unsigned IntID = 5806 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5807 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5808 if (IsUnmasked) 5809 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5810 else 5811 Ops.push_back(PassThru); 5812 Ops.push_back(BasePtr); 5813 if (!IsUnmasked) 5814 Ops.push_back(Mask); 5815 Ops.push_back(VL); 5816 if (!IsUnmasked) 5817 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5818 5819 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5820 5821 SDValue Result = 5822 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5823 Chain = Result.getValue(1); 5824 5825 if (VT.isFixedLengthVector()) 5826 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5827 5828 return DAG.getMergeValues({Result, Chain}, DL); 5829 } 5830 5831 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5832 SelectionDAG &DAG) const { 5833 SDLoc DL(Op); 5834 5835 const auto *MemSD = cast<MemSDNode>(Op); 5836 EVT MemVT = MemSD->getMemoryVT(); 5837 MachineMemOperand *MMO = MemSD->getMemOperand(); 5838 SDValue Chain = MemSD->getChain(); 5839 SDValue BasePtr = MemSD->getBasePtr(); 5840 SDValue Val, Mask, VL; 5841 5842 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5843 Val = VPStore->getValue(); 5844 Mask = VPStore->getMask(); 5845 VL = VPStore->getVectorLength(); 5846 } else { 5847 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5848 Val = MStore->getValue(); 5849 Mask = MStore->getMask(); 5850 } 5851 5852 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5853 5854 MVT VT = Val.getSimpleValueType(); 5855 MVT XLenVT = Subtarget.getXLenVT(); 5856 5857 MVT ContainerVT = VT; 5858 if (VT.isFixedLengthVector()) { 5859 ContainerVT = getContainerForFixedLengthVector(VT); 5860 5861 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5862 if (!IsUnmasked) { 5863 MVT MaskVT = getMaskTypeFor(ContainerVT); 5864 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5865 } 5866 } 5867 5868 if (!VL) 5869 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5870 5871 unsigned IntID = 5872 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5873 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5874 Ops.push_back(Val); 5875 Ops.push_back(BasePtr); 5876 if (!IsUnmasked) 5877 Ops.push_back(Mask); 5878 Ops.push_back(VL); 5879 5880 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5881 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5882 } 5883 5884 SDValue 5885 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5886 SelectionDAG &DAG) const { 5887 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5888 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5889 5890 MVT VT = Op.getSimpleValueType(); 5891 5892 SDValue Op1 = 5893 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5894 SDValue Op2 = 5895 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5896 5897 SDLoc DL(Op); 5898 SDValue VL = 5899 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5900 5901 MVT MaskVT = getMaskTypeFor(ContainerVT); 5902 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 5903 5904 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5905 Op.getOperand(2), Mask, VL); 5906 5907 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5908 } 5909 5910 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5911 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5912 MVT VT = Op.getSimpleValueType(); 5913 5914 if (VT.getVectorElementType() == MVT::i1) 5915 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5916 5917 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5918 } 5919 5920 SDValue 5921 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5922 SelectionDAG &DAG) const { 5923 unsigned Opc; 5924 switch (Op.getOpcode()) { 5925 default: llvm_unreachable("Unexpected opcode!"); 5926 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5927 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5928 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5929 } 5930 5931 return lowerToScalableOp(Op, DAG, Opc); 5932 } 5933 5934 // Lower vector ABS to smax(X, sub(0, X)). 5935 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5936 SDLoc DL(Op); 5937 MVT VT = Op.getSimpleValueType(); 5938 SDValue X = Op.getOperand(0); 5939 5940 assert(VT.isFixedLengthVector() && "Unexpected type"); 5941 5942 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5943 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5944 5945 SDValue Mask, VL; 5946 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5947 5948 SDValue SplatZero = DAG.getNode( 5949 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 5950 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5951 SDValue NegX = 5952 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5953 SDValue Max = 5954 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5955 5956 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5957 } 5958 5959 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5960 SDValue Op, SelectionDAG &DAG) const { 5961 SDLoc DL(Op); 5962 MVT VT = Op.getSimpleValueType(); 5963 SDValue Mag = Op.getOperand(0); 5964 SDValue Sign = Op.getOperand(1); 5965 assert(Mag.getValueType() == Sign.getValueType() && 5966 "Can only handle COPYSIGN with matching types."); 5967 5968 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5969 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5970 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5971 5972 SDValue Mask, VL; 5973 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5974 5975 SDValue CopySign = 5976 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5977 5978 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5979 } 5980 5981 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5982 SDValue Op, SelectionDAG &DAG) const { 5983 MVT VT = Op.getSimpleValueType(); 5984 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5985 5986 MVT I1ContainerVT = 5987 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5988 5989 SDValue CC = 5990 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5991 SDValue Op1 = 5992 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5993 SDValue Op2 = 5994 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5995 5996 SDLoc DL(Op); 5997 SDValue Mask, VL; 5998 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5999 6000 SDValue Select = 6001 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 6002 6003 return convertFromScalableVector(VT, Select, DAG, Subtarget); 6004 } 6005 6006 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 6007 unsigned NewOpc, 6008 bool HasMask) const { 6009 MVT VT = Op.getSimpleValueType(); 6010 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6011 6012 // Create list of operands by converting existing ones to scalable types. 6013 SmallVector<SDValue, 6> Ops; 6014 for (const SDValue &V : Op->op_values()) { 6015 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6016 6017 // Pass through non-vector operands. 6018 if (!V.getValueType().isVector()) { 6019 Ops.push_back(V); 6020 continue; 6021 } 6022 6023 // "cast" fixed length vector to a scalable vector. 6024 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6025 "Only fixed length vectors are supported!"); 6026 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6027 } 6028 6029 SDLoc DL(Op); 6030 SDValue Mask, VL; 6031 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6032 if (HasMask) 6033 Ops.push_back(Mask); 6034 Ops.push_back(VL); 6035 6036 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6037 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6038 } 6039 6040 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6041 // * Operands of each node are assumed to be in the same order. 6042 // * The EVL operand is promoted from i32 to i64 on RV64. 6043 // * Fixed-length vectors are converted to their scalable-vector container 6044 // types. 6045 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6046 unsigned RISCVISDOpc) const { 6047 SDLoc DL(Op); 6048 MVT VT = Op.getSimpleValueType(); 6049 SmallVector<SDValue, 4> Ops; 6050 6051 for (const auto &OpIdx : enumerate(Op->ops())) { 6052 SDValue V = OpIdx.value(); 6053 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6054 // Pass through operands which aren't fixed-length vectors. 6055 if (!V.getValueType().isFixedLengthVector()) { 6056 Ops.push_back(V); 6057 continue; 6058 } 6059 // "cast" fixed length vector to a scalable vector. 6060 MVT OpVT = V.getSimpleValueType(); 6061 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6062 assert(useRVVForFixedLengthVectorVT(OpVT) && 6063 "Only fixed length vectors are supported!"); 6064 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6065 } 6066 6067 if (!VT.isFixedLengthVector()) 6068 return DAG.getNode(RISCVISDOpc, DL, VT, Ops); 6069 6070 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6071 6072 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops); 6073 6074 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6075 } 6076 6077 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op, 6078 SelectionDAG &DAG) const { 6079 SDLoc DL(Op); 6080 MVT VT = Op.getSimpleValueType(); 6081 6082 SDValue Src = Op.getOperand(0); 6083 // NOTE: Mask is dropped. 6084 SDValue VL = Op.getOperand(2); 6085 6086 MVT ContainerVT = VT; 6087 if (VT.isFixedLengthVector()) { 6088 ContainerVT = getContainerForFixedLengthVector(VT); 6089 MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6090 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6091 } 6092 6093 MVT XLenVT = Subtarget.getXLenVT(); 6094 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6095 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6096 DAG.getUNDEF(ContainerVT), Zero, VL); 6097 6098 SDValue SplatValue = 6099 DAG.getConstant(Op.getOpcode() == ISD::VP_ZEXT ? 1 : -1, DL, XLenVT); 6100 SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6101 DAG.getUNDEF(ContainerVT), SplatValue, VL); 6102 6103 SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src, 6104 Splat, ZeroSplat, VL); 6105 if (!VT.isFixedLengthVector()) 6106 return Result; 6107 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6108 } 6109 6110 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op, 6111 SelectionDAG &DAG) const { 6112 SDLoc DL(Op); 6113 MVT VT = Op.getSimpleValueType(); 6114 6115 SDValue Op1 = Op.getOperand(0); 6116 SDValue Op2 = Op.getOperand(1); 6117 ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 6118 // NOTE: Mask is dropped. 6119 SDValue VL = Op.getOperand(4); 6120 6121 MVT ContainerVT = VT; 6122 if (VT.isFixedLengthVector()) { 6123 ContainerVT = getContainerForFixedLengthVector(VT); 6124 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6125 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6126 } 6127 6128 SDValue Result; 6129 SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 6130 6131 switch (Condition) { 6132 default: 6133 break; 6134 // X != Y --> (X^Y) 6135 case ISD::SETNE: 6136 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6137 break; 6138 // X == Y --> ~(X^Y) 6139 case ISD::SETEQ: { 6140 SDValue Temp = 6141 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6142 Result = 6143 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL); 6144 break; 6145 } 6146 // X >s Y --> X == 0 & Y == 1 --> ~X & Y 6147 // X <u Y --> X == 0 & Y == 1 --> ~X & Y 6148 case ISD::SETGT: 6149 case ISD::SETULT: { 6150 SDValue Temp = 6151 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6152 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL); 6153 break; 6154 } 6155 // X <s Y --> X == 1 & Y == 0 --> ~Y & X 6156 // X >u Y --> X == 1 & Y == 0 --> ~Y & X 6157 case ISD::SETLT: 6158 case ISD::SETUGT: { 6159 SDValue Temp = 6160 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6161 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL); 6162 break; 6163 } 6164 // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 6165 // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 6166 case ISD::SETGE: 6167 case ISD::SETULE: { 6168 SDValue Temp = 6169 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6170 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL); 6171 break; 6172 } 6173 // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 6174 // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 6175 case ISD::SETLE: 6176 case ISD::SETUGE: { 6177 SDValue Temp = 6178 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6179 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL); 6180 break; 6181 } 6182 } 6183 6184 if (!VT.isFixedLengthVector()) 6185 return Result; 6186 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6187 } 6188 6189 // Lower Floating-Point/Integer Type-Convert VP SDNodes 6190 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG, 6191 unsigned RISCVISDOpc) const { 6192 SDLoc DL(Op); 6193 6194 SDValue Src = Op.getOperand(0); 6195 SDValue Mask = Op.getOperand(1); 6196 SDValue VL = Op.getOperand(2); 6197 6198 MVT DstVT = Op.getSimpleValueType(); 6199 MVT SrcVT = Src.getSimpleValueType(); 6200 if (DstVT.isFixedLengthVector()) { 6201 DstVT = getContainerForFixedLengthVector(DstVT); 6202 SrcVT = getContainerForFixedLengthVector(SrcVT); 6203 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6204 MVT MaskVT = getMaskTypeFor(DstVT); 6205 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6206 } 6207 6208 unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL || 6209 RISCVISDOpc == RISCVISD::FP_TO_SINT_VL) 6210 ? RISCVISD::VSEXT_VL 6211 : RISCVISD::VZEXT_VL; 6212 6213 unsigned DstEltSize = DstVT.getScalarSizeInBits(); 6214 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 6215 6216 SDValue Result; 6217 if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion. 6218 if (SrcVT.isInteger()) { 6219 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6220 6221 // Do we need to do any pre-widening before converting? 6222 if (SrcEltSize == 1) { 6223 MVT IntVT = DstVT.changeVectorElementTypeToInteger(); 6224 MVT XLenVT = Subtarget.getXLenVT(); 6225 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6226 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6227 DAG.getUNDEF(IntVT), Zero, VL); 6228 SDValue One = DAG.getConstant( 6229 RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT); 6230 SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6231 DAG.getUNDEF(IntVT), One, VL); 6232 Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat, 6233 ZeroSplat, VL); 6234 } else if (DstEltSize > (2 * SrcEltSize)) { 6235 // Widen before converting. 6236 MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2), 6237 DstVT.getVectorElementCount()); 6238 Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL); 6239 } 6240 6241 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6242 } else { 6243 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6244 "Wrong input/output vector types"); 6245 6246 // Convert f16 to f32 then convert f32 to i64. 6247 if (DstEltSize > (2 * SrcEltSize)) { 6248 assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6249 MVT InterimFVT = 6250 MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6251 Src = 6252 DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL); 6253 } 6254 6255 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6256 } 6257 } else { // Narrowing + Conversion 6258 if (SrcVT.isInteger()) { 6259 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6260 // First do a narrowing convert to an FP type half the size, then round 6261 // the FP type to a small FP type if needed. 6262 6263 MVT InterimFVT = DstVT; 6264 if (SrcEltSize > (2 * DstEltSize)) { 6265 assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!"); 6266 assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6267 InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6268 } 6269 6270 Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL); 6271 6272 if (InterimFVT != DstVT) { 6273 Src = Result; 6274 Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL); 6275 } 6276 } else { 6277 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6278 "Wrong input/output vector types"); 6279 // First do a narrowing conversion to an integer half the size, then 6280 // truncate if needed. 6281 6282 if (DstEltSize == 1) { 6283 // First convert to the same size integer, then convert to mask using 6284 // setcc. 6285 assert(SrcEltSize >= 16 && "Unexpected FP type!"); 6286 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize), 6287 DstVT.getVectorElementCount()); 6288 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6289 6290 // Compare the integer result to 0. The integer should be 0 or 1/-1, 6291 // otherwise the conversion was undefined. 6292 MVT XLenVT = Subtarget.getXLenVT(); 6293 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 6294 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT, 6295 DAG.getUNDEF(InterimIVT), SplatZero); 6296 Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero, 6297 DAG.getCondCode(ISD::SETNE), Mask, VL); 6298 } else { 6299 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6300 DstVT.getVectorElementCount()); 6301 6302 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6303 6304 while (InterimIVT != DstVT) { 6305 SrcEltSize /= 2; 6306 Src = Result; 6307 InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6308 DstVT.getVectorElementCount()); 6309 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT, 6310 Src, Mask, VL); 6311 } 6312 } 6313 } 6314 } 6315 6316 MVT VT = Op.getSimpleValueType(); 6317 if (!VT.isFixedLengthVector()) 6318 return Result; 6319 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6320 } 6321 6322 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6323 unsigned MaskOpc, 6324 unsigned VecOpc) const { 6325 MVT VT = Op.getSimpleValueType(); 6326 if (VT.getVectorElementType() != MVT::i1) 6327 return lowerVPOp(Op, DAG, VecOpc); 6328 6329 // It is safe to drop mask parameter as masked-off elements are undef. 6330 SDValue Op1 = Op->getOperand(0); 6331 SDValue Op2 = Op->getOperand(1); 6332 SDValue VL = Op->getOperand(3); 6333 6334 MVT ContainerVT = VT; 6335 const bool IsFixed = VT.isFixedLengthVector(); 6336 if (IsFixed) { 6337 ContainerVT = getContainerForFixedLengthVector(VT); 6338 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6339 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6340 } 6341 6342 SDLoc DL(Op); 6343 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6344 if (!IsFixed) 6345 return Val; 6346 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6347 } 6348 6349 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6350 // matched to a RVV indexed load. The RVV indexed load instructions only 6351 // support the "unsigned unscaled" addressing mode; indices are implicitly 6352 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6353 // signed or scaled indexing is extended to the XLEN value type and scaled 6354 // accordingly. 6355 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6356 SelectionDAG &DAG) const { 6357 SDLoc DL(Op); 6358 MVT VT = Op.getSimpleValueType(); 6359 6360 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6361 EVT MemVT = MemSD->getMemoryVT(); 6362 MachineMemOperand *MMO = MemSD->getMemOperand(); 6363 SDValue Chain = MemSD->getChain(); 6364 SDValue BasePtr = MemSD->getBasePtr(); 6365 6366 ISD::LoadExtType LoadExtType; 6367 SDValue Index, Mask, PassThru, VL; 6368 6369 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6370 Index = VPGN->getIndex(); 6371 Mask = VPGN->getMask(); 6372 PassThru = DAG.getUNDEF(VT); 6373 VL = VPGN->getVectorLength(); 6374 // VP doesn't support extending loads. 6375 LoadExtType = ISD::NON_EXTLOAD; 6376 } else { 6377 // Else it must be a MGATHER. 6378 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6379 Index = MGN->getIndex(); 6380 Mask = MGN->getMask(); 6381 PassThru = MGN->getPassThru(); 6382 LoadExtType = MGN->getExtensionType(); 6383 } 6384 6385 MVT IndexVT = Index.getSimpleValueType(); 6386 MVT XLenVT = Subtarget.getXLenVT(); 6387 6388 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6389 "Unexpected VTs!"); 6390 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6391 // Targets have to explicitly opt-in for extending vector loads. 6392 assert(LoadExtType == ISD::NON_EXTLOAD && 6393 "Unexpected extending MGATHER/VP_GATHER"); 6394 (void)LoadExtType; 6395 6396 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6397 // the selection of the masked intrinsics doesn't do this for us. 6398 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6399 6400 MVT ContainerVT = VT; 6401 if (VT.isFixedLengthVector()) { 6402 // We need to use the larger of the result and index type to determine the 6403 // scalable type to use so we don't increase LMUL for any operand/result. 6404 if (VT.bitsGE(IndexVT)) { 6405 ContainerVT = getContainerForFixedLengthVector(VT); 6406 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6407 ContainerVT.getVectorElementCount()); 6408 } else { 6409 IndexVT = getContainerForFixedLengthVector(IndexVT); 6410 ContainerVT = MVT::getVectorVT(ContainerVT.getVectorElementType(), 6411 IndexVT.getVectorElementCount()); 6412 } 6413 6414 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6415 6416 if (!IsUnmasked) { 6417 MVT MaskVT = getMaskTypeFor(ContainerVT); 6418 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6419 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6420 } 6421 } 6422 6423 if (!VL) 6424 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6425 6426 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6427 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6428 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6429 VL); 6430 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6431 TrueMask, VL); 6432 } 6433 6434 unsigned IntID = 6435 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6436 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6437 if (IsUnmasked) 6438 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6439 else 6440 Ops.push_back(PassThru); 6441 Ops.push_back(BasePtr); 6442 Ops.push_back(Index); 6443 if (!IsUnmasked) 6444 Ops.push_back(Mask); 6445 Ops.push_back(VL); 6446 if (!IsUnmasked) 6447 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6448 6449 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6450 SDValue Result = 6451 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6452 Chain = Result.getValue(1); 6453 6454 if (VT.isFixedLengthVector()) 6455 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6456 6457 return DAG.getMergeValues({Result, Chain}, DL); 6458 } 6459 6460 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6461 // matched to a RVV indexed store. The RVV indexed store instructions only 6462 // support the "unsigned unscaled" addressing mode; indices are implicitly 6463 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6464 // signed or scaled indexing is extended to the XLEN value type and scaled 6465 // accordingly. 6466 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6467 SelectionDAG &DAG) const { 6468 SDLoc DL(Op); 6469 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6470 EVT MemVT = MemSD->getMemoryVT(); 6471 MachineMemOperand *MMO = MemSD->getMemOperand(); 6472 SDValue Chain = MemSD->getChain(); 6473 SDValue BasePtr = MemSD->getBasePtr(); 6474 6475 bool IsTruncatingStore = false; 6476 SDValue Index, Mask, Val, VL; 6477 6478 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6479 Index = VPSN->getIndex(); 6480 Mask = VPSN->getMask(); 6481 Val = VPSN->getValue(); 6482 VL = VPSN->getVectorLength(); 6483 // VP doesn't support truncating stores. 6484 IsTruncatingStore = false; 6485 } else { 6486 // Else it must be a MSCATTER. 6487 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6488 Index = MSN->getIndex(); 6489 Mask = MSN->getMask(); 6490 Val = MSN->getValue(); 6491 IsTruncatingStore = MSN->isTruncatingStore(); 6492 } 6493 6494 MVT VT = Val.getSimpleValueType(); 6495 MVT IndexVT = Index.getSimpleValueType(); 6496 MVT XLenVT = Subtarget.getXLenVT(); 6497 6498 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6499 "Unexpected VTs!"); 6500 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6501 // Targets have to explicitly opt-in for extending vector loads and 6502 // truncating vector stores. 6503 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6504 (void)IsTruncatingStore; 6505 6506 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6507 // the selection of the masked intrinsics doesn't do this for us. 6508 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6509 6510 MVT ContainerVT = VT; 6511 if (VT.isFixedLengthVector()) { 6512 // We need to use the larger of the value and index type to determine the 6513 // scalable type to use so we don't increase LMUL for any operand/result. 6514 if (VT.bitsGE(IndexVT)) { 6515 ContainerVT = getContainerForFixedLengthVector(VT); 6516 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6517 ContainerVT.getVectorElementCount()); 6518 } else { 6519 IndexVT = getContainerForFixedLengthVector(IndexVT); 6520 ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 6521 IndexVT.getVectorElementCount()); 6522 } 6523 6524 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6525 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6526 6527 if (!IsUnmasked) { 6528 MVT MaskVT = getMaskTypeFor(ContainerVT); 6529 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6530 } 6531 } 6532 6533 if (!VL) 6534 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6535 6536 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6537 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6538 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6539 VL); 6540 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6541 TrueMask, VL); 6542 } 6543 6544 unsigned IntID = 6545 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6546 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6547 Ops.push_back(Val); 6548 Ops.push_back(BasePtr); 6549 Ops.push_back(Index); 6550 if (!IsUnmasked) 6551 Ops.push_back(Mask); 6552 Ops.push_back(VL); 6553 6554 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6555 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6556 } 6557 6558 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6559 SelectionDAG &DAG) const { 6560 const MVT XLenVT = Subtarget.getXLenVT(); 6561 SDLoc DL(Op); 6562 SDValue Chain = Op->getOperand(0); 6563 SDValue SysRegNo = DAG.getTargetConstant( 6564 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6565 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6566 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6567 6568 // Encoding used for rounding mode in RISCV differs from that used in 6569 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6570 // table, which consists of a sequence of 4-bit fields, each representing 6571 // corresponding FLT_ROUNDS mode. 6572 static const int Table = 6573 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6574 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6575 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6576 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6577 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6578 6579 SDValue Shift = 6580 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6581 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6582 DAG.getConstant(Table, DL, XLenVT), Shift); 6583 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6584 DAG.getConstant(7, DL, XLenVT)); 6585 6586 return DAG.getMergeValues({Masked, Chain}, DL); 6587 } 6588 6589 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6590 SelectionDAG &DAG) const { 6591 const MVT XLenVT = Subtarget.getXLenVT(); 6592 SDLoc DL(Op); 6593 SDValue Chain = Op->getOperand(0); 6594 SDValue RMValue = Op->getOperand(1); 6595 SDValue SysRegNo = DAG.getTargetConstant( 6596 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6597 6598 // Encoding used for rounding mode in RISCV differs from that used in 6599 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6600 // a table, which consists of a sequence of 4-bit fields, each representing 6601 // corresponding RISCV mode. 6602 static const unsigned Table = 6603 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6604 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6605 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6606 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6607 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6608 6609 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6610 DAG.getConstant(2, DL, XLenVT)); 6611 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6612 DAG.getConstant(Table, DL, XLenVT), Shift); 6613 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6614 DAG.getConstant(0x7, DL, XLenVT)); 6615 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6616 RMValue); 6617 } 6618 6619 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6620 switch (IntNo) { 6621 default: 6622 llvm_unreachable("Unexpected Intrinsic"); 6623 case Intrinsic::riscv_bcompress: 6624 return RISCVISD::BCOMPRESSW; 6625 case Intrinsic::riscv_bdecompress: 6626 return RISCVISD::BDECOMPRESSW; 6627 case Intrinsic::riscv_bfp: 6628 return RISCVISD::BFPW; 6629 case Intrinsic::riscv_fsl: 6630 return RISCVISD::FSLW; 6631 case Intrinsic::riscv_fsr: 6632 return RISCVISD::FSRW; 6633 } 6634 } 6635 6636 // Converts the given intrinsic to a i64 operation with any extension. 6637 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6638 unsigned IntNo) { 6639 SDLoc DL(N); 6640 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6641 // Deal with the Instruction Operands 6642 SmallVector<SDValue, 3> NewOps; 6643 for (SDValue Op : drop_begin(N->ops())) 6644 // Promote the operand to i64 type 6645 NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op)); 6646 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps); 6647 // ReplaceNodeResults requires we maintain the same type for the return value. 6648 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6649 } 6650 6651 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6652 // form of the given Opcode. 6653 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6654 switch (Opcode) { 6655 default: 6656 llvm_unreachable("Unexpected opcode"); 6657 case ISD::SHL: 6658 return RISCVISD::SLLW; 6659 case ISD::SRA: 6660 return RISCVISD::SRAW; 6661 case ISD::SRL: 6662 return RISCVISD::SRLW; 6663 case ISD::SDIV: 6664 return RISCVISD::DIVW; 6665 case ISD::UDIV: 6666 return RISCVISD::DIVUW; 6667 case ISD::UREM: 6668 return RISCVISD::REMUW; 6669 case ISD::ROTL: 6670 return RISCVISD::ROLW; 6671 case ISD::ROTR: 6672 return RISCVISD::RORW; 6673 } 6674 } 6675 6676 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6677 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6678 // otherwise be promoted to i64, making it difficult to select the 6679 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6680 // type i8/i16/i32 is lost. 6681 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6682 unsigned ExtOpc = ISD::ANY_EXTEND) { 6683 SDLoc DL(N); 6684 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6685 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6686 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6687 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6688 // ReplaceNodeResults requires we maintain the same type for the return value. 6689 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6690 } 6691 6692 // Converts the given 32-bit operation to a i64 operation with signed extension 6693 // semantic to reduce the signed extension instructions. 6694 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6695 SDLoc DL(N); 6696 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6697 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6698 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6699 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6700 DAG.getValueType(MVT::i32)); 6701 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6702 } 6703 6704 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6705 SmallVectorImpl<SDValue> &Results, 6706 SelectionDAG &DAG) const { 6707 SDLoc DL(N); 6708 switch (N->getOpcode()) { 6709 default: 6710 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6711 case ISD::STRICT_FP_TO_SINT: 6712 case ISD::STRICT_FP_TO_UINT: 6713 case ISD::FP_TO_SINT: 6714 case ISD::FP_TO_UINT: { 6715 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6716 "Unexpected custom legalisation"); 6717 bool IsStrict = N->isStrictFPOpcode(); 6718 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6719 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6720 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6721 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6722 TargetLowering::TypeSoftenFloat) { 6723 if (!isTypeLegal(Op0.getValueType())) 6724 return; 6725 if (IsStrict) { 6726 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6727 : RISCVISD::STRICT_FCVT_WU_RV64; 6728 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6729 SDValue Res = DAG.getNode( 6730 Opc, DL, VTs, N->getOperand(0), Op0, 6731 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6732 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6733 Results.push_back(Res.getValue(1)); 6734 return; 6735 } 6736 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6737 SDValue Res = 6738 DAG.getNode(Opc, DL, MVT::i64, Op0, 6739 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6740 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6741 return; 6742 } 6743 // If the FP type needs to be softened, emit a library call using the 'si' 6744 // version. If we left it to default legalization we'd end up with 'di'. If 6745 // the FP type doesn't need to be softened just let generic type 6746 // legalization promote the result type. 6747 RTLIB::Libcall LC; 6748 if (IsSigned) 6749 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6750 else 6751 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6752 MakeLibCallOptions CallOptions; 6753 EVT OpVT = Op0.getValueType(); 6754 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6755 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6756 SDValue Result; 6757 std::tie(Result, Chain) = 6758 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6759 Results.push_back(Result); 6760 if (IsStrict) 6761 Results.push_back(Chain); 6762 break; 6763 } 6764 case ISD::READCYCLECOUNTER: { 6765 assert(!Subtarget.is64Bit() && 6766 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6767 6768 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6769 SDValue RCW = 6770 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6771 6772 Results.push_back( 6773 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6774 Results.push_back(RCW.getValue(2)); 6775 break; 6776 } 6777 case ISD::MUL: { 6778 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6779 unsigned XLen = Subtarget.getXLen(); 6780 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6781 if (Size > XLen) { 6782 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6783 SDValue LHS = N->getOperand(0); 6784 SDValue RHS = N->getOperand(1); 6785 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6786 6787 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6788 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6789 // We need exactly one side to be unsigned. 6790 if (LHSIsU == RHSIsU) 6791 return; 6792 6793 auto MakeMULPair = [&](SDValue S, SDValue U) { 6794 MVT XLenVT = Subtarget.getXLenVT(); 6795 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6796 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6797 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6798 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6799 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6800 }; 6801 6802 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6803 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6804 6805 // The other operand should be signed, but still prefer MULH when 6806 // possible. 6807 if (RHSIsU && LHSIsS && !RHSIsS) 6808 Results.push_back(MakeMULPair(LHS, RHS)); 6809 else if (LHSIsU && RHSIsS && !LHSIsS) 6810 Results.push_back(MakeMULPair(RHS, LHS)); 6811 6812 return; 6813 } 6814 LLVM_FALLTHROUGH; 6815 } 6816 case ISD::ADD: 6817 case ISD::SUB: 6818 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6819 "Unexpected custom legalisation"); 6820 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6821 break; 6822 case ISD::SHL: 6823 case ISD::SRA: 6824 case ISD::SRL: 6825 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6826 "Unexpected custom legalisation"); 6827 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6828 // If we can use a BSET instruction, allow default promotion to apply. 6829 if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() && 6830 isOneConstant(N->getOperand(0))) 6831 break; 6832 Results.push_back(customLegalizeToWOp(N, DAG)); 6833 break; 6834 } 6835 6836 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6837 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6838 // shift amount. 6839 if (N->getOpcode() == ISD::SHL) { 6840 SDLoc DL(N); 6841 SDValue NewOp0 = 6842 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6843 SDValue NewOp1 = 6844 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6845 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6846 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6847 DAG.getValueType(MVT::i32)); 6848 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6849 } 6850 6851 break; 6852 case ISD::ROTL: 6853 case ISD::ROTR: 6854 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6855 "Unexpected custom legalisation"); 6856 Results.push_back(customLegalizeToWOp(N, DAG)); 6857 break; 6858 case ISD::CTTZ: 6859 case ISD::CTTZ_ZERO_UNDEF: 6860 case ISD::CTLZ: 6861 case ISD::CTLZ_ZERO_UNDEF: { 6862 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6863 "Unexpected custom legalisation"); 6864 6865 SDValue NewOp0 = 6866 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6867 bool IsCTZ = 6868 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6869 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6870 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6871 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6872 return; 6873 } 6874 case ISD::SDIV: 6875 case ISD::UDIV: 6876 case ISD::UREM: { 6877 MVT VT = N->getSimpleValueType(0); 6878 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6879 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6880 "Unexpected custom legalisation"); 6881 // Don't promote division/remainder by constant since we should expand those 6882 // to multiply by magic constant. 6883 // FIXME: What if the expansion is disabled for minsize. 6884 if (N->getOperand(1).getOpcode() == ISD::Constant) 6885 return; 6886 6887 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6888 // the upper 32 bits. For other types we need to sign or zero extend 6889 // based on the opcode. 6890 unsigned ExtOpc = ISD::ANY_EXTEND; 6891 if (VT != MVT::i32) 6892 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6893 : ISD::ZERO_EXTEND; 6894 6895 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6896 break; 6897 } 6898 case ISD::UADDO: 6899 case ISD::USUBO: { 6900 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6901 "Unexpected custom legalisation"); 6902 bool IsAdd = N->getOpcode() == ISD::UADDO; 6903 // Create an ADDW or SUBW. 6904 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6905 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6906 SDValue Res = 6907 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6908 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6909 DAG.getValueType(MVT::i32)); 6910 6911 SDValue Overflow; 6912 if (IsAdd && isOneConstant(RHS)) { 6913 // Special case uaddo X, 1 overflowed if the addition result is 0. 6914 // FIXME: We can do this for any constant RHS by using (X + C) < C. 6915 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, 6916 DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ); 6917 } else { 6918 // Sign extend the LHS and perform an unsigned compare with the ADDW 6919 // result. Since the inputs are sign extended from i32, this is equivalent 6920 // to comparing the lower 32 bits. 6921 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6922 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6923 IsAdd ? ISD::SETULT : ISD::SETUGT); 6924 } 6925 6926 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6927 Results.push_back(Overflow); 6928 return; 6929 } 6930 case ISD::UADDSAT: 6931 case ISD::USUBSAT: { 6932 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6933 "Unexpected custom legalisation"); 6934 if (Subtarget.hasStdExtZbb()) { 6935 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6936 // sign extend allows overflow of the lower 32 bits to be detected on 6937 // the promoted size. 6938 SDValue LHS = 6939 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6940 SDValue RHS = 6941 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6942 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6943 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6944 return; 6945 } 6946 6947 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6948 // promotion for UADDO/USUBO. 6949 Results.push_back(expandAddSubSat(N, DAG)); 6950 return; 6951 } 6952 case ISD::ABS: { 6953 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6954 "Unexpected custom legalisation"); 6955 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6956 6957 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 6958 6959 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6960 6961 // Freeze the source so we can increase it's use count. 6962 Src = DAG.getFreeze(Src); 6963 6964 // Copy sign bit to all bits using the sraiw pattern. 6965 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 6966 DAG.getValueType(MVT::i32)); 6967 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 6968 DAG.getConstant(31, DL, MVT::i64)); 6969 6970 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 6971 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 6972 6973 // NOTE: The result is only required to be anyextended, but sext is 6974 // consistent with type legalization of sub. 6975 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 6976 DAG.getValueType(MVT::i32)); 6977 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6978 return; 6979 } 6980 case ISD::BITCAST: { 6981 EVT VT = N->getValueType(0); 6982 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6983 SDValue Op0 = N->getOperand(0); 6984 EVT Op0VT = Op0.getValueType(); 6985 MVT XLenVT = Subtarget.getXLenVT(); 6986 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6987 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6988 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6989 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6990 Subtarget.hasStdExtF()) { 6991 SDValue FPConv = 6992 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6993 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6994 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6995 isTypeLegal(Op0VT)) { 6996 // Custom-legalize bitcasts from fixed-length vector types to illegal 6997 // scalar types in order to improve codegen. Bitcast the vector to a 6998 // one-element vector type whose element type is the same as the result 6999 // type, and extract the first element. 7000 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 7001 if (isTypeLegal(BVT)) { 7002 SDValue BVec = DAG.getBitcast(BVT, Op0); 7003 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 7004 DAG.getConstant(0, DL, XLenVT))); 7005 } 7006 } 7007 break; 7008 } 7009 case RISCVISD::GREV: 7010 case RISCVISD::GORC: 7011 case RISCVISD::SHFL: { 7012 MVT VT = N->getSimpleValueType(0); 7013 MVT XLenVT = Subtarget.getXLenVT(); 7014 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) && 7015 "Unexpected custom legalisation"); 7016 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 7017 assert((Subtarget.hasStdExtZbp() || 7018 (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV && 7019 N->getConstantOperandVal(1) == 7)) && 7020 "Unexpected extension"); 7021 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7022 SDValue NewOp1 = 7023 DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1)); 7024 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1); 7025 // ReplaceNodeResults requires we maintain the same type for the return 7026 // value. 7027 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes)); 7028 break; 7029 } 7030 case ISD::BSWAP: 7031 case ISD::BITREVERSE: { 7032 MVT VT = N->getSimpleValueType(0); 7033 MVT XLenVT = Subtarget.getXLenVT(); 7034 assert((VT == MVT::i8 || VT == MVT::i16 || 7035 (VT == MVT::i32 && Subtarget.is64Bit())) && 7036 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 7037 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7038 unsigned Imm = VT.getSizeInBits() - 1; 7039 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 7040 if (N->getOpcode() == ISD::BSWAP) 7041 Imm &= ~0x7U; 7042 SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0, 7043 DAG.getConstant(Imm, DL, XLenVT)); 7044 // ReplaceNodeResults requires we maintain the same type for the return 7045 // value. 7046 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 7047 break; 7048 } 7049 case ISD::FSHL: 7050 case ISD::FSHR: { 7051 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7052 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 7053 SDValue NewOp0 = 7054 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7055 SDValue NewOp1 = 7056 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7057 SDValue NewShAmt = 7058 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7059 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 7060 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 7061 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 7062 DAG.getConstant(0x1f, DL, MVT::i64)); 7063 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 7064 // instruction use different orders. fshl will return its first operand for 7065 // shift of zero, fshr will return its second operand. fsl and fsr both 7066 // return rs1 so the ISD nodes need to have different operand orders. 7067 // Shift amount is in rs2. 7068 unsigned Opc = RISCVISD::FSLW; 7069 if (N->getOpcode() == ISD::FSHR) { 7070 std::swap(NewOp0, NewOp1); 7071 Opc = RISCVISD::FSRW; 7072 } 7073 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 7074 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 7075 break; 7076 } 7077 case ISD::EXTRACT_VECTOR_ELT: { 7078 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 7079 // type is illegal (currently only vXi64 RV32). 7080 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 7081 // transferred to the destination register. We issue two of these from the 7082 // upper- and lower- halves of the SEW-bit vector element, slid down to the 7083 // first element. 7084 SDValue Vec = N->getOperand(0); 7085 SDValue Idx = N->getOperand(1); 7086 7087 // The vector type hasn't been legalized yet so we can't issue target 7088 // specific nodes if it needs legalization. 7089 // FIXME: We would manually legalize if it's important. 7090 if (!isTypeLegal(Vec.getValueType())) 7091 return; 7092 7093 MVT VecVT = Vec.getSimpleValueType(); 7094 7095 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 7096 VecVT.getVectorElementType() == MVT::i64 && 7097 "Unexpected EXTRACT_VECTOR_ELT legalization"); 7098 7099 // If this is a fixed vector, we need to convert it to a scalable vector. 7100 MVT ContainerVT = VecVT; 7101 if (VecVT.isFixedLengthVector()) { 7102 ContainerVT = getContainerForFixedLengthVector(VecVT); 7103 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 7104 } 7105 7106 MVT XLenVT = Subtarget.getXLenVT(); 7107 7108 // Use a VL of 1 to avoid processing more elements than we need. 7109 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7110 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 7111 7112 // Unless the index is known to be 0, we must slide the vector down to get 7113 // the desired element into index 0. 7114 if (!isNullConstant(Idx)) { 7115 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 7116 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 7117 } 7118 7119 // Extract the lower XLEN bits of the correct vector element. 7120 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7121 7122 // To extract the upper XLEN bits of the vector element, shift the first 7123 // element right by 32 bits and re-extract the lower XLEN bits. 7124 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 7125 DAG.getUNDEF(ContainerVT), 7126 DAG.getConstant(32, DL, XLenVT), VL); 7127 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 7128 ThirtyTwoV, Mask, VL); 7129 7130 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7131 7132 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7133 break; 7134 } 7135 case ISD::INTRINSIC_WO_CHAIN: { 7136 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7137 switch (IntNo) { 7138 default: 7139 llvm_unreachable( 7140 "Don't know how to custom type legalize this intrinsic!"); 7141 case Intrinsic::riscv_grev: 7142 case Intrinsic::riscv_gorc: { 7143 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7144 "Unexpected custom legalisation"); 7145 SDValue NewOp1 = 7146 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7147 SDValue NewOp2 = 7148 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7149 unsigned Opc = 7150 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 7151 // If the control is a constant, promote the node by clearing any extra 7152 // bits bits in the control. isel will form greviw/gorciw if the result is 7153 // sign extended. 7154 if (isa<ConstantSDNode>(NewOp2)) { 7155 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7156 DAG.getConstant(0x1f, DL, MVT::i64)); 7157 Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 7158 } 7159 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7160 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7161 break; 7162 } 7163 case Intrinsic::riscv_bcompress: 7164 case Intrinsic::riscv_bdecompress: 7165 case Intrinsic::riscv_bfp: 7166 case Intrinsic::riscv_fsl: 7167 case Intrinsic::riscv_fsr: { 7168 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7169 "Unexpected custom legalisation"); 7170 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 7171 break; 7172 } 7173 case Intrinsic::riscv_orc_b: { 7174 // Lower to the GORCI encoding for orc.b with the operand extended. 7175 SDValue NewOp = 7176 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7177 SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp, 7178 DAG.getConstant(7, DL, MVT::i64)); 7179 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7180 return; 7181 } 7182 case Intrinsic::riscv_shfl: 7183 case Intrinsic::riscv_unshfl: { 7184 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7185 "Unexpected custom legalisation"); 7186 SDValue NewOp1 = 7187 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7188 SDValue NewOp2 = 7189 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7190 unsigned Opc = 7191 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 7192 // There is no (UN)SHFLIW. If the control word is a constant, we can use 7193 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 7194 // will be shuffled the same way as the lower 32 bit half, but the two 7195 // halves won't cross. 7196 if (isa<ConstantSDNode>(NewOp2)) { 7197 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7198 DAG.getConstant(0xf, DL, MVT::i64)); 7199 Opc = 7200 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 7201 } 7202 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7203 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7204 break; 7205 } 7206 case Intrinsic::riscv_vmv_x_s: { 7207 EVT VT = N->getValueType(0); 7208 MVT XLenVT = Subtarget.getXLenVT(); 7209 if (VT.bitsLT(XLenVT)) { 7210 // Simple case just extract using vmv.x.s and truncate. 7211 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 7212 Subtarget.getXLenVT(), N->getOperand(1)); 7213 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 7214 return; 7215 } 7216 7217 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 7218 "Unexpected custom legalization"); 7219 7220 // We need to do the move in two steps. 7221 SDValue Vec = N->getOperand(1); 7222 MVT VecVT = Vec.getSimpleValueType(); 7223 7224 // First extract the lower XLEN bits of the element. 7225 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7226 7227 // To extract the upper XLEN bits of the vector element, shift the first 7228 // element right by 32 bits and re-extract the lower XLEN bits. 7229 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7230 SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG); 7231 7232 SDValue ThirtyTwoV = 7233 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 7234 DAG.getConstant(32, DL, XLenVT), VL); 7235 SDValue LShr32 = 7236 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 7237 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7238 7239 Results.push_back( 7240 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7241 break; 7242 } 7243 } 7244 break; 7245 } 7246 case ISD::VECREDUCE_ADD: 7247 case ISD::VECREDUCE_AND: 7248 case ISD::VECREDUCE_OR: 7249 case ISD::VECREDUCE_XOR: 7250 case ISD::VECREDUCE_SMAX: 7251 case ISD::VECREDUCE_UMAX: 7252 case ISD::VECREDUCE_SMIN: 7253 case ISD::VECREDUCE_UMIN: 7254 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 7255 Results.push_back(V); 7256 break; 7257 case ISD::VP_REDUCE_ADD: 7258 case ISD::VP_REDUCE_AND: 7259 case ISD::VP_REDUCE_OR: 7260 case ISD::VP_REDUCE_XOR: 7261 case ISD::VP_REDUCE_SMAX: 7262 case ISD::VP_REDUCE_UMAX: 7263 case ISD::VP_REDUCE_SMIN: 7264 case ISD::VP_REDUCE_UMIN: 7265 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 7266 Results.push_back(V); 7267 break; 7268 case ISD::FLT_ROUNDS_: { 7269 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7270 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7271 Results.push_back(Res.getValue(0)); 7272 Results.push_back(Res.getValue(1)); 7273 break; 7274 } 7275 } 7276 } 7277 7278 // A structure to hold one of the bit-manipulation patterns below. Together, a 7279 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7280 // (or (and (shl x, 1), 0xAAAAAAAA), 7281 // (and (srl x, 1), 0x55555555)) 7282 struct RISCVBitmanipPat { 7283 SDValue Op; 7284 unsigned ShAmt; 7285 bool IsSHL; 7286 7287 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7288 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7289 } 7290 }; 7291 7292 // Matches patterns of the form 7293 // (and (shl x, C2), (C1 << C2)) 7294 // (and (srl x, C2), C1) 7295 // (shl (and x, C1), C2) 7296 // (srl (and x, (C1 << C2)), C2) 7297 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7298 // The expected masks for each shift amount are specified in BitmanipMasks where 7299 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7300 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7301 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7302 // XLen is 64. 7303 static Optional<RISCVBitmanipPat> 7304 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7305 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7306 "Unexpected number of masks"); 7307 Optional<uint64_t> Mask; 7308 // Optionally consume a mask around the shift operation. 7309 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7310 Mask = Op.getConstantOperandVal(1); 7311 Op = Op.getOperand(0); 7312 } 7313 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7314 return None; 7315 bool IsSHL = Op.getOpcode() == ISD::SHL; 7316 7317 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7318 return None; 7319 uint64_t ShAmt = Op.getConstantOperandVal(1); 7320 7321 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7322 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7323 return None; 7324 // If we don't have enough masks for 64 bit, then we must be trying to 7325 // match SHFL so we're only allowed to shift 1/4 of the width. 7326 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7327 return None; 7328 7329 SDValue Src = Op.getOperand(0); 7330 7331 // The expected mask is shifted left when the AND is found around SHL 7332 // patterns. 7333 // ((x >> 1) & 0x55555555) 7334 // ((x << 1) & 0xAAAAAAAA) 7335 bool SHLExpMask = IsSHL; 7336 7337 if (!Mask) { 7338 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7339 // the mask is all ones: consume that now. 7340 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7341 Mask = Src.getConstantOperandVal(1); 7342 Src = Src.getOperand(0); 7343 // The expected mask is now in fact shifted left for SRL, so reverse the 7344 // decision. 7345 // ((x & 0xAAAAAAAA) >> 1) 7346 // ((x & 0x55555555) << 1) 7347 SHLExpMask = !SHLExpMask; 7348 } else { 7349 // Use a default shifted mask of all-ones if there's no AND, truncated 7350 // down to the expected width. This simplifies the logic later on. 7351 Mask = maskTrailingOnes<uint64_t>(Width); 7352 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7353 } 7354 } 7355 7356 unsigned MaskIdx = Log2_32(ShAmt); 7357 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7358 7359 if (SHLExpMask) 7360 ExpMask <<= ShAmt; 7361 7362 if (Mask != ExpMask) 7363 return None; 7364 7365 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7366 } 7367 7368 // Matches any of the following bit-manipulation patterns: 7369 // (and (shl x, 1), (0x55555555 << 1)) 7370 // (and (srl x, 1), 0x55555555) 7371 // (shl (and x, 0x55555555), 1) 7372 // (srl (and x, (0x55555555 << 1)), 1) 7373 // where the shift amount and mask may vary thus: 7374 // [1] = 0x55555555 / 0xAAAAAAAA 7375 // [2] = 0x33333333 / 0xCCCCCCCC 7376 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7377 // [8] = 0x00FF00FF / 0xFF00FF00 7378 // [16] = 0x0000FFFF / 0xFFFFFFFF 7379 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7380 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7381 // These are the unshifted masks which we use to match bit-manipulation 7382 // patterns. They may be shifted left in certain circumstances. 7383 static const uint64_t BitmanipMasks[] = { 7384 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7385 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7386 7387 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7388 } 7389 7390 // Match the following pattern as a GREVI(W) operation 7391 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7392 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7393 const RISCVSubtarget &Subtarget) { 7394 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7395 EVT VT = Op.getValueType(); 7396 7397 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7398 auto LHS = matchGREVIPat(Op.getOperand(0)); 7399 auto RHS = matchGREVIPat(Op.getOperand(1)); 7400 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7401 SDLoc DL(Op); 7402 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7403 DAG.getConstant(LHS->ShAmt, DL, VT)); 7404 } 7405 } 7406 return SDValue(); 7407 } 7408 7409 // Matches any the following pattern as a GORCI(W) operation 7410 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7411 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7412 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7413 // Note that with the variant of 3., 7414 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7415 // the inner pattern will first be matched as GREVI and then the outer 7416 // pattern will be matched to GORC via the first rule above. 7417 // 4. (or (rotl/rotr x, bitwidth/2), x) 7418 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7419 const RISCVSubtarget &Subtarget) { 7420 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7421 EVT VT = Op.getValueType(); 7422 7423 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7424 SDLoc DL(Op); 7425 SDValue Op0 = Op.getOperand(0); 7426 SDValue Op1 = Op.getOperand(1); 7427 7428 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7429 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7430 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7431 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7432 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7433 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7434 if ((Reverse.getOpcode() == ISD::ROTL || 7435 Reverse.getOpcode() == ISD::ROTR) && 7436 Reverse.getOperand(0) == X && 7437 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7438 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7439 if (RotAmt == (VT.getSizeInBits() / 2)) 7440 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7441 DAG.getConstant(RotAmt, DL, VT)); 7442 } 7443 return SDValue(); 7444 }; 7445 7446 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7447 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7448 return V; 7449 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7450 return V; 7451 7452 // OR is commutable so canonicalize its OR operand to the left 7453 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7454 std::swap(Op0, Op1); 7455 if (Op0.getOpcode() != ISD::OR) 7456 return SDValue(); 7457 SDValue OrOp0 = Op0.getOperand(0); 7458 SDValue OrOp1 = Op0.getOperand(1); 7459 auto LHS = matchGREVIPat(OrOp0); 7460 // OR is commutable so swap the operands and try again: x might have been 7461 // on the left 7462 if (!LHS) { 7463 std::swap(OrOp0, OrOp1); 7464 LHS = matchGREVIPat(OrOp0); 7465 } 7466 auto RHS = matchGREVIPat(Op1); 7467 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7468 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7469 DAG.getConstant(LHS->ShAmt, DL, VT)); 7470 } 7471 } 7472 return SDValue(); 7473 } 7474 7475 // Matches any of the following bit-manipulation patterns: 7476 // (and (shl x, 1), (0x22222222 << 1)) 7477 // (and (srl x, 1), 0x22222222) 7478 // (shl (and x, 0x22222222), 1) 7479 // (srl (and x, (0x22222222 << 1)), 1) 7480 // where the shift amount and mask may vary thus: 7481 // [1] = 0x22222222 / 0x44444444 7482 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7483 // [4] = 0x00F000F0 / 0x0F000F00 7484 // [8] = 0x0000FF00 / 0x00FF0000 7485 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7486 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7487 // These are the unshifted masks which we use to match bit-manipulation 7488 // patterns. They may be shifted left in certain circumstances. 7489 static const uint64_t BitmanipMasks[] = { 7490 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7491 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7492 7493 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7494 } 7495 7496 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7497 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7498 const RISCVSubtarget &Subtarget) { 7499 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7500 EVT VT = Op.getValueType(); 7501 7502 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7503 return SDValue(); 7504 7505 SDValue Op0 = Op.getOperand(0); 7506 SDValue Op1 = Op.getOperand(1); 7507 7508 // Or is commutable so canonicalize the second OR to the LHS. 7509 if (Op0.getOpcode() != ISD::OR) 7510 std::swap(Op0, Op1); 7511 if (Op0.getOpcode() != ISD::OR) 7512 return SDValue(); 7513 7514 // We found an inner OR, so our operands are the operands of the inner OR 7515 // and the other operand of the outer OR. 7516 SDValue A = Op0.getOperand(0); 7517 SDValue B = Op0.getOperand(1); 7518 SDValue C = Op1; 7519 7520 auto Match1 = matchSHFLPat(A); 7521 auto Match2 = matchSHFLPat(B); 7522 7523 // If neither matched, we failed. 7524 if (!Match1 && !Match2) 7525 return SDValue(); 7526 7527 // We had at least one match. if one failed, try the remaining C operand. 7528 if (!Match1) { 7529 std::swap(A, C); 7530 Match1 = matchSHFLPat(A); 7531 if (!Match1) 7532 return SDValue(); 7533 } else if (!Match2) { 7534 std::swap(B, C); 7535 Match2 = matchSHFLPat(B); 7536 if (!Match2) 7537 return SDValue(); 7538 } 7539 assert(Match1 && Match2); 7540 7541 // Make sure our matches pair up. 7542 if (!Match1->formsPairWith(*Match2)) 7543 return SDValue(); 7544 7545 // All the remains is to make sure C is an AND with the same input, that masks 7546 // out the bits that are being shuffled. 7547 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7548 C.getOperand(0) != Match1->Op) 7549 return SDValue(); 7550 7551 uint64_t Mask = C.getConstantOperandVal(1); 7552 7553 static const uint64_t BitmanipMasks[] = { 7554 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7555 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7556 }; 7557 7558 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7559 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7560 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7561 7562 if (Mask != ExpMask) 7563 return SDValue(); 7564 7565 SDLoc DL(Op); 7566 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7567 DAG.getConstant(Match1->ShAmt, DL, VT)); 7568 } 7569 7570 // Optimize (add (shl x, c0), (shl y, c1)) -> 7571 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7572 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7573 const RISCVSubtarget &Subtarget) { 7574 // Perform this optimization only in the zba extension. 7575 if (!Subtarget.hasStdExtZba()) 7576 return SDValue(); 7577 7578 // Skip for vector types and larger types. 7579 EVT VT = N->getValueType(0); 7580 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7581 return SDValue(); 7582 7583 // The two operand nodes must be SHL and have no other use. 7584 SDValue N0 = N->getOperand(0); 7585 SDValue N1 = N->getOperand(1); 7586 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7587 !N0->hasOneUse() || !N1->hasOneUse()) 7588 return SDValue(); 7589 7590 // Check c0 and c1. 7591 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7592 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7593 if (!N0C || !N1C) 7594 return SDValue(); 7595 int64_t C0 = N0C->getSExtValue(); 7596 int64_t C1 = N1C->getSExtValue(); 7597 if (C0 <= 0 || C1 <= 0) 7598 return SDValue(); 7599 7600 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7601 int64_t Bits = std::min(C0, C1); 7602 int64_t Diff = std::abs(C0 - C1); 7603 if (Diff != 1 && Diff != 2 && Diff != 3) 7604 return SDValue(); 7605 7606 // Build nodes. 7607 SDLoc DL(N); 7608 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7609 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7610 SDValue NA0 = 7611 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7612 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7613 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7614 } 7615 7616 // Combine 7617 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7618 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7619 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7620 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7621 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7622 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7623 // The grev patterns represents BSWAP. 7624 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7625 // off the grev. 7626 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7627 const RISCVSubtarget &Subtarget) { 7628 bool IsWInstruction = 7629 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7630 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7631 IsWInstruction) && 7632 "Unexpected opcode!"); 7633 SDValue Src = N->getOperand(0); 7634 EVT VT = N->getValueType(0); 7635 SDLoc DL(N); 7636 7637 if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV) 7638 return SDValue(); 7639 7640 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7641 !isa<ConstantSDNode>(Src.getOperand(1))) 7642 return SDValue(); 7643 7644 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7645 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7646 7647 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7648 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7649 unsigned ShAmt1 = N->getConstantOperandVal(1); 7650 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7651 if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7652 return SDValue(); 7653 7654 Src = Src.getOperand(0); 7655 7656 // Toggle bit the MSB of the shift. 7657 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7658 if (CombinedShAmt == 0) 7659 return Src; 7660 7661 SDValue Res = DAG.getNode( 7662 RISCVISD::GREV, DL, VT, Src, 7663 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7664 if (!IsWInstruction) 7665 return Res; 7666 7667 // Sign extend the result to match the behavior of the rotate. This will be 7668 // selected to GREVIW in isel. 7669 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res, 7670 DAG.getValueType(MVT::i32)); 7671 } 7672 7673 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7674 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7675 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7676 // not undo itself, but they are redundant. 7677 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7678 bool IsGORC = N->getOpcode() == RISCVISD::GORC; 7679 assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode"); 7680 SDValue Src = N->getOperand(0); 7681 7682 if (Src.getOpcode() != N->getOpcode()) 7683 return SDValue(); 7684 7685 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7686 !isa<ConstantSDNode>(Src.getOperand(1))) 7687 return SDValue(); 7688 7689 unsigned ShAmt1 = N->getConstantOperandVal(1); 7690 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7691 Src = Src.getOperand(0); 7692 7693 unsigned CombinedShAmt; 7694 if (IsGORC) 7695 CombinedShAmt = ShAmt1 | ShAmt2; 7696 else 7697 CombinedShAmt = ShAmt1 ^ ShAmt2; 7698 7699 if (CombinedShAmt == 0) 7700 return Src; 7701 7702 SDLoc DL(N); 7703 return DAG.getNode( 7704 N->getOpcode(), DL, N->getValueType(0), Src, 7705 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7706 } 7707 7708 // Combine a constant select operand into its use: 7709 // 7710 // (and (select cond, -1, c), x) 7711 // -> (select cond, x, (and x, c)) [AllOnes=1] 7712 // (or (select cond, 0, c), x) 7713 // -> (select cond, x, (or x, c)) [AllOnes=0] 7714 // (xor (select cond, 0, c), x) 7715 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7716 // (add (select cond, 0, c), x) 7717 // -> (select cond, x, (add x, c)) [AllOnes=0] 7718 // (sub x, (select cond, 0, c)) 7719 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7720 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7721 SelectionDAG &DAG, bool AllOnes) { 7722 EVT VT = N->getValueType(0); 7723 7724 // Skip vectors. 7725 if (VT.isVector()) 7726 return SDValue(); 7727 7728 if ((Slct.getOpcode() != ISD::SELECT && 7729 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7730 !Slct.hasOneUse()) 7731 return SDValue(); 7732 7733 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7734 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7735 }; 7736 7737 bool SwapSelectOps; 7738 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7739 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7740 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7741 SDValue NonConstantVal; 7742 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7743 SwapSelectOps = false; 7744 NonConstantVal = FalseVal; 7745 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7746 SwapSelectOps = true; 7747 NonConstantVal = TrueVal; 7748 } else 7749 return SDValue(); 7750 7751 // Slct is now know to be the desired identity constant when CC is true. 7752 TrueVal = OtherOp; 7753 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7754 // Unless SwapSelectOps says the condition should be false. 7755 if (SwapSelectOps) 7756 std::swap(TrueVal, FalseVal); 7757 7758 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7759 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7760 {Slct.getOperand(0), Slct.getOperand(1), 7761 Slct.getOperand(2), TrueVal, FalseVal}); 7762 7763 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7764 {Slct.getOperand(0), TrueVal, FalseVal}); 7765 } 7766 7767 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7768 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7769 bool AllOnes) { 7770 SDValue N0 = N->getOperand(0); 7771 SDValue N1 = N->getOperand(1); 7772 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7773 return Result; 7774 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7775 return Result; 7776 return SDValue(); 7777 } 7778 7779 // Transform (add (mul x, c0), c1) -> 7780 // (add (mul (add x, c1/c0), c0), c1%c0). 7781 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7782 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7783 // to an infinite loop in DAGCombine if transformed. 7784 // Or transform (add (mul x, c0), c1) -> 7785 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7786 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7787 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7788 // lead to an infinite loop in DAGCombine if transformed. 7789 // Or transform (add (mul x, c0), c1) -> 7790 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7791 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7792 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7793 // lead to an infinite loop in DAGCombine if transformed. 7794 // Or transform (add (mul x, c0), c1) -> 7795 // (mul (add x, c1/c0), c0). 7796 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7797 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7798 const RISCVSubtarget &Subtarget) { 7799 // Skip for vector types and larger types. 7800 EVT VT = N->getValueType(0); 7801 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7802 return SDValue(); 7803 // The first operand node must be a MUL and has no other use. 7804 SDValue N0 = N->getOperand(0); 7805 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7806 return SDValue(); 7807 // Check if c0 and c1 match above conditions. 7808 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7809 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7810 if (!N0C || !N1C) 7811 return SDValue(); 7812 // If N0C has multiple uses it's possible one of the cases in 7813 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 7814 // in an infinite loop. 7815 if (!N0C->hasOneUse()) 7816 return SDValue(); 7817 int64_t C0 = N0C->getSExtValue(); 7818 int64_t C1 = N1C->getSExtValue(); 7819 int64_t CA, CB; 7820 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7821 return SDValue(); 7822 // Search for proper CA (non-zero) and CB that both are simm12. 7823 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7824 !isInt<12>(C0 * (C1 / C0))) { 7825 CA = C1 / C0; 7826 CB = C1 % C0; 7827 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7828 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7829 CA = C1 / C0 + 1; 7830 CB = C1 % C0 - C0; 7831 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7832 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7833 CA = C1 / C0 - 1; 7834 CB = C1 % C0 + C0; 7835 } else 7836 return SDValue(); 7837 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7838 SDLoc DL(N); 7839 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7840 DAG.getConstant(CA, DL, VT)); 7841 SDValue New1 = 7842 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7843 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7844 } 7845 7846 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7847 const RISCVSubtarget &Subtarget) { 7848 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7849 return V; 7850 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7851 return V; 7852 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7853 // (select lhs, rhs, cc, x, (add x, y)) 7854 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7855 } 7856 7857 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7858 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 7859 // (select lhs, rhs, cc, x, (sub x, y)) 7860 SDValue N0 = N->getOperand(0); 7861 SDValue N1 = N->getOperand(1); 7862 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 7863 } 7864 7865 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG) { 7866 // fold (and (select lhs, rhs, cc, -1, y), x) -> 7867 // (select lhs, rhs, cc, x, (and x, y)) 7868 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 7869 } 7870 7871 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 7872 const RISCVSubtarget &Subtarget) { 7873 if (Subtarget.hasStdExtZbp()) { 7874 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 7875 return GREV; 7876 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 7877 return GORC; 7878 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 7879 return SHFL; 7880 } 7881 7882 // fold (or (select cond, 0, y), x) -> 7883 // (select cond, x, (or x, y)) 7884 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7885 } 7886 7887 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 7888 SDValue N0 = N->getOperand(0); 7889 SDValue N1 = N->getOperand(1); 7890 7891 // fold (xor (sllw 1, x), -1) -> (rolw ~1, x) 7892 // NOTE: Assumes ROL being legal means ROLW is legal. 7893 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7894 if (N0.getOpcode() == RISCVISD::SLLW && 7895 isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) && 7896 TLI.isOperationLegal(ISD::ROTL, MVT::i64)) { 7897 SDLoc DL(N); 7898 return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64, 7899 DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1)); 7900 } 7901 7902 // fold (xor (select cond, 0, y), x) -> 7903 // (select cond, x, (xor x, y)) 7904 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7905 } 7906 7907 static SDValue 7908 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 7909 const RISCVSubtarget &Subtarget) { 7910 SDValue Src = N->getOperand(0); 7911 EVT VT = N->getValueType(0); 7912 7913 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 7914 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 7915 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 7916 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 7917 Src.getOperand(0)); 7918 7919 // Fold (i64 (sext_inreg (abs X), i32)) -> 7920 // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits. 7921 // The (sext_inreg (neg X), i32) will be selected to negw by isel. This 7922 // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user 7923 // of the (i32 (abs X)) is a sext or setcc or something else that causes type 7924 // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have 7925 // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg 7926 // may get combined into an earlier operation so we need to use 7927 // ComputeNumSignBits. 7928 // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for 7929 // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so 7930 // we can't assume that X has 33 sign bits. We must check. 7931 if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() && 7932 Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 && 7933 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 && 7934 DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) { 7935 SDLoc DL(N); 7936 SDValue Freeze = DAG.getFreeze(Src.getOperand(0)); 7937 SDValue Neg = 7938 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze); 7939 Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg, 7940 DAG.getValueType(MVT::i32)); 7941 return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg); 7942 } 7943 7944 return SDValue(); 7945 } 7946 7947 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 7948 // vwadd(u).vv/vx or vwsub(u).vv/vx. 7949 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 7950 bool Commute = false) { 7951 assert((N->getOpcode() == RISCVISD::ADD_VL || 7952 N->getOpcode() == RISCVISD::SUB_VL) && 7953 "Unexpected opcode"); 7954 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 7955 SDValue Op0 = N->getOperand(0); 7956 SDValue Op1 = N->getOperand(1); 7957 if (Commute) 7958 std::swap(Op0, Op1); 7959 7960 MVT VT = N->getSimpleValueType(0); 7961 7962 // Determine the narrow size for a widening add/sub. 7963 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 7964 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 7965 VT.getVectorElementCount()); 7966 7967 SDValue Mask = N->getOperand(2); 7968 SDValue VL = N->getOperand(3); 7969 7970 SDLoc DL(N); 7971 7972 // If the RHS is a sext or zext, we can form a widening op. 7973 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 7974 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 7975 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 7976 unsigned ExtOpc = Op1.getOpcode(); 7977 Op1 = Op1.getOperand(0); 7978 // Re-introduce narrower extends if needed. 7979 if (Op1.getValueType() != NarrowVT) 7980 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 7981 7982 unsigned WOpc; 7983 if (ExtOpc == RISCVISD::VSEXT_VL) 7984 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 7985 else 7986 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 7987 7988 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 7989 } 7990 7991 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 7992 // sext/zext? 7993 7994 return SDValue(); 7995 } 7996 7997 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 7998 // vwsub(u).vv/vx. 7999 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 8000 SDValue Op0 = N->getOperand(0); 8001 SDValue Op1 = N->getOperand(1); 8002 SDValue Mask = N->getOperand(2); 8003 SDValue VL = N->getOperand(3); 8004 8005 MVT VT = N->getSimpleValueType(0); 8006 MVT NarrowVT = Op1.getSimpleValueType(); 8007 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 8008 8009 unsigned VOpc; 8010 switch (N->getOpcode()) { 8011 default: llvm_unreachable("Unexpected opcode"); 8012 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 8013 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 8014 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 8015 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 8016 } 8017 8018 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 8019 N->getOpcode() == RISCVISD::VWSUB_W_VL; 8020 8021 SDLoc DL(N); 8022 8023 // If the LHS is a sext or zext, we can narrow this op to the same size as 8024 // the RHS. 8025 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 8026 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 8027 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 8028 unsigned ExtOpc = Op0.getOpcode(); 8029 Op0 = Op0.getOperand(0); 8030 // Re-introduce narrower extends if needed. 8031 if (Op0.getValueType() != NarrowVT) 8032 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8033 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 8034 } 8035 8036 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 8037 N->getOpcode() == RISCVISD::VWADDU_W_VL; 8038 8039 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 8040 // to commute and use a vwadd(u).vx instead. 8041 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 8042 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 8043 Op0 = Op0.getOperand(1); 8044 8045 // See if have enough sign bits or zero bits in the scalar to use a 8046 // widening add/sub by splatting to smaller element size. 8047 unsigned EltBits = VT.getScalarSizeInBits(); 8048 unsigned ScalarBits = Op0.getValueSizeInBits(); 8049 // Make sure we're getting all element bits from the scalar register. 8050 // FIXME: Support implicit sign extension of vmv.v.x? 8051 if (ScalarBits < EltBits) 8052 return SDValue(); 8053 8054 if (IsSigned) { 8055 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 8056 return SDValue(); 8057 } else { 8058 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8059 if (!DAG.MaskedValueIsZero(Op0, Mask)) 8060 return SDValue(); 8061 } 8062 8063 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8064 DAG.getUNDEF(NarrowVT), Op0, VL); 8065 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 8066 } 8067 8068 return SDValue(); 8069 } 8070 8071 // Try to form VWMUL, VWMULU or VWMULSU. 8072 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 8073 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 8074 bool Commute) { 8075 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 8076 SDValue Op0 = N->getOperand(0); 8077 SDValue Op1 = N->getOperand(1); 8078 if (Commute) 8079 std::swap(Op0, Op1); 8080 8081 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 8082 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 8083 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 8084 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 8085 return SDValue(); 8086 8087 SDValue Mask = N->getOperand(2); 8088 SDValue VL = N->getOperand(3); 8089 8090 // Make sure the mask and VL match. 8091 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 8092 return SDValue(); 8093 8094 MVT VT = N->getSimpleValueType(0); 8095 8096 // Determine the narrow size for a widening multiply. 8097 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8098 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8099 VT.getVectorElementCount()); 8100 8101 SDLoc DL(N); 8102 8103 // See if the other operand is the same opcode. 8104 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 8105 if (!Op1.hasOneUse()) 8106 return SDValue(); 8107 8108 // Make sure the mask and VL match. 8109 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 8110 return SDValue(); 8111 8112 Op1 = Op1.getOperand(0); 8113 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 8114 // The operand is a splat of a scalar. 8115 8116 // The pasthru must be undef for tail agnostic 8117 if (!Op1.getOperand(0).isUndef()) 8118 return SDValue(); 8119 // The VL must be the same. 8120 if (Op1.getOperand(2) != VL) 8121 return SDValue(); 8122 8123 // Get the scalar value. 8124 Op1 = Op1.getOperand(1); 8125 8126 // See if have enough sign bits or zero bits in the scalar to use a 8127 // widening multiply by splatting to smaller element size. 8128 unsigned EltBits = VT.getScalarSizeInBits(); 8129 unsigned ScalarBits = Op1.getValueSizeInBits(); 8130 // Make sure we're getting all element bits from the scalar register. 8131 // FIXME: Support implicit sign extension of vmv.v.x? 8132 if (ScalarBits < EltBits) 8133 return SDValue(); 8134 8135 // If the LHS is a sign extend, try to use vwmul. 8136 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 8137 // Can use vwmul. 8138 } else { 8139 // Otherwise try to use vwmulu or vwmulsu. 8140 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8141 if (DAG.MaskedValueIsZero(Op1, Mask)) 8142 IsVWMULSU = IsSignExt; 8143 else 8144 return SDValue(); 8145 } 8146 8147 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8148 DAG.getUNDEF(NarrowVT), Op1, VL); 8149 } else 8150 return SDValue(); 8151 8152 Op0 = Op0.getOperand(0); 8153 8154 // Re-introduce narrower extends if needed. 8155 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 8156 if (Op0.getValueType() != NarrowVT) 8157 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8158 // vwmulsu requires second operand to be zero extended. 8159 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 8160 if (Op1.getValueType() != NarrowVT) 8161 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8162 8163 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 8164 if (!IsVWMULSU) 8165 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 8166 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 8167 } 8168 8169 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 8170 switch (Op.getOpcode()) { 8171 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 8172 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 8173 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 8174 case ISD::FCEIL: return RISCVFPRndMode::RUP; 8175 case ISD::FROUND: return RISCVFPRndMode::RMM; 8176 } 8177 8178 return RISCVFPRndMode::Invalid; 8179 } 8180 8181 // Fold 8182 // (fp_to_int (froundeven X)) -> fcvt X, rne 8183 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 8184 // (fp_to_int (ffloor X)) -> fcvt X, rdn 8185 // (fp_to_int (fceil X)) -> fcvt X, rup 8186 // (fp_to_int (fround X)) -> fcvt X, rmm 8187 static SDValue performFP_TO_INTCombine(SDNode *N, 8188 TargetLowering::DAGCombinerInfo &DCI, 8189 const RISCVSubtarget &Subtarget) { 8190 SelectionDAG &DAG = DCI.DAG; 8191 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8192 MVT XLenVT = Subtarget.getXLenVT(); 8193 8194 // Only handle XLen or i32 types. Other types narrower than XLen will 8195 // eventually be legalized to XLenVT. 8196 EVT VT = N->getValueType(0); 8197 if (VT != MVT::i32 && VT != XLenVT) 8198 return SDValue(); 8199 8200 SDValue Src = N->getOperand(0); 8201 8202 // Ensure the FP type is also legal. 8203 if (!TLI.isTypeLegal(Src.getValueType())) 8204 return SDValue(); 8205 8206 // Don't do this for f16 with Zfhmin and not Zfh. 8207 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8208 return SDValue(); 8209 8210 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8211 if (FRM == RISCVFPRndMode::Invalid) 8212 return SDValue(); 8213 8214 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8215 8216 unsigned Opc; 8217 if (VT == XLenVT) 8218 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8219 else 8220 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8221 8222 SDLoc DL(N); 8223 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 8224 DAG.getTargetConstant(FRM, DL, XLenVT)); 8225 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 8226 } 8227 8228 // Fold 8229 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 8230 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 8231 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8232 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8233 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8234 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8235 TargetLowering::DAGCombinerInfo &DCI, 8236 const RISCVSubtarget &Subtarget) { 8237 SelectionDAG &DAG = DCI.DAG; 8238 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8239 MVT XLenVT = Subtarget.getXLenVT(); 8240 8241 // Only handle XLen types. Other types narrower than XLen will eventually be 8242 // legalized to XLenVT. 8243 EVT DstVT = N->getValueType(0); 8244 if (DstVT != XLenVT) 8245 return SDValue(); 8246 8247 SDValue Src = N->getOperand(0); 8248 8249 // Ensure the FP type is also legal. 8250 if (!TLI.isTypeLegal(Src.getValueType())) 8251 return SDValue(); 8252 8253 // Don't do this for f16 with Zfhmin and not Zfh. 8254 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8255 return SDValue(); 8256 8257 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8258 8259 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8260 if (FRM == RISCVFPRndMode::Invalid) 8261 return SDValue(); 8262 8263 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8264 8265 unsigned Opc; 8266 if (SatVT == DstVT) 8267 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8268 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8269 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8270 else 8271 return SDValue(); 8272 // FIXME: Support other SatVTs by clamping before or after the conversion. 8273 8274 Src = Src.getOperand(0); 8275 8276 SDLoc DL(N); 8277 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8278 DAG.getTargetConstant(FRM, DL, XLenVT)); 8279 8280 // RISCV FP-to-int conversions saturate to the destination register size, but 8281 // don't produce 0 for nan. 8282 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8283 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8284 } 8285 8286 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is 8287 // smaller than XLenVT. 8288 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG, 8289 const RISCVSubtarget &Subtarget) { 8290 assert(Subtarget.hasStdExtZbkb() && "Unexpected extension"); 8291 8292 SDValue Src = N->getOperand(0); 8293 if (Src.getOpcode() != ISD::BSWAP) 8294 return SDValue(); 8295 8296 EVT VT = N->getValueType(0); 8297 if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() || 8298 !isPowerOf2_32(VT.getSizeInBits())) 8299 return SDValue(); 8300 8301 SDLoc DL(N); 8302 return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0), 8303 DAG.getConstant(7, DL, VT)); 8304 } 8305 8306 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8307 DAGCombinerInfo &DCI) const { 8308 SelectionDAG &DAG = DCI.DAG; 8309 8310 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8311 // bits are demanded. N will be added to the Worklist if it was not deleted. 8312 // Caller should return SDValue(N, 0) if this returns true. 8313 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8314 SDValue Op = N->getOperand(OpNo); 8315 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8316 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8317 return false; 8318 8319 if (N->getOpcode() != ISD::DELETED_NODE) 8320 DCI.AddToWorklist(N); 8321 return true; 8322 }; 8323 8324 switch (N->getOpcode()) { 8325 default: 8326 break; 8327 case RISCVISD::SplitF64: { 8328 SDValue Op0 = N->getOperand(0); 8329 // If the input to SplitF64 is just BuildPairF64 then the operation is 8330 // redundant. Instead, use BuildPairF64's operands directly. 8331 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8332 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8333 8334 if (Op0->isUndef()) { 8335 SDValue Lo = DAG.getUNDEF(MVT::i32); 8336 SDValue Hi = DAG.getUNDEF(MVT::i32); 8337 return DCI.CombineTo(N, Lo, Hi); 8338 } 8339 8340 SDLoc DL(N); 8341 8342 // It's cheaper to materialise two 32-bit integers than to load a double 8343 // from the constant pool and transfer it to integer registers through the 8344 // stack. 8345 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8346 APInt V = C->getValueAPF().bitcastToAPInt(); 8347 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8348 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8349 return DCI.CombineTo(N, Lo, Hi); 8350 } 8351 8352 // This is a target-specific version of a DAGCombine performed in 8353 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8354 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8355 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8356 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8357 !Op0.getNode()->hasOneUse()) 8358 break; 8359 SDValue NewSplitF64 = 8360 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8361 Op0.getOperand(0)); 8362 SDValue Lo = NewSplitF64.getValue(0); 8363 SDValue Hi = NewSplitF64.getValue(1); 8364 APInt SignBit = APInt::getSignMask(32); 8365 if (Op0.getOpcode() == ISD::FNEG) { 8366 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8367 DAG.getConstant(SignBit, DL, MVT::i32)); 8368 return DCI.CombineTo(N, Lo, NewHi); 8369 } 8370 assert(Op0.getOpcode() == ISD::FABS); 8371 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8372 DAG.getConstant(~SignBit, DL, MVT::i32)); 8373 return DCI.CombineTo(N, Lo, NewHi); 8374 } 8375 case RISCVISD::SLLW: 8376 case RISCVISD::SRAW: 8377 case RISCVISD::SRLW: { 8378 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8379 if (SimplifyDemandedLowBitsHelper(0, 32) || 8380 SimplifyDemandedLowBitsHelper(1, 5)) 8381 return SDValue(N, 0); 8382 8383 break; 8384 } 8385 case ISD::ROTR: 8386 case ISD::ROTL: 8387 case RISCVISD::RORW: 8388 case RISCVISD::ROLW: { 8389 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8390 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8391 if (SimplifyDemandedLowBitsHelper(0, 32) || 8392 SimplifyDemandedLowBitsHelper(1, 5)) 8393 return SDValue(N, 0); 8394 } 8395 8396 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8397 } 8398 case RISCVISD::CLZW: 8399 case RISCVISD::CTZW: { 8400 // Only the lower 32 bits of the first operand are read 8401 if (SimplifyDemandedLowBitsHelper(0, 32)) 8402 return SDValue(N, 0); 8403 break; 8404 } 8405 case RISCVISD::GREV: 8406 case RISCVISD::GORC: { 8407 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8408 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8409 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8410 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8411 return SDValue(N, 0); 8412 8413 return combineGREVI_GORCI(N, DAG); 8414 } 8415 case RISCVISD::GREVW: 8416 case RISCVISD::GORCW: { 8417 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8418 if (SimplifyDemandedLowBitsHelper(0, 32) || 8419 SimplifyDemandedLowBitsHelper(1, 5)) 8420 return SDValue(N, 0); 8421 8422 break; 8423 } 8424 case RISCVISD::SHFL: 8425 case RISCVISD::UNSHFL: { 8426 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8427 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8428 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8429 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8430 return SDValue(N, 0); 8431 8432 break; 8433 } 8434 case RISCVISD::SHFLW: 8435 case RISCVISD::UNSHFLW: { 8436 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8437 if (SimplifyDemandedLowBitsHelper(0, 32) || 8438 SimplifyDemandedLowBitsHelper(1, 4)) 8439 return SDValue(N, 0); 8440 8441 break; 8442 } 8443 case RISCVISD::BCOMPRESSW: 8444 case RISCVISD::BDECOMPRESSW: { 8445 // Only the lower 32 bits of LHS and RHS are read. 8446 if (SimplifyDemandedLowBitsHelper(0, 32) || 8447 SimplifyDemandedLowBitsHelper(1, 32)) 8448 return SDValue(N, 0); 8449 8450 break; 8451 } 8452 case RISCVISD::FSR: 8453 case RISCVISD::FSL: 8454 case RISCVISD::FSRW: 8455 case RISCVISD::FSLW: { 8456 bool IsWInstruction = 8457 N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW; 8458 unsigned BitWidth = 8459 IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits(); 8460 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8461 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 8462 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1)) 8463 return SDValue(N, 0); 8464 8465 break; 8466 } 8467 case RISCVISD::FMV_X_ANYEXTH: 8468 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8469 SDLoc DL(N); 8470 SDValue Op0 = N->getOperand(0); 8471 MVT VT = N->getSimpleValueType(0); 8472 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8473 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8474 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8475 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8476 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8477 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8478 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8479 assert(Op0.getOperand(0).getValueType() == VT && 8480 "Unexpected value type!"); 8481 return Op0.getOperand(0); 8482 } 8483 8484 // This is a target-specific version of a DAGCombine performed in 8485 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8486 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8487 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8488 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8489 !Op0.getNode()->hasOneUse()) 8490 break; 8491 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8492 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8493 APInt SignBit = APInt::getSignMask(FPBits).sextOrSelf(VT.getSizeInBits()); 8494 if (Op0.getOpcode() == ISD::FNEG) 8495 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8496 DAG.getConstant(SignBit, DL, VT)); 8497 8498 assert(Op0.getOpcode() == ISD::FABS); 8499 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8500 DAG.getConstant(~SignBit, DL, VT)); 8501 } 8502 case ISD::ADD: 8503 return performADDCombine(N, DAG, Subtarget); 8504 case ISD::SUB: 8505 return performSUBCombine(N, DAG); 8506 case ISD::AND: 8507 return performANDCombine(N, DAG); 8508 case ISD::OR: 8509 return performORCombine(N, DAG, Subtarget); 8510 case ISD::XOR: 8511 return performXORCombine(N, DAG); 8512 case ISD::SIGN_EXTEND_INREG: 8513 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 8514 case ISD::ZERO_EXTEND: 8515 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8516 // type legalization. This is safe because fp_to_uint produces poison if 8517 // it overflows. 8518 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8519 SDValue Src = N->getOperand(0); 8520 if (Src.getOpcode() == ISD::FP_TO_UINT && 8521 isTypeLegal(Src.getOperand(0).getValueType())) 8522 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8523 Src.getOperand(0)); 8524 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8525 isTypeLegal(Src.getOperand(1).getValueType())) { 8526 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8527 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8528 Src.getOperand(0), Src.getOperand(1)); 8529 DCI.CombineTo(N, Res); 8530 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8531 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8532 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8533 } 8534 } 8535 return SDValue(); 8536 case RISCVISD::SELECT_CC: { 8537 // Transform 8538 SDValue LHS = N->getOperand(0); 8539 SDValue RHS = N->getOperand(1); 8540 SDValue TrueV = N->getOperand(3); 8541 SDValue FalseV = N->getOperand(4); 8542 8543 // If the True and False values are the same, we don't need a select_cc. 8544 if (TrueV == FalseV) 8545 return TrueV; 8546 8547 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8548 if (!ISD::isIntEqualitySetCC(CCVal)) 8549 break; 8550 8551 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8552 // (select_cc X, Y, lt, trueV, falseV) 8553 // Sometimes the setcc is introduced after select_cc has been formed. 8554 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8555 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8556 // If we're looking for eq 0 instead of ne 0, we need to invert the 8557 // condition. 8558 bool Invert = CCVal == ISD::SETEQ; 8559 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8560 if (Invert) 8561 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8562 8563 SDLoc DL(N); 8564 RHS = LHS.getOperand(1); 8565 LHS = LHS.getOperand(0); 8566 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8567 8568 SDValue TargetCC = DAG.getCondCode(CCVal); 8569 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8570 {LHS, RHS, TargetCC, TrueV, FalseV}); 8571 } 8572 8573 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8574 // (select_cc X, Y, eq/ne, trueV, falseV) 8575 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8576 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8577 {LHS.getOperand(0), LHS.getOperand(1), 8578 N->getOperand(2), TrueV, FalseV}); 8579 // (select_cc X, 1, setne, trueV, falseV) -> 8580 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8581 // This can occur when legalizing some floating point comparisons. 8582 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8583 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8584 SDLoc DL(N); 8585 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8586 SDValue TargetCC = DAG.getCondCode(CCVal); 8587 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8588 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8589 {LHS, RHS, TargetCC, TrueV, FalseV}); 8590 } 8591 8592 break; 8593 } 8594 case RISCVISD::BR_CC: { 8595 SDValue LHS = N->getOperand(1); 8596 SDValue RHS = N->getOperand(2); 8597 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8598 if (!ISD::isIntEqualitySetCC(CCVal)) 8599 break; 8600 8601 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8602 // (br_cc X, Y, lt, dest) 8603 // Sometimes the setcc is introduced after br_cc has been formed. 8604 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8605 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8606 // If we're looking for eq 0 instead of ne 0, we need to invert the 8607 // condition. 8608 bool Invert = CCVal == ISD::SETEQ; 8609 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8610 if (Invert) 8611 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8612 8613 SDLoc DL(N); 8614 RHS = LHS.getOperand(1); 8615 LHS = LHS.getOperand(0); 8616 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8617 8618 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8619 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8620 N->getOperand(4)); 8621 } 8622 8623 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8624 // (br_cc X, Y, eq/ne, trueV, falseV) 8625 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8626 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8627 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8628 N->getOperand(3), N->getOperand(4)); 8629 8630 // (br_cc X, 1, setne, br_cc) -> 8631 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8632 // This can occur when legalizing some floating point comparisons. 8633 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8634 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8635 SDLoc DL(N); 8636 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8637 SDValue TargetCC = DAG.getCondCode(CCVal); 8638 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8639 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8640 N->getOperand(0), LHS, RHS, TargetCC, 8641 N->getOperand(4)); 8642 } 8643 break; 8644 } 8645 case ISD::BITREVERSE: 8646 return performBITREVERSECombine(N, DAG, Subtarget); 8647 case ISD::FP_TO_SINT: 8648 case ISD::FP_TO_UINT: 8649 return performFP_TO_INTCombine(N, DCI, Subtarget); 8650 case ISD::FP_TO_SINT_SAT: 8651 case ISD::FP_TO_UINT_SAT: 8652 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8653 case ISD::FCOPYSIGN: { 8654 EVT VT = N->getValueType(0); 8655 if (!VT.isVector()) 8656 break; 8657 // There is a form of VFSGNJ which injects the negated sign of its second 8658 // operand. Try and bubble any FNEG up after the extend/round to produce 8659 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8660 // TRUNC=1. 8661 SDValue In2 = N->getOperand(1); 8662 // Avoid cases where the extend/round has multiple uses, as duplicating 8663 // those is typically more expensive than removing a fneg. 8664 if (!In2.hasOneUse()) 8665 break; 8666 if (In2.getOpcode() != ISD::FP_EXTEND && 8667 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8668 break; 8669 In2 = In2.getOperand(0); 8670 if (In2.getOpcode() != ISD::FNEG) 8671 break; 8672 SDLoc DL(N); 8673 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8674 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8675 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8676 } 8677 case ISD::MGATHER: 8678 case ISD::MSCATTER: 8679 case ISD::VP_GATHER: 8680 case ISD::VP_SCATTER: { 8681 if (!DCI.isBeforeLegalize()) 8682 break; 8683 SDValue Index, ScaleOp; 8684 bool IsIndexScaled = false; 8685 bool IsIndexSigned = false; 8686 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8687 Index = VPGSN->getIndex(); 8688 ScaleOp = VPGSN->getScale(); 8689 IsIndexScaled = VPGSN->isIndexScaled(); 8690 IsIndexSigned = VPGSN->isIndexSigned(); 8691 } else { 8692 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 8693 Index = MGSN->getIndex(); 8694 ScaleOp = MGSN->getScale(); 8695 IsIndexScaled = MGSN->isIndexScaled(); 8696 IsIndexSigned = MGSN->isIndexSigned(); 8697 } 8698 EVT IndexVT = Index.getValueType(); 8699 MVT XLenVT = Subtarget.getXLenVT(); 8700 // RISCV indexed loads only support the "unsigned unscaled" addressing 8701 // mode, so anything else must be manually legalized. 8702 bool NeedsIdxLegalization = 8703 IsIndexScaled || 8704 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 8705 if (!NeedsIdxLegalization) 8706 break; 8707 8708 SDLoc DL(N); 8709 8710 // Any index legalization should first promote to XLenVT, so we don't lose 8711 // bits when scaling. This may create an illegal index type so we let 8712 // LLVM's legalization take care of the splitting. 8713 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 8714 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 8715 IndexVT = IndexVT.changeVectorElementType(XLenVT); 8716 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8717 DL, IndexVT, Index); 8718 } 8719 8720 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 8721 if (IsIndexScaled && Scale != 1) { 8722 // Manually scale the indices by the element size. 8723 // TODO: Sanitize the scale operand here? 8724 // TODO: For VP nodes, should we use VP_SHL here? 8725 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 8726 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 8727 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 8728 } 8729 8730 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_UNSCALED; 8731 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 8732 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 8733 {VPGN->getChain(), VPGN->getBasePtr(), Index, 8734 VPGN->getScale(), VPGN->getMask(), 8735 VPGN->getVectorLength()}, 8736 VPGN->getMemOperand(), NewIndexTy); 8737 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 8738 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 8739 {VPSN->getChain(), VPSN->getValue(), 8740 VPSN->getBasePtr(), Index, VPSN->getScale(), 8741 VPSN->getMask(), VPSN->getVectorLength()}, 8742 VPSN->getMemOperand(), NewIndexTy); 8743 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 8744 return DAG.getMaskedGather( 8745 N->getVTList(), MGN->getMemoryVT(), DL, 8746 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 8747 MGN->getBasePtr(), Index, MGN->getScale()}, 8748 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 8749 const auto *MSN = cast<MaskedScatterSDNode>(N); 8750 return DAG.getMaskedScatter( 8751 N->getVTList(), MSN->getMemoryVT(), DL, 8752 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 8753 Index, MSN->getScale()}, 8754 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 8755 } 8756 case RISCVISD::SRA_VL: 8757 case RISCVISD::SRL_VL: 8758 case RISCVISD::SHL_VL: { 8759 SDValue ShAmt = N->getOperand(1); 8760 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8761 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8762 SDLoc DL(N); 8763 SDValue VL = N->getOperand(3); 8764 EVT VT = N->getValueType(0); 8765 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8766 ShAmt.getOperand(1), VL); 8767 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8768 N->getOperand(2), N->getOperand(3)); 8769 } 8770 break; 8771 } 8772 case ISD::SRA: 8773 case ISD::SRL: 8774 case ISD::SHL: { 8775 SDValue ShAmt = N->getOperand(1); 8776 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8777 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8778 SDLoc DL(N); 8779 EVT VT = N->getValueType(0); 8780 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8781 ShAmt.getOperand(1), 8782 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 8783 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 8784 } 8785 break; 8786 } 8787 case RISCVISD::ADD_VL: 8788 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 8789 return V; 8790 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 8791 case RISCVISD::SUB_VL: 8792 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 8793 case RISCVISD::VWADD_W_VL: 8794 case RISCVISD::VWADDU_W_VL: 8795 case RISCVISD::VWSUB_W_VL: 8796 case RISCVISD::VWSUBU_W_VL: 8797 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 8798 case RISCVISD::MUL_VL: 8799 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 8800 return V; 8801 // Mul is commutative. 8802 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 8803 case ISD::STORE: { 8804 auto *Store = cast<StoreSDNode>(N); 8805 SDValue Val = Store->getValue(); 8806 // Combine store of vmv.x.s to vse with VL of 1. 8807 // FIXME: Support FP. 8808 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 8809 SDValue Src = Val.getOperand(0); 8810 EVT VecVT = Src.getValueType(); 8811 EVT MemVT = Store->getMemoryVT(); 8812 // The memory VT and the element type must match. 8813 if (VecVT.getVectorElementType() == MemVT) { 8814 SDLoc DL(N); 8815 MVT MaskVT = getMaskTypeFor(VecVT); 8816 return DAG.getStoreVP( 8817 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 8818 DAG.getConstant(1, DL, MaskVT), 8819 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 8820 Store->getMemOperand(), Store->getAddressingMode(), 8821 Store->isTruncatingStore(), /*IsCompress*/ false); 8822 } 8823 } 8824 8825 break; 8826 } 8827 case ISD::SPLAT_VECTOR: { 8828 EVT VT = N->getValueType(0); 8829 // Only perform this combine on legal MVT types. 8830 if (!isTypeLegal(VT)) 8831 break; 8832 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 8833 DAG, Subtarget)) 8834 return Gather; 8835 break; 8836 } 8837 case RISCVISD::VMV_V_X_VL: { 8838 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 8839 // scalar input. 8840 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 8841 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 8842 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 8843 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 8844 return SDValue(N, 0); 8845 8846 break; 8847 } 8848 case ISD::INTRINSIC_WO_CHAIN: { 8849 unsigned IntNo = N->getConstantOperandVal(0); 8850 switch (IntNo) { 8851 // By default we do not combine any intrinsic. 8852 default: 8853 return SDValue(); 8854 case Intrinsic::riscv_vcpop: 8855 case Intrinsic::riscv_vcpop_mask: 8856 case Intrinsic::riscv_vfirst: 8857 case Intrinsic::riscv_vfirst_mask: { 8858 SDValue VL = N->getOperand(2); 8859 if (IntNo == Intrinsic::riscv_vcpop_mask || 8860 IntNo == Intrinsic::riscv_vfirst_mask) 8861 VL = N->getOperand(3); 8862 if (!isNullConstant(VL)) 8863 return SDValue(); 8864 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 8865 SDLoc DL(N); 8866 EVT VT = N->getValueType(0); 8867 if (IntNo == Intrinsic::riscv_vfirst || 8868 IntNo == Intrinsic::riscv_vfirst_mask) 8869 return DAG.getConstant(-1, DL, VT); 8870 return DAG.getConstant(0, DL, VT); 8871 } 8872 } 8873 } 8874 } 8875 8876 return SDValue(); 8877 } 8878 8879 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 8880 const SDNode *N, CombineLevel Level) const { 8881 // The following folds are only desirable if `(OP _, c1 << c2)` can be 8882 // materialised in fewer instructions than `(OP _, c1)`: 8883 // 8884 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 8885 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 8886 SDValue N0 = N->getOperand(0); 8887 EVT Ty = N0.getValueType(); 8888 if (Ty.isScalarInteger() && 8889 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 8890 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 8891 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 8892 if (C1 && C2) { 8893 const APInt &C1Int = C1->getAPIntValue(); 8894 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 8895 8896 // We can materialise `c1 << c2` into an add immediate, so it's "free", 8897 // and the combine should happen, to potentially allow further combines 8898 // later. 8899 if (ShiftedC1Int.getMinSignedBits() <= 64 && 8900 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 8901 return true; 8902 8903 // We can materialise `c1` in an add immediate, so it's "free", and the 8904 // combine should be prevented. 8905 if (C1Int.getMinSignedBits() <= 64 && 8906 isLegalAddImmediate(C1Int.getSExtValue())) 8907 return false; 8908 8909 // Neither constant will fit into an immediate, so find materialisation 8910 // costs. 8911 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 8912 Subtarget.getFeatureBits(), 8913 /*CompressionCost*/true); 8914 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 8915 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 8916 /*CompressionCost*/true); 8917 8918 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 8919 // combine should be prevented. 8920 if (C1Cost < ShiftedC1Cost) 8921 return false; 8922 } 8923 } 8924 return true; 8925 } 8926 8927 bool RISCVTargetLowering::targetShrinkDemandedConstant( 8928 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 8929 TargetLoweringOpt &TLO) const { 8930 // Delay this optimization as late as possible. 8931 if (!TLO.LegalOps) 8932 return false; 8933 8934 EVT VT = Op.getValueType(); 8935 if (VT.isVector()) 8936 return false; 8937 8938 // Only handle AND for now. 8939 if (Op.getOpcode() != ISD::AND) 8940 return false; 8941 8942 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 8943 if (!C) 8944 return false; 8945 8946 const APInt &Mask = C->getAPIntValue(); 8947 8948 // Clear all non-demanded bits initially. 8949 APInt ShrunkMask = Mask & DemandedBits; 8950 8951 // Try to make a smaller immediate by setting undemanded bits. 8952 8953 APInt ExpandedMask = Mask | ~DemandedBits; 8954 8955 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 8956 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 8957 }; 8958 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 8959 if (NewMask == Mask) 8960 return true; 8961 SDLoc DL(Op); 8962 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 8963 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 8964 return TLO.CombineTo(Op, NewOp); 8965 }; 8966 8967 // If the shrunk mask fits in sign extended 12 bits, let the target 8968 // independent code apply it. 8969 if (ShrunkMask.isSignedIntN(12)) 8970 return false; 8971 8972 // Preserve (and X, 0xffff) when zext.h is supported. 8973 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 8974 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 8975 if (IsLegalMask(NewMask)) 8976 return UseMask(NewMask); 8977 } 8978 8979 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 8980 if (VT == MVT::i64) { 8981 APInt NewMask = APInt(64, 0xffffffff); 8982 if (IsLegalMask(NewMask)) 8983 return UseMask(NewMask); 8984 } 8985 8986 // For the remaining optimizations, we need to be able to make a negative 8987 // number through a combination of mask and undemanded bits. 8988 if (!ExpandedMask.isNegative()) 8989 return false; 8990 8991 // What is the fewest number of bits we need to represent the negative number. 8992 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 8993 8994 // Try to make a 12 bit negative immediate. If that fails try to make a 32 8995 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 8996 APInt NewMask = ShrunkMask; 8997 if (MinSignedBits <= 12) 8998 NewMask.setBitsFrom(11); 8999 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 9000 NewMask.setBitsFrom(31); 9001 else 9002 return false; 9003 9004 // Check that our new mask is a subset of the demanded mask. 9005 assert(IsLegalMask(NewMask)); 9006 return UseMask(NewMask); 9007 } 9008 9009 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) { 9010 static const uint64_t GREVMasks[] = { 9011 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 9012 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 9013 9014 for (unsigned Stage = 0; Stage != 6; ++Stage) { 9015 unsigned Shift = 1 << Stage; 9016 if (ShAmt & Shift) { 9017 uint64_t Mask = GREVMasks[Stage]; 9018 uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask); 9019 if (IsGORC) 9020 Res |= x; 9021 x = Res; 9022 } 9023 } 9024 9025 return x; 9026 } 9027 9028 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 9029 KnownBits &Known, 9030 const APInt &DemandedElts, 9031 const SelectionDAG &DAG, 9032 unsigned Depth) const { 9033 unsigned BitWidth = Known.getBitWidth(); 9034 unsigned Opc = Op.getOpcode(); 9035 assert((Opc >= ISD::BUILTIN_OP_END || 9036 Opc == ISD::INTRINSIC_WO_CHAIN || 9037 Opc == ISD::INTRINSIC_W_CHAIN || 9038 Opc == ISD::INTRINSIC_VOID) && 9039 "Should use MaskedValueIsZero if you don't know whether Op" 9040 " is a target node!"); 9041 9042 Known.resetAll(); 9043 switch (Opc) { 9044 default: break; 9045 case RISCVISD::SELECT_CC: { 9046 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 9047 // If we don't know any bits, early out. 9048 if (Known.isUnknown()) 9049 break; 9050 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 9051 9052 // Only known if known in both the LHS and RHS. 9053 Known = KnownBits::commonBits(Known, Known2); 9054 break; 9055 } 9056 case RISCVISD::REMUW: { 9057 KnownBits Known2; 9058 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9059 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9060 // We only care about the lower 32 bits. 9061 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 9062 // Restore the original width by sign extending. 9063 Known = Known.sext(BitWidth); 9064 break; 9065 } 9066 case RISCVISD::DIVUW: { 9067 KnownBits Known2; 9068 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9069 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9070 // We only care about the lower 32 bits. 9071 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 9072 // Restore the original width by sign extending. 9073 Known = Known.sext(BitWidth); 9074 break; 9075 } 9076 case RISCVISD::CTZW: { 9077 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9078 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 9079 unsigned LowBits = Log2_32(PossibleTZ) + 1; 9080 Known.Zero.setBitsFrom(LowBits); 9081 break; 9082 } 9083 case RISCVISD::CLZW: { 9084 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9085 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 9086 unsigned LowBits = Log2_32(PossibleLZ) + 1; 9087 Known.Zero.setBitsFrom(LowBits); 9088 break; 9089 } 9090 case RISCVISD::GREV: 9091 case RISCVISD::GORC: { 9092 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 9093 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9094 unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1); 9095 bool IsGORC = Op.getOpcode() == RISCVISD::GORC; 9096 // To compute zeros, we need to invert the value and invert it back after. 9097 Known.Zero = 9098 ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC); 9099 Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC); 9100 } 9101 break; 9102 } 9103 case RISCVISD::READ_VLENB: { 9104 // If we know the minimum VLen from Zvl extensions, we can use that to 9105 // determine the trailing zeros of VLENB. 9106 // FIXME: Limit to 128 bit vectors until we have more testing. 9107 unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8; 9108 if (MinVLenB > 0) 9109 Known.Zero.setLowBits(Log2_32(MinVLenB)); 9110 // We assume VLENB is no more than 65536 / 8 bytes. 9111 Known.Zero.setBitsFrom(14); 9112 break; 9113 } 9114 case ISD::INTRINSIC_W_CHAIN: 9115 case ISD::INTRINSIC_WO_CHAIN: { 9116 unsigned IntNo = 9117 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 9118 switch (IntNo) { 9119 default: 9120 // We can't do anything for most intrinsics. 9121 break; 9122 case Intrinsic::riscv_vsetvli: 9123 case Intrinsic::riscv_vsetvlimax: 9124 case Intrinsic::riscv_vsetvli_opt: 9125 case Intrinsic::riscv_vsetvlimax_opt: 9126 // Assume that VL output is positive and would fit in an int32_t. 9127 // TODO: VLEN might be capped at 16 bits in a future V spec update. 9128 if (BitWidth >= 32) 9129 Known.Zero.setBitsFrom(31); 9130 break; 9131 } 9132 break; 9133 } 9134 } 9135 } 9136 9137 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 9138 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 9139 unsigned Depth) const { 9140 switch (Op.getOpcode()) { 9141 default: 9142 break; 9143 case RISCVISD::SELECT_CC: { 9144 unsigned Tmp = 9145 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 9146 if (Tmp == 1) return 1; // Early out. 9147 unsigned Tmp2 = 9148 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 9149 return std::min(Tmp, Tmp2); 9150 } 9151 case RISCVISD::SLLW: 9152 case RISCVISD::SRAW: 9153 case RISCVISD::SRLW: 9154 case RISCVISD::DIVW: 9155 case RISCVISD::DIVUW: 9156 case RISCVISD::REMUW: 9157 case RISCVISD::ROLW: 9158 case RISCVISD::RORW: 9159 case RISCVISD::GREVW: 9160 case RISCVISD::GORCW: 9161 case RISCVISD::FSLW: 9162 case RISCVISD::FSRW: 9163 case RISCVISD::SHFLW: 9164 case RISCVISD::UNSHFLW: 9165 case RISCVISD::BCOMPRESSW: 9166 case RISCVISD::BDECOMPRESSW: 9167 case RISCVISD::BFPW: 9168 case RISCVISD::FCVT_W_RV64: 9169 case RISCVISD::FCVT_WU_RV64: 9170 case RISCVISD::STRICT_FCVT_W_RV64: 9171 case RISCVISD::STRICT_FCVT_WU_RV64: 9172 // TODO: As the result is sign-extended, this is conservatively correct. A 9173 // more precise answer could be calculated for SRAW depending on known 9174 // bits in the shift amount. 9175 return 33; 9176 case RISCVISD::SHFL: 9177 case RISCVISD::UNSHFL: { 9178 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 9179 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 9180 // will stay within the upper 32 bits. If there were more than 32 sign bits 9181 // before there will be at least 33 sign bits after. 9182 if (Op.getValueType() == MVT::i64 && 9183 isa<ConstantSDNode>(Op.getOperand(1)) && 9184 (Op.getConstantOperandVal(1) & 0x10) == 0) { 9185 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 9186 if (Tmp > 32) 9187 return 33; 9188 } 9189 break; 9190 } 9191 case RISCVISD::VMV_X_S: { 9192 // The number of sign bits of the scalar result is computed by obtaining the 9193 // element type of the input vector operand, subtracting its width from the 9194 // XLEN, and then adding one (sign bit within the element type). If the 9195 // element type is wider than XLen, the least-significant XLEN bits are 9196 // taken. 9197 unsigned XLen = Subtarget.getXLen(); 9198 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 9199 if (EltBits <= XLen) 9200 return XLen - EltBits + 1; 9201 break; 9202 } 9203 } 9204 9205 return 1; 9206 } 9207 9208 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 9209 MachineBasicBlock *BB) { 9210 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 9211 9212 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 9213 // Should the count have wrapped while it was being read, we need to try 9214 // again. 9215 // ... 9216 // read: 9217 // rdcycleh x3 # load high word of cycle 9218 // rdcycle x2 # load low word of cycle 9219 // rdcycleh x4 # load high word of cycle 9220 // bne x3, x4, read # check if high word reads match, otherwise try again 9221 // ... 9222 9223 MachineFunction &MF = *BB->getParent(); 9224 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9225 MachineFunction::iterator It = ++BB->getIterator(); 9226 9227 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9228 MF.insert(It, LoopMBB); 9229 9230 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9231 MF.insert(It, DoneMBB); 9232 9233 // Transfer the remainder of BB and its successor edges to DoneMBB. 9234 DoneMBB->splice(DoneMBB->begin(), BB, 9235 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9236 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 9237 9238 BB->addSuccessor(LoopMBB); 9239 9240 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9241 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9242 Register LoReg = MI.getOperand(0).getReg(); 9243 Register HiReg = MI.getOperand(1).getReg(); 9244 DebugLoc DL = MI.getDebugLoc(); 9245 9246 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 9247 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 9248 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9249 .addReg(RISCV::X0); 9250 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 9251 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 9252 .addReg(RISCV::X0); 9253 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 9254 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9255 .addReg(RISCV::X0); 9256 9257 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 9258 .addReg(HiReg) 9259 .addReg(ReadAgainReg) 9260 .addMBB(LoopMBB); 9261 9262 LoopMBB->addSuccessor(LoopMBB); 9263 LoopMBB->addSuccessor(DoneMBB); 9264 9265 MI.eraseFromParent(); 9266 9267 return DoneMBB; 9268 } 9269 9270 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9271 MachineBasicBlock *BB) { 9272 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9273 9274 MachineFunction &MF = *BB->getParent(); 9275 DebugLoc DL = MI.getDebugLoc(); 9276 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9277 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9278 Register LoReg = MI.getOperand(0).getReg(); 9279 Register HiReg = MI.getOperand(1).getReg(); 9280 Register SrcReg = MI.getOperand(2).getReg(); 9281 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9282 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9283 9284 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9285 RI); 9286 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9287 MachineMemOperand *MMOLo = 9288 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9289 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9290 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9291 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9292 .addFrameIndex(FI) 9293 .addImm(0) 9294 .addMemOperand(MMOLo); 9295 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9296 .addFrameIndex(FI) 9297 .addImm(4) 9298 .addMemOperand(MMOHi); 9299 MI.eraseFromParent(); // The pseudo instruction is gone now. 9300 return BB; 9301 } 9302 9303 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9304 MachineBasicBlock *BB) { 9305 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9306 "Unexpected instruction"); 9307 9308 MachineFunction &MF = *BB->getParent(); 9309 DebugLoc DL = MI.getDebugLoc(); 9310 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9311 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9312 Register DstReg = MI.getOperand(0).getReg(); 9313 Register LoReg = MI.getOperand(1).getReg(); 9314 Register HiReg = MI.getOperand(2).getReg(); 9315 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9316 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9317 9318 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9319 MachineMemOperand *MMOLo = 9320 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9321 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9322 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9323 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9324 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9325 .addFrameIndex(FI) 9326 .addImm(0) 9327 .addMemOperand(MMOLo); 9328 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9329 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9330 .addFrameIndex(FI) 9331 .addImm(4) 9332 .addMemOperand(MMOHi); 9333 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9334 MI.eraseFromParent(); // The pseudo instruction is gone now. 9335 return BB; 9336 } 9337 9338 static bool isSelectPseudo(MachineInstr &MI) { 9339 switch (MI.getOpcode()) { 9340 default: 9341 return false; 9342 case RISCV::Select_GPR_Using_CC_GPR: 9343 case RISCV::Select_FPR16_Using_CC_GPR: 9344 case RISCV::Select_FPR32_Using_CC_GPR: 9345 case RISCV::Select_FPR64_Using_CC_GPR: 9346 return true; 9347 } 9348 } 9349 9350 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9351 unsigned RelOpcode, unsigned EqOpcode, 9352 const RISCVSubtarget &Subtarget) { 9353 DebugLoc DL = MI.getDebugLoc(); 9354 Register DstReg = MI.getOperand(0).getReg(); 9355 Register Src1Reg = MI.getOperand(1).getReg(); 9356 Register Src2Reg = MI.getOperand(2).getReg(); 9357 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9358 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9359 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9360 9361 // Save the current FFLAGS. 9362 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9363 9364 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9365 .addReg(Src1Reg) 9366 .addReg(Src2Reg); 9367 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9368 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9369 9370 // Restore the FFLAGS. 9371 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9372 .addReg(SavedFFlags, RegState::Kill); 9373 9374 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9375 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9376 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9377 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9378 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9379 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9380 9381 // Erase the pseudoinstruction. 9382 MI.eraseFromParent(); 9383 return BB; 9384 } 9385 9386 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9387 MachineBasicBlock *BB, 9388 const RISCVSubtarget &Subtarget) { 9389 // To "insert" Select_* instructions, we actually have to insert the triangle 9390 // control-flow pattern. The incoming instructions know the destination vreg 9391 // to set, the condition code register to branch on, the true/false values to 9392 // select between, and the condcode to use to select the appropriate branch. 9393 // 9394 // We produce the following control flow: 9395 // HeadMBB 9396 // | \ 9397 // | IfFalseMBB 9398 // | / 9399 // TailMBB 9400 // 9401 // When we find a sequence of selects we attempt to optimize their emission 9402 // by sharing the control flow. Currently we only handle cases where we have 9403 // multiple selects with the exact same condition (same LHS, RHS and CC). 9404 // The selects may be interleaved with other instructions if the other 9405 // instructions meet some requirements we deem safe: 9406 // - They are debug instructions. Otherwise, 9407 // - They do not have side-effects, do not access memory and their inputs do 9408 // not depend on the results of the select pseudo-instructions. 9409 // The TrueV/FalseV operands of the selects cannot depend on the result of 9410 // previous selects in the sequence. 9411 // These conditions could be further relaxed. See the X86 target for a 9412 // related approach and more information. 9413 Register LHS = MI.getOperand(1).getReg(); 9414 Register RHS = MI.getOperand(2).getReg(); 9415 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9416 9417 SmallVector<MachineInstr *, 4> SelectDebugValues; 9418 SmallSet<Register, 4> SelectDests; 9419 SelectDests.insert(MI.getOperand(0).getReg()); 9420 9421 MachineInstr *LastSelectPseudo = &MI; 9422 9423 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9424 SequenceMBBI != E; ++SequenceMBBI) { 9425 if (SequenceMBBI->isDebugInstr()) 9426 continue; 9427 else if (isSelectPseudo(*SequenceMBBI)) { 9428 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9429 SequenceMBBI->getOperand(2).getReg() != RHS || 9430 SequenceMBBI->getOperand(3).getImm() != CC || 9431 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9432 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9433 break; 9434 LastSelectPseudo = &*SequenceMBBI; 9435 SequenceMBBI->collectDebugValues(SelectDebugValues); 9436 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9437 } else { 9438 if (SequenceMBBI->hasUnmodeledSideEffects() || 9439 SequenceMBBI->mayLoadOrStore()) 9440 break; 9441 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9442 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9443 })) 9444 break; 9445 } 9446 } 9447 9448 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9449 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9450 DebugLoc DL = MI.getDebugLoc(); 9451 MachineFunction::iterator I = ++BB->getIterator(); 9452 9453 MachineBasicBlock *HeadMBB = BB; 9454 MachineFunction *F = BB->getParent(); 9455 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9456 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9457 9458 F->insert(I, IfFalseMBB); 9459 F->insert(I, TailMBB); 9460 9461 // Transfer debug instructions associated with the selects to TailMBB. 9462 for (MachineInstr *DebugInstr : SelectDebugValues) { 9463 TailMBB->push_back(DebugInstr->removeFromParent()); 9464 } 9465 9466 // Move all instructions after the sequence to TailMBB. 9467 TailMBB->splice(TailMBB->end(), HeadMBB, 9468 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9469 // Update machine-CFG edges by transferring all successors of the current 9470 // block to the new block which will contain the Phi nodes for the selects. 9471 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9472 // Set the successors for HeadMBB. 9473 HeadMBB->addSuccessor(IfFalseMBB); 9474 HeadMBB->addSuccessor(TailMBB); 9475 9476 // Insert appropriate branch. 9477 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9478 .addReg(LHS) 9479 .addReg(RHS) 9480 .addMBB(TailMBB); 9481 9482 // IfFalseMBB just falls through to TailMBB. 9483 IfFalseMBB->addSuccessor(TailMBB); 9484 9485 // Create PHIs for all of the select pseudo-instructions. 9486 auto SelectMBBI = MI.getIterator(); 9487 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9488 auto InsertionPoint = TailMBB->begin(); 9489 while (SelectMBBI != SelectEnd) { 9490 auto Next = std::next(SelectMBBI); 9491 if (isSelectPseudo(*SelectMBBI)) { 9492 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9493 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9494 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9495 .addReg(SelectMBBI->getOperand(4).getReg()) 9496 .addMBB(HeadMBB) 9497 .addReg(SelectMBBI->getOperand(5).getReg()) 9498 .addMBB(IfFalseMBB); 9499 SelectMBBI->eraseFromParent(); 9500 } 9501 SelectMBBI = Next; 9502 } 9503 9504 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9505 return TailMBB; 9506 } 9507 9508 MachineBasicBlock * 9509 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9510 MachineBasicBlock *BB) const { 9511 switch (MI.getOpcode()) { 9512 default: 9513 llvm_unreachable("Unexpected instr type to insert"); 9514 case RISCV::ReadCycleWide: 9515 assert(!Subtarget.is64Bit() && 9516 "ReadCycleWrite is only to be used on riscv32"); 9517 return emitReadCycleWidePseudo(MI, BB); 9518 case RISCV::Select_GPR_Using_CC_GPR: 9519 case RISCV::Select_FPR16_Using_CC_GPR: 9520 case RISCV::Select_FPR32_Using_CC_GPR: 9521 case RISCV::Select_FPR64_Using_CC_GPR: 9522 return emitSelectPseudo(MI, BB, Subtarget); 9523 case RISCV::BuildPairF64Pseudo: 9524 return emitBuildPairF64Pseudo(MI, BB); 9525 case RISCV::SplitF64Pseudo: 9526 return emitSplitF64Pseudo(MI, BB); 9527 case RISCV::PseudoQuietFLE_H: 9528 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9529 case RISCV::PseudoQuietFLT_H: 9530 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9531 case RISCV::PseudoQuietFLE_S: 9532 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9533 case RISCV::PseudoQuietFLT_S: 9534 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9535 case RISCV::PseudoQuietFLE_D: 9536 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9537 case RISCV::PseudoQuietFLT_D: 9538 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9539 } 9540 } 9541 9542 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9543 SDNode *Node) const { 9544 // Add FRM dependency to any instructions with dynamic rounding mode. 9545 unsigned Opc = MI.getOpcode(); 9546 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9547 if (Idx < 0) 9548 return; 9549 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9550 return; 9551 // If the instruction already reads FRM, don't add another read. 9552 if (MI.readsRegister(RISCV::FRM)) 9553 return; 9554 MI.addOperand( 9555 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9556 } 9557 9558 // Calling Convention Implementation. 9559 // The expectations for frontend ABI lowering vary from target to target. 9560 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 9561 // details, but this is a longer term goal. For now, we simply try to keep the 9562 // role of the frontend as simple and well-defined as possible. The rules can 9563 // be summarised as: 9564 // * Never split up large scalar arguments. We handle them here. 9565 // * If a hardfloat calling convention is being used, and the struct may be 9566 // passed in a pair of registers (fp+fp, int+fp), and both registers are 9567 // available, then pass as two separate arguments. If either the GPRs or FPRs 9568 // are exhausted, then pass according to the rule below. 9569 // * If a struct could never be passed in registers or directly in a stack 9570 // slot (as it is larger than 2*XLEN and the floating point rules don't 9571 // apply), then pass it using a pointer with the byval attribute. 9572 // * If a struct is less than 2*XLEN, then coerce to either a two-element 9573 // word-sized array or a 2*XLEN scalar (depending on alignment). 9574 // * The frontend can determine whether a struct is returned by reference or 9575 // not based on its size and fields. If it will be returned by reference, the 9576 // frontend must modify the prototype so a pointer with the sret annotation is 9577 // passed as the first argument. This is not necessary for large scalar 9578 // returns. 9579 // * Struct return values and varargs should be coerced to structs containing 9580 // register-size fields in the same situations they would be for fixed 9581 // arguments. 9582 9583 static const MCPhysReg ArgGPRs[] = { 9584 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 9585 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 9586 }; 9587 static const MCPhysReg ArgFPR16s[] = { 9588 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 9589 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 9590 }; 9591 static const MCPhysReg ArgFPR32s[] = { 9592 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 9593 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 9594 }; 9595 static const MCPhysReg ArgFPR64s[] = { 9596 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 9597 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 9598 }; 9599 // This is an interim calling convention and it may be changed in the future. 9600 static const MCPhysReg ArgVRs[] = { 9601 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 9602 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 9603 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 9604 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 9605 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 9606 RISCV::V20M2, RISCV::V22M2}; 9607 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 9608 RISCV::V20M4}; 9609 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 9610 9611 // Pass a 2*XLEN argument that has been split into two XLEN values through 9612 // registers or the stack as necessary. 9613 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 9614 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 9615 MVT ValVT2, MVT LocVT2, 9616 ISD::ArgFlagsTy ArgFlags2) { 9617 unsigned XLenInBytes = XLen / 8; 9618 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9619 // At least one half can be passed via register. 9620 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 9621 VA1.getLocVT(), CCValAssign::Full)); 9622 } else { 9623 // Both halves must be passed on the stack, with proper alignment. 9624 Align StackAlign = 9625 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 9626 State.addLoc( 9627 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 9628 State.AllocateStack(XLenInBytes, StackAlign), 9629 VA1.getLocVT(), CCValAssign::Full)); 9630 State.addLoc(CCValAssign::getMem( 9631 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9632 LocVT2, CCValAssign::Full)); 9633 return false; 9634 } 9635 9636 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9637 // The second half can also be passed via register. 9638 State.addLoc( 9639 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 9640 } else { 9641 // The second half is passed via the stack, without additional alignment. 9642 State.addLoc(CCValAssign::getMem( 9643 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9644 LocVT2, CCValAssign::Full)); 9645 } 9646 9647 return false; 9648 } 9649 9650 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 9651 Optional<unsigned> FirstMaskArgument, 9652 CCState &State, const RISCVTargetLowering &TLI) { 9653 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 9654 if (RC == &RISCV::VRRegClass) { 9655 // Assign the first mask argument to V0. 9656 // This is an interim calling convention and it may be changed in the 9657 // future. 9658 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 9659 return State.AllocateReg(RISCV::V0); 9660 return State.AllocateReg(ArgVRs); 9661 } 9662 if (RC == &RISCV::VRM2RegClass) 9663 return State.AllocateReg(ArgVRM2s); 9664 if (RC == &RISCV::VRM4RegClass) 9665 return State.AllocateReg(ArgVRM4s); 9666 if (RC == &RISCV::VRM8RegClass) 9667 return State.AllocateReg(ArgVRM8s); 9668 llvm_unreachable("Unhandled register class for ValueType"); 9669 } 9670 9671 // Implements the RISC-V calling convention. Returns true upon failure. 9672 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 9673 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 9674 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 9675 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 9676 Optional<unsigned> FirstMaskArgument) { 9677 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 9678 assert(XLen == 32 || XLen == 64); 9679 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 9680 9681 // Any return value split in to more than two values can't be returned 9682 // directly. Vectors are returned via the available vector registers. 9683 if (!LocVT.isVector() && IsRet && ValNo > 1) 9684 return true; 9685 9686 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 9687 // variadic argument, or if no F16/F32 argument registers are available. 9688 bool UseGPRForF16_F32 = true; 9689 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 9690 // variadic argument, or if no F64 argument registers are available. 9691 bool UseGPRForF64 = true; 9692 9693 switch (ABI) { 9694 default: 9695 llvm_unreachable("Unexpected ABI"); 9696 case RISCVABI::ABI_ILP32: 9697 case RISCVABI::ABI_LP64: 9698 break; 9699 case RISCVABI::ABI_ILP32F: 9700 case RISCVABI::ABI_LP64F: 9701 UseGPRForF16_F32 = !IsFixed; 9702 break; 9703 case RISCVABI::ABI_ILP32D: 9704 case RISCVABI::ABI_LP64D: 9705 UseGPRForF16_F32 = !IsFixed; 9706 UseGPRForF64 = !IsFixed; 9707 break; 9708 } 9709 9710 // FPR16, FPR32, and FPR64 alias each other. 9711 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 9712 UseGPRForF16_F32 = true; 9713 UseGPRForF64 = true; 9714 } 9715 9716 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 9717 // similar local variables rather than directly checking against the target 9718 // ABI. 9719 9720 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 9721 LocVT = XLenVT; 9722 LocInfo = CCValAssign::BCvt; 9723 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 9724 LocVT = MVT::i64; 9725 LocInfo = CCValAssign::BCvt; 9726 } 9727 9728 // If this is a variadic argument, the RISC-V calling convention requires 9729 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 9730 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 9731 // be used regardless of whether the original argument was split during 9732 // legalisation or not. The argument will not be passed by registers if the 9733 // original type is larger than 2*XLEN, so the register alignment rule does 9734 // not apply. 9735 unsigned TwoXLenInBytes = (2 * XLen) / 8; 9736 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 9737 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 9738 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 9739 // Skip 'odd' register if necessary. 9740 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 9741 State.AllocateReg(ArgGPRs); 9742 } 9743 9744 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 9745 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 9746 State.getPendingArgFlags(); 9747 9748 assert(PendingLocs.size() == PendingArgFlags.size() && 9749 "PendingLocs and PendingArgFlags out of sync"); 9750 9751 // Handle passing f64 on RV32D with a soft float ABI or when floating point 9752 // registers are exhausted. 9753 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 9754 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 9755 "Can't lower f64 if it is split"); 9756 // Depending on available argument GPRS, f64 may be passed in a pair of 9757 // GPRs, split between a GPR and the stack, or passed completely on the 9758 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 9759 // cases. 9760 Register Reg = State.AllocateReg(ArgGPRs); 9761 LocVT = MVT::i32; 9762 if (!Reg) { 9763 unsigned StackOffset = State.AllocateStack(8, Align(8)); 9764 State.addLoc( 9765 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9766 return false; 9767 } 9768 if (!State.AllocateReg(ArgGPRs)) 9769 State.AllocateStack(4, Align(4)); 9770 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9771 return false; 9772 } 9773 9774 // Fixed-length vectors are located in the corresponding scalable-vector 9775 // container types. 9776 if (ValVT.isFixedLengthVector()) 9777 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9778 9779 // Split arguments might be passed indirectly, so keep track of the pending 9780 // values. Split vectors are passed via a mix of registers and indirectly, so 9781 // treat them as we would any other argument. 9782 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 9783 LocVT = XLenVT; 9784 LocInfo = CCValAssign::Indirect; 9785 PendingLocs.push_back( 9786 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 9787 PendingArgFlags.push_back(ArgFlags); 9788 if (!ArgFlags.isSplitEnd()) { 9789 return false; 9790 } 9791 } 9792 9793 // If the split argument only had two elements, it should be passed directly 9794 // in registers or on the stack. 9795 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 9796 PendingLocs.size() <= 2) { 9797 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 9798 // Apply the normal calling convention rules to the first half of the 9799 // split argument. 9800 CCValAssign VA = PendingLocs[0]; 9801 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 9802 PendingLocs.clear(); 9803 PendingArgFlags.clear(); 9804 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 9805 ArgFlags); 9806 } 9807 9808 // Allocate to a register if possible, or else a stack slot. 9809 Register Reg; 9810 unsigned StoreSizeBytes = XLen / 8; 9811 Align StackAlign = Align(XLen / 8); 9812 9813 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 9814 Reg = State.AllocateReg(ArgFPR16s); 9815 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 9816 Reg = State.AllocateReg(ArgFPR32s); 9817 else if (ValVT == MVT::f64 && !UseGPRForF64) 9818 Reg = State.AllocateReg(ArgFPR64s); 9819 else if (ValVT.isVector()) { 9820 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 9821 if (!Reg) { 9822 // For return values, the vector must be passed fully via registers or 9823 // via the stack. 9824 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 9825 // but we're using all of them. 9826 if (IsRet) 9827 return true; 9828 // Try using a GPR to pass the address 9829 if ((Reg = State.AllocateReg(ArgGPRs))) { 9830 LocVT = XLenVT; 9831 LocInfo = CCValAssign::Indirect; 9832 } else if (ValVT.isScalableVector()) { 9833 LocVT = XLenVT; 9834 LocInfo = CCValAssign::Indirect; 9835 } else { 9836 // Pass fixed-length vectors on the stack. 9837 LocVT = ValVT; 9838 StoreSizeBytes = ValVT.getStoreSize(); 9839 // Align vectors to their element sizes, being careful for vXi1 9840 // vectors. 9841 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9842 } 9843 } 9844 } else { 9845 Reg = State.AllocateReg(ArgGPRs); 9846 } 9847 9848 unsigned StackOffset = 9849 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 9850 9851 // If we reach this point and PendingLocs is non-empty, we must be at the 9852 // end of a split argument that must be passed indirectly. 9853 if (!PendingLocs.empty()) { 9854 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 9855 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 9856 9857 for (auto &It : PendingLocs) { 9858 if (Reg) 9859 It.convertToReg(Reg); 9860 else 9861 It.convertToMem(StackOffset); 9862 State.addLoc(It); 9863 } 9864 PendingLocs.clear(); 9865 PendingArgFlags.clear(); 9866 return false; 9867 } 9868 9869 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 9870 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 9871 "Expected an XLenVT or vector types at this stage"); 9872 9873 if (Reg) { 9874 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9875 return false; 9876 } 9877 9878 // When a floating-point value is passed on the stack, no bit-conversion is 9879 // needed. 9880 if (ValVT.isFloatingPoint()) { 9881 LocVT = ValVT; 9882 LocInfo = CCValAssign::Full; 9883 } 9884 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9885 return false; 9886 } 9887 9888 template <typename ArgTy> 9889 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 9890 for (const auto &ArgIdx : enumerate(Args)) { 9891 MVT ArgVT = ArgIdx.value().VT; 9892 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 9893 return ArgIdx.index(); 9894 } 9895 return None; 9896 } 9897 9898 void RISCVTargetLowering::analyzeInputArgs( 9899 MachineFunction &MF, CCState &CCInfo, 9900 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 9901 RISCVCCAssignFn Fn) const { 9902 unsigned NumArgs = Ins.size(); 9903 FunctionType *FType = MF.getFunction().getFunctionType(); 9904 9905 Optional<unsigned> FirstMaskArgument; 9906 if (Subtarget.hasVInstructions()) 9907 FirstMaskArgument = preAssignMask(Ins); 9908 9909 for (unsigned i = 0; i != NumArgs; ++i) { 9910 MVT ArgVT = Ins[i].VT; 9911 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 9912 9913 Type *ArgTy = nullptr; 9914 if (IsRet) 9915 ArgTy = FType->getReturnType(); 9916 else if (Ins[i].isOrigArg()) 9917 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 9918 9919 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9920 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9921 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 9922 FirstMaskArgument)) { 9923 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 9924 << EVT(ArgVT).getEVTString() << '\n'); 9925 llvm_unreachable(nullptr); 9926 } 9927 } 9928 } 9929 9930 void RISCVTargetLowering::analyzeOutputArgs( 9931 MachineFunction &MF, CCState &CCInfo, 9932 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 9933 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 9934 unsigned NumArgs = Outs.size(); 9935 9936 Optional<unsigned> FirstMaskArgument; 9937 if (Subtarget.hasVInstructions()) 9938 FirstMaskArgument = preAssignMask(Outs); 9939 9940 for (unsigned i = 0; i != NumArgs; i++) { 9941 MVT ArgVT = Outs[i].VT; 9942 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 9943 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 9944 9945 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 9946 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 9947 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 9948 FirstMaskArgument)) { 9949 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 9950 << EVT(ArgVT).getEVTString() << "\n"); 9951 llvm_unreachable(nullptr); 9952 } 9953 } 9954 } 9955 9956 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 9957 // values. 9958 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 9959 const CCValAssign &VA, const SDLoc &DL, 9960 const RISCVSubtarget &Subtarget) { 9961 switch (VA.getLocInfo()) { 9962 default: 9963 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 9964 case CCValAssign::Full: 9965 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 9966 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 9967 break; 9968 case CCValAssign::BCvt: 9969 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 9970 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 9971 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 9972 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 9973 else 9974 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 9975 break; 9976 } 9977 return Val; 9978 } 9979 9980 // The caller is responsible for loading the full value if the argument is 9981 // passed with CCValAssign::Indirect. 9982 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 9983 const CCValAssign &VA, const SDLoc &DL, 9984 const RISCVTargetLowering &TLI) { 9985 MachineFunction &MF = DAG.getMachineFunction(); 9986 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9987 EVT LocVT = VA.getLocVT(); 9988 SDValue Val; 9989 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 9990 Register VReg = RegInfo.createVirtualRegister(RC); 9991 RegInfo.addLiveIn(VA.getLocReg(), VReg); 9992 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 9993 9994 if (VA.getLocInfo() == CCValAssign::Indirect) 9995 return Val; 9996 9997 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 9998 } 9999 10000 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 10001 const CCValAssign &VA, const SDLoc &DL, 10002 const RISCVSubtarget &Subtarget) { 10003 EVT LocVT = VA.getLocVT(); 10004 10005 switch (VA.getLocInfo()) { 10006 default: 10007 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10008 case CCValAssign::Full: 10009 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 10010 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 10011 break; 10012 case CCValAssign::BCvt: 10013 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10014 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 10015 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10016 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 10017 else 10018 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 10019 break; 10020 } 10021 return Val; 10022 } 10023 10024 // The caller is responsible for loading the full value if the argument is 10025 // passed with CCValAssign::Indirect. 10026 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 10027 const CCValAssign &VA, const SDLoc &DL) { 10028 MachineFunction &MF = DAG.getMachineFunction(); 10029 MachineFrameInfo &MFI = MF.getFrameInfo(); 10030 EVT LocVT = VA.getLocVT(); 10031 EVT ValVT = VA.getValVT(); 10032 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 10033 if (ValVT.isScalableVector()) { 10034 // When the value is a scalable vector, we save the pointer which points to 10035 // the scalable vector value in the stack. The ValVT will be the pointer 10036 // type, instead of the scalable vector type. 10037 ValVT = LocVT; 10038 } 10039 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 10040 /*IsImmutable=*/true); 10041 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 10042 SDValue Val; 10043 10044 ISD::LoadExtType ExtType; 10045 switch (VA.getLocInfo()) { 10046 default: 10047 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10048 case CCValAssign::Full: 10049 case CCValAssign::Indirect: 10050 case CCValAssign::BCvt: 10051 ExtType = ISD::NON_EXTLOAD; 10052 break; 10053 } 10054 Val = DAG.getExtLoad( 10055 ExtType, DL, LocVT, Chain, FIN, 10056 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 10057 return Val; 10058 } 10059 10060 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 10061 const CCValAssign &VA, const SDLoc &DL) { 10062 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 10063 "Unexpected VA"); 10064 MachineFunction &MF = DAG.getMachineFunction(); 10065 MachineFrameInfo &MFI = MF.getFrameInfo(); 10066 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10067 10068 if (VA.isMemLoc()) { 10069 // f64 is passed on the stack. 10070 int FI = 10071 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 10072 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10073 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 10074 MachinePointerInfo::getFixedStack(MF, FI)); 10075 } 10076 10077 assert(VA.isRegLoc() && "Expected register VA assignment"); 10078 10079 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10080 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 10081 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 10082 SDValue Hi; 10083 if (VA.getLocReg() == RISCV::X17) { 10084 // Second half of f64 is passed on the stack. 10085 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 10086 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10087 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 10088 MachinePointerInfo::getFixedStack(MF, FI)); 10089 } else { 10090 // Second half of f64 is passed in another GPR. 10091 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10092 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 10093 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 10094 } 10095 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 10096 } 10097 10098 // FastCC has less than 1% performance improvement for some particular 10099 // benchmark. But theoretically, it may has benenfit for some cases. 10100 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 10101 unsigned ValNo, MVT ValVT, MVT LocVT, 10102 CCValAssign::LocInfo LocInfo, 10103 ISD::ArgFlagsTy ArgFlags, CCState &State, 10104 bool IsFixed, bool IsRet, Type *OrigTy, 10105 const RISCVTargetLowering &TLI, 10106 Optional<unsigned> FirstMaskArgument) { 10107 10108 // X5 and X6 might be used for save-restore libcall. 10109 static const MCPhysReg GPRList[] = { 10110 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 10111 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 10112 RISCV::X29, RISCV::X30, RISCV::X31}; 10113 10114 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10115 if (unsigned Reg = State.AllocateReg(GPRList)) { 10116 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10117 return false; 10118 } 10119 } 10120 10121 if (LocVT == MVT::f16) { 10122 static const MCPhysReg FPR16List[] = { 10123 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 10124 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 10125 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 10126 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 10127 if (unsigned Reg = State.AllocateReg(FPR16List)) { 10128 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10129 return false; 10130 } 10131 } 10132 10133 if (LocVT == MVT::f32) { 10134 static const MCPhysReg FPR32List[] = { 10135 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 10136 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 10137 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 10138 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 10139 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10140 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10141 return false; 10142 } 10143 } 10144 10145 if (LocVT == MVT::f64) { 10146 static const MCPhysReg FPR64List[] = { 10147 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 10148 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 10149 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 10150 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 10151 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10152 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10153 return false; 10154 } 10155 } 10156 10157 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 10158 unsigned Offset4 = State.AllocateStack(4, Align(4)); 10159 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 10160 return false; 10161 } 10162 10163 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 10164 unsigned Offset5 = State.AllocateStack(8, Align(8)); 10165 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 10166 return false; 10167 } 10168 10169 if (LocVT.isVector()) { 10170 if (unsigned Reg = 10171 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 10172 // Fixed-length vectors are located in the corresponding scalable-vector 10173 // container types. 10174 if (ValVT.isFixedLengthVector()) 10175 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10176 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10177 } else { 10178 // Try and pass the address via a "fast" GPR. 10179 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 10180 LocInfo = CCValAssign::Indirect; 10181 LocVT = TLI.getSubtarget().getXLenVT(); 10182 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 10183 } else if (ValVT.isFixedLengthVector()) { 10184 auto StackAlign = 10185 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10186 unsigned StackOffset = 10187 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 10188 State.addLoc( 10189 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10190 } else { 10191 // Can't pass scalable vectors on the stack. 10192 return true; 10193 } 10194 } 10195 10196 return false; 10197 } 10198 10199 return true; // CC didn't match. 10200 } 10201 10202 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 10203 CCValAssign::LocInfo LocInfo, 10204 ISD::ArgFlagsTy ArgFlags, CCState &State) { 10205 10206 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10207 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 10208 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 10209 static const MCPhysReg GPRList[] = { 10210 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 10211 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 10212 if (unsigned Reg = State.AllocateReg(GPRList)) { 10213 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10214 return false; 10215 } 10216 } 10217 10218 if (LocVT == MVT::f32) { 10219 // Pass in STG registers: F1, ..., F6 10220 // fs0 ... fs5 10221 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 10222 RISCV::F18_F, RISCV::F19_F, 10223 RISCV::F20_F, RISCV::F21_F}; 10224 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10225 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10226 return false; 10227 } 10228 } 10229 10230 if (LocVT == MVT::f64) { 10231 // Pass in STG registers: D1, ..., D6 10232 // fs6 ... fs11 10233 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 10234 RISCV::F24_D, RISCV::F25_D, 10235 RISCV::F26_D, RISCV::F27_D}; 10236 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10237 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10238 return false; 10239 } 10240 } 10241 10242 report_fatal_error("No registers left in GHC calling convention"); 10243 return true; 10244 } 10245 10246 // Transform physical registers into virtual registers. 10247 SDValue RISCVTargetLowering::LowerFormalArguments( 10248 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 10249 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 10250 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 10251 10252 MachineFunction &MF = DAG.getMachineFunction(); 10253 10254 switch (CallConv) { 10255 default: 10256 report_fatal_error("Unsupported calling convention"); 10257 case CallingConv::C: 10258 case CallingConv::Fast: 10259 break; 10260 case CallingConv::GHC: 10261 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10262 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10263 report_fatal_error( 10264 "GHC calling convention requires the F and D instruction set extensions"); 10265 } 10266 10267 const Function &Func = MF.getFunction(); 10268 if (Func.hasFnAttribute("interrupt")) { 10269 if (!Func.arg_empty()) 10270 report_fatal_error( 10271 "Functions with the interrupt attribute cannot have arguments!"); 10272 10273 StringRef Kind = 10274 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10275 10276 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10277 report_fatal_error( 10278 "Function interrupt attribute argument not supported!"); 10279 } 10280 10281 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10282 MVT XLenVT = Subtarget.getXLenVT(); 10283 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10284 // Used with vargs to acumulate store chains. 10285 std::vector<SDValue> OutChains; 10286 10287 // Assign locations to all of the incoming arguments. 10288 SmallVector<CCValAssign, 16> ArgLocs; 10289 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10290 10291 if (CallConv == CallingConv::GHC) 10292 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10293 else 10294 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10295 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10296 : CC_RISCV); 10297 10298 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10299 CCValAssign &VA = ArgLocs[i]; 10300 SDValue ArgValue; 10301 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10302 // case. 10303 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10304 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10305 else if (VA.isRegLoc()) 10306 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10307 else 10308 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10309 10310 if (VA.getLocInfo() == CCValAssign::Indirect) { 10311 // If the original argument was split and passed by reference (e.g. i128 10312 // on RV32), we need to load all parts of it here (using the same 10313 // address). Vectors may be partly split to registers and partly to the 10314 // stack, in which case the base address is partly offset and subsequent 10315 // stores are relative to that. 10316 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10317 MachinePointerInfo())); 10318 unsigned ArgIndex = Ins[i].OrigArgIndex; 10319 unsigned ArgPartOffset = Ins[i].PartOffset; 10320 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10321 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10322 CCValAssign &PartVA = ArgLocs[i + 1]; 10323 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10324 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10325 if (PartVA.getValVT().isScalableVector()) 10326 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10327 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10328 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10329 MachinePointerInfo())); 10330 ++i; 10331 } 10332 continue; 10333 } 10334 InVals.push_back(ArgValue); 10335 } 10336 10337 if (IsVarArg) { 10338 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10339 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10340 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10341 MachineFrameInfo &MFI = MF.getFrameInfo(); 10342 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10343 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10344 10345 // Offset of the first variable argument from stack pointer, and size of 10346 // the vararg save area. For now, the varargs save area is either zero or 10347 // large enough to hold a0-a7. 10348 int VaArgOffset, VarArgsSaveSize; 10349 10350 // If all registers are allocated, then all varargs must be passed on the 10351 // stack and we don't need to save any argregs. 10352 if (ArgRegs.size() == Idx) { 10353 VaArgOffset = CCInfo.getNextStackOffset(); 10354 VarArgsSaveSize = 0; 10355 } else { 10356 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10357 VaArgOffset = -VarArgsSaveSize; 10358 } 10359 10360 // Record the frame index of the first variable argument 10361 // which is a value necessary to VASTART. 10362 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10363 RVFI->setVarArgsFrameIndex(FI); 10364 10365 // If saving an odd number of registers then create an extra stack slot to 10366 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10367 // offsets to even-numbered registered remain 2*XLEN-aligned. 10368 if (Idx % 2) { 10369 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10370 VarArgsSaveSize += XLenInBytes; 10371 } 10372 10373 // Copy the integer registers that may have been used for passing varargs 10374 // to the vararg save area. 10375 for (unsigned I = Idx; I < ArgRegs.size(); 10376 ++I, VaArgOffset += XLenInBytes) { 10377 const Register Reg = RegInfo.createVirtualRegister(RC); 10378 RegInfo.addLiveIn(ArgRegs[I], Reg); 10379 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10380 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10381 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10382 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10383 MachinePointerInfo::getFixedStack(MF, FI)); 10384 cast<StoreSDNode>(Store.getNode()) 10385 ->getMemOperand() 10386 ->setValue((Value *)nullptr); 10387 OutChains.push_back(Store); 10388 } 10389 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10390 } 10391 10392 // All stores are grouped in one node to allow the matching between 10393 // the size of Ins and InVals. This only happens for vararg functions. 10394 if (!OutChains.empty()) { 10395 OutChains.push_back(Chain); 10396 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10397 } 10398 10399 return Chain; 10400 } 10401 10402 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10403 /// for tail call optimization. 10404 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10405 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10406 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10407 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10408 10409 auto &Callee = CLI.Callee; 10410 auto CalleeCC = CLI.CallConv; 10411 auto &Outs = CLI.Outs; 10412 auto &Caller = MF.getFunction(); 10413 auto CallerCC = Caller.getCallingConv(); 10414 10415 // Exception-handling functions need a special set of instructions to 10416 // indicate a return to the hardware. Tail-calling another function would 10417 // probably break this. 10418 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10419 // should be expanded as new function attributes are introduced. 10420 if (Caller.hasFnAttribute("interrupt")) 10421 return false; 10422 10423 // Do not tail call opt if the stack is used to pass parameters. 10424 if (CCInfo.getNextStackOffset() != 0) 10425 return false; 10426 10427 // Do not tail call opt if any parameters need to be passed indirectly. 10428 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10429 // passed indirectly. So the address of the value will be passed in a 10430 // register, or if not available, then the address is put on the stack. In 10431 // order to pass indirectly, space on the stack often needs to be allocated 10432 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10433 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10434 // are passed CCValAssign::Indirect. 10435 for (auto &VA : ArgLocs) 10436 if (VA.getLocInfo() == CCValAssign::Indirect) 10437 return false; 10438 10439 // Do not tail call opt if either caller or callee uses struct return 10440 // semantics. 10441 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10442 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10443 if (IsCallerStructRet || IsCalleeStructRet) 10444 return false; 10445 10446 // Externally-defined functions with weak linkage should not be 10447 // tail-called. The behaviour of branch instructions in this situation (as 10448 // used for tail calls) is implementation-defined, so we cannot rely on the 10449 // linker replacing the tail call with a return. 10450 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10451 const GlobalValue *GV = G->getGlobal(); 10452 if (GV->hasExternalWeakLinkage()) 10453 return false; 10454 } 10455 10456 // The callee has to preserve all registers the caller needs to preserve. 10457 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10458 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10459 if (CalleeCC != CallerCC) { 10460 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10461 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10462 return false; 10463 } 10464 10465 // Byval parameters hand the function a pointer directly into the stack area 10466 // we want to reuse during a tail call. Working around this *is* possible 10467 // but less efficient and uglier in LowerCall. 10468 for (auto &Arg : Outs) 10469 if (Arg.Flags.isByVal()) 10470 return false; 10471 10472 return true; 10473 } 10474 10475 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10476 return DAG.getDataLayout().getPrefTypeAlign( 10477 VT.getTypeForEVT(*DAG.getContext())); 10478 } 10479 10480 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10481 // and output parameter nodes. 10482 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10483 SmallVectorImpl<SDValue> &InVals) const { 10484 SelectionDAG &DAG = CLI.DAG; 10485 SDLoc &DL = CLI.DL; 10486 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10487 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10488 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10489 SDValue Chain = CLI.Chain; 10490 SDValue Callee = CLI.Callee; 10491 bool &IsTailCall = CLI.IsTailCall; 10492 CallingConv::ID CallConv = CLI.CallConv; 10493 bool IsVarArg = CLI.IsVarArg; 10494 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10495 MVT XLenVT = Subtarget.getXLenVT(); 10496 10497 MachineFunction &MF = DAG.getMachineFunction(); 10498 10499 // Analyze the operands of the call, assigning locations to each operand. 10500 SmallVector<CCValAssign, 16> ArgLocs; 10501 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10502 10503 if (CallConv == CallingConv::GHC) 10504 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10505 else 10506 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10507 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10508 : CC_RISCV); 10509 10510 // Check if it's really possible to do a tail call. 10511 if (IsTailCall) 10512 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10513 10514 if (IsTailCall) 10515 ++NumTailCalls; 10516 else if (CLI.CB && CLI.CB->isMustTailCall()) 10517 report_fatal_error("failed to perform tail call elimination on a call " 10518 "site marked musttail"); 10519 10520 // Get a count of how many bytes are to be pushed on the stack. 10521 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10522 10523 // Create local copies for byval args 10524 SmallVector<SDValue, 8> ByValArgs; 10525 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10526 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10527 if (!Flags.isByVal()) 10528 continue; 10529 10530 SDValue Arg = OutVals[i]; 10531 unsigned Size = Flags.getByValSize(); 10532 Align Alignment = Flags.getNonZeroByValAlign(); 10533 10534 int FI = 10535 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10536 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10537 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10538 10539 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10540 /*IsVolatile=*/false, 10541 /*AlwaysInline=*/false, IsTailCall, 10542 MachinePointerInfo(), MachinePointerInfo()); 10543 ByValArgs.push_back(FIPtr); 10544 } 10545 10546 if (!IsTailCall) 10547 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10548 10549 // Copy argument values to their designated locations. 10550 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10551 SmallVector<SDValue, 8> MemOpChains; 10552 SDValue StackPtr; 10553 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10554 CCValAssign &VA = ArgLocs[i]; 10555 SDValue ArgValue = OutVals[i]; 10556 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10557 10558 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10559 bool IsF64OnRV32DSoftABI = 10560 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 10561 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 10562 SDValue SplitF64 = DAG.getNode( 10563 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 10564 SDValue Lo = SplitF64.getValue(0); 10565 SDValue Hi = SplitF64.getValue(1); 10566 10567 Register RegLo = VA.getLocReg(); 10568 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 10569 10570 if (RegLo == RISCV::X17) { 10571 // Second half of f64 is passed on the stack. 10572 // Work out the address of the stack slot. 10573 if (!StackPtr.getNode()) 10574 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10575 // Emit the store. 10576 MemOpChains.push_back( 10577 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 10578 } else { 10579 // Second half of f64 is passed in another GPR. 10580 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10581 Register RegHigh = RegLo + 1; 10582 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 10583 } 10584 continue; 10585 } 10586 10587 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 10588 // as any other MemLoc. 10589 10590 // Promote the value if needed. 10591 // For now, only handle fully promoted and indirect arguments. 10592 if (VA.getLocInfo() == CCValAssign::Indirect) { 10593 // Store the argument in a stack slot and pass its address. 10594 Align StackAlign = 10595 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 10596 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 10597 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 10598 // If the original argument was split (e.g. i128), we need 10599 // to store the required parts of it here (and pass just one address). 10600 // Vectors may be partly split to registers and partly to the stack, in 10601 // which case the base address is partly offset and subsequent stores are 10602 // relative to that. 10603 unsigned ArgIndex = Outs[i].OrigArgIndex; 10604 unsigned ArgPartOffset = Outs[i].PartOffset; 10605 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10606 // Calculate the total size to store. We don't have access to what we're 10607 // actually storing other than performing the loop and collecting the 10608 // info. 10609 SmallVector<std::pair<SDValue, SDValue>> Parts; 10610 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 10611 SDValue PartValue = OutVals[i + 1]; 10612 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 10613 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10614 EVT PartVT = PartValue.getValueType(); 10615 if (PartVT.isScalableVector()) 10616 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10617 StoredSize += PartVT.getStoreSize(); 10618 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 10619 Parts.push_back(std::make_pair(PartValue, Offset)); 10620 ++i; 10621 } 10622 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 10623 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 10624 MemOpChains.push_back( 10625 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 10626 MachinePointerInfo::getFixedStack(MF, FI))); 10627 for (const auto &Part : Parts) { 10628 SDValue PartValue = Part.first; 10629 SDValue PartOffset = Part.second; 10630 SDValue Address = 10631 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 10632 MemOpChains.push_back( 10633 DAG.getStore(Chain, DL, PartValue, Address, 10634 MachinePointerInfo::getFixedStack(MF, FI))); 10635 } 10636 ArgValue = SpillSlot; 10637 } else { 10638 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 10639 } 10640 10641 // Use local copy if it is a byval arg. 10642 if (Flags.isByVal()) 10643 ArgValue = ByValArgs[j++]; 10644 10645 if (VA.isRegLoc()) { 10646 // Queue up the argument copies and emit them at the end. 10647 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 10648 } else { 10649 assert(VA.isMemLoc() && "Argument not register or memory"); 10650 assert(!IsTailCall && "Tail call not allowed if stack is used " 10651 "for passing parameters"); 10652 10653 // Work out the address of the stack slot. 10654 if (!StackPtr.getNode()) 10655 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10656 SDValue Address = 10657 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 10658 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 10659 10660 // Emit the store. 10661 MemOpChains.push_back( 10662 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 10663 } 10664 } 10665 10666 // Join the stores, which are independent of one another. 10667 if (!MemOpChains.empty()) 10668 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 10669 10670 SDValue Glue; 10671 10672 // Build a sequence of copy-to-reg nodes, chained and glued together. 10673 for (auto &Reg : RegsToPass) { 10674 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 10675 Glue = Chain.getValue(1); 10676 } 10677 10678 // Validate that none of the argument registers have been marked as 10679 // reserved, if so report an error. Do the same for the return address if this 10680 // is not a tailcall. 10681 validateCCReservedRegs(RegsToPass, MF); 10682 if (!IsTailCall && 10683 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 10684 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10685 MF.getFunction(), 10686 "Return address register required, but has been reserved."}); 10687 10688 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 10689 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 10690 // split it and then direct call can be matched by PseudoCALL. 10691 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 10692 const GlobalValue *GV = S->getGlobal(); 10693 10694 unsigned OpFlags = RISCVII::MO_CALL; 10695 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 10696 OpFlags = RISCVII::MO_PLT; 10697 10698 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 10699 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 10700 unsigned OpFlags = RISCVII::MO_CALL; 10701 10702 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 10703 nullptr)) 10704 OpFlags = RISCVII::MO_PLT; 10705 10706 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 10707 } 10708 10709 // The first call operand is the chain and the second is the target address. 10710 SmallVector<SDValue, 8> Ops; 10711 Ops.push_back(Chain); 10712 Ops.push_back(Callee); 10713 10714 // Add argument registers to the end of the list so that they are 10715 // known live into the call. 10716 for (auto &Reg : RegsToPass) 10717 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 10718 10719 if (!IsTailCall) { 10720 // Add a register mask operand representing the call-preserved registers. 10721 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10722 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 10723 assert(Mask && "Missing call preserved mask for calling convention"); 10724 Ops.push_back(DAG.getRegisterMask(Mask)); 10725 } 10726 10727 // Glue the call to the argument copies, if any. 10728 if (Glue.getNode()) 10729 Ops.push_back(Glue); 10730 10731 // Emit the call. 10732 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10733 10734 if (IsTailCall) { 10735 MF.getFrameInfo().setHasTailCall(); 10736 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 10737 } 10738 10739 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 10740 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 10741 Glue = Chain.getValue(1); 10742 10743 // Mark the end of the call, which is glued to the call itself. 10744 Chain = DAG.getCALLSEQ_END(Chain, 10745 DAG.getConstant(NumBytes, DL, PtrVT, true), 10746 DAG.getConstant(0, DL, PtrVT, true), 10747 Glue, DL); 10748 Glue = Chain.getValue(1); 10749 10750 // Assign locations to each value returned by this call. 10751 SmallVector<CCValAssign, 16> RVLocs; 10752 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 10753 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 10754 10755 // Copy all of the result registers out of their specified physreg. 10756 for (auto &VA : RVLocs) { 10757 // Copy the value out 10758 SDValue RetValue = 10759 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 10760 // Glue the RetValue to the end of the call sequence 10761 Chain = RetValue.getValue(1); 10762 Glue = RetValue.getValue(2); 10763 10764 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10765 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 10766 SDValue RetValue2 = 10767 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 10768 Chain = RetValue2.getValue(1); 10769 Glue = RetValue2.getValue(2); 10770 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 10771 RetValue2); 10772 } 10773 10774 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 10775 10776 InVals.push_back(RetValue); 10777 } 10778 10779 return Chain; 10780 } 10781 10782 bool RISCVTargetLowering::CanLowerReturn( 10783 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 10784 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 10785 SmallVector<CCValAssign, 16> RVLocs; 10786 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 10787 10788 Optional<unsigned> FirstMaskArgument; 10789 if (Subtarget.hasVInstructions()) 10790 FirstMaskArgument = preAssignMask(Outs); 10791 10792 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10793 MVT VT = Outs[i].VT; 10794 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10795 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10796 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 10797 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 10798 *this, FirstMaskArgument)) 10799 return false; 10800 } 10801 return true; 10802 } 10803 10804 SDValue 10805 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 10806 bool IsVarArg, 10807 const SmallVectorImpl<ISD::OutputArg> &Outs, 10808 const SmallVectorImpl<SDValue> &OutVals, 10809 const SDLoc &DL, SelectionDAG &DAG) const { 10810 const MachineFunction &MF = DAG.getMachineFunction(); 10811 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10812 10813 // Stores the assignment of the return value to a location. 10814 SmallVector<CCValAssign, 16> RVLocs; 10815 10816 // Info about the registers and stack slot. 10817 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 10818 *DAG.getContext()); 10819 10820 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 10821 nullptr, CC_RISCV); 10822 10823 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 10824 report_fatal_error("GHC functions return void only"); 10825 10826 SDValue Glue; 10827 SmallVector<SDValue, 4> RetOps(1, Chain); 10828 10829 // Copy the result values into the output registers. 10830 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 10831 SDValue Val = OutVals[i]; 10832 CCValAssign &VA = RVLocs[i]; 10833 assert(VA.isRegLoc() && "Can only return in registers!"); 10834 10835 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10836 // Handle returning f64 on RV32D with a soft float ABI. 10837 assert(VA.isRegLoc() && "Expected return via registers"); 10838 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 10839 DAG.getVTList(MVT::i32, MVT::i32), Val); 10840 SDValue Lo = SplitF64.getValue(0); 10841 SDValue Hi = SplitF64.getValue(1); 10842 Register RegLo = VA.getLocReg(); 10843 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10844 Register RegHi = RegLo + 1; 10845 10846 if (STI.isRegisterReservedByUser(RegLo) || 10847 STI.isRegisterReservedByUser(RegHi)) 10848 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10849 MF.getFunction(), 10850 "Return value register required, but has been reserved."}); 10851 10852 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 10853 Glue = Chain.getValue(1); 10854 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 10855 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 10856 Glue = Chain.getValue(1); 10857 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 10858 } else { 10859 // Handle a 'normal' return. 10860 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 10861 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 10862 10863 if (STI.isRegisterReservedByUser(VA.getLocReg())) 10864 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10865 MF.getFunction(), 10866 "Return value register required, but has been reserved."}); 10867 10868 // Guarantee that all emitted copies are stuck together. 10869 Glue = Chain.getValue(1); 10870 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 10871 } 10872 } 10873 10874 RetOps[0] = Chain; // Update chain. 10875 10876 // Add the glue node if we have it. 10877 if (Glue.getNode()) { 10878 RetOps.push_back(Glue); 10879 } 10880 10881 unsigned RetOpc = RISCVISD::RET_FLAG; 10882 // Interrupt service routines use different return instructions. 10883 const Function &Func = DAG.getMachineFunction().getFunction(); 10884 if (Func.hasFnAttribute("interrupt")) { 10885 if (!Func.getReturnType()->isVoidTy()) 10886 report_fatal_error( 10887 "Functions with the interrupt attribute must have void return type!"); 10888 10889 MachineFunction &MF = DAG.getMachineFunction(); 10890 StringRef Kind = 10891 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10892 10893 if (Kind == "user") 10894 RetOpc = RISCVISD::URET_FLAG; 10895 else if (Kind == "supervisor") 10896 RetOpc = RISCVISD::SRET_FLAG; 10897 else 10898 RetOpc = RISCVISD::MRET_FLAG; 10899 } 10900 10901 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 10902 } 10903 10904 void RISCVTargetLowering::validateCCReservedRegs( 10905 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 10906 MachineFunction &MF) const { 10907 const Function &F = MF.getFunction(); 10908 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10909 10910 if (llvm::any_of(Regs, [&STI](auto Reg) { 10911 return STI.isRegisterReservedByUser(Reg.first); 10912 })) 10913 F.getContext().diagnose(DiagnosticInfoUnsupported{ 10914 F, "Argument register required, but has been reserved."}); 10915 } 10916 10917 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 10918 return CI->isTailCall(); 10919 } 10920 10921 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 10922 #define NODE_NAME_CASE(NODE) \ 10923 case RISCVISD::NODE: \ 10924 return "RISCVISD::" #NODE; 10925 // clang-format off 10926 switch ((RISCVISD::NodeType)Opcode) { 10927 case RISCVISD::FIRST_NUMBER: 10928 break; 10929 NODE_NAME_CASE(RET_FLAG) 10930 NODE_NAME_CASE(URET_FLAG) 10931 NODE_NAME_CASE(SRET_FLAG) 10932 NODE_NAME_CASE(MRET_FLAG) 10933 NODE_NAME_CASE(CALL) 10934 NODE_NAME_CASE(SELECT_CC) 10935 NODE_NAME_CASE(BR_CC) 10936 NODE_NAME_CASE(BuildPairF64) 10937 NODE_NAME_CASE(SplitF64) 10938 NODE_NAME_CASE(TAIL) 10939 NODE_NAME_CASE(MULHSU) 10940 NODE_NAME_CASE(SLLW) 10941 NODE_NAME_CASE(SRAW) 10942 NODE_NAME_CASE(SRLW) 10943 NODE_NAME_CASE(DIVW) 10944 NODE_NAME_CASE(DIVUW) 10945 NODE_NAME_CASE(REMUW) 10946 NODE_NAME_CASE(ROLW) 10947 NODE_NAME_CASE(RORW) 10948 NODE_NAME_CASE(CLZW) 10949 NODE_NAME_CASE(CTZW) 10950 NODE_NAME_CASE(FSLW) 10951 NODE_NAME_CASE(FSRW) 10952 NODE_NAME_CASE(FSL) 10953 NODE_NAME_CASE(FSR) 10954 NODE_NAME_CASE(FMV_H_X) 10955 NODE_NAME_CASE(FMV_X_ANYEXTH) 10956 NODE_NAME_CASE(FMV_X_SIGNEXTH) 10957 NODE_NAME_CASE(FMV_W_X_RV64) 10958 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 10959 NODE_NAME_CASE(FCVT_X) 10960 NODE_NAME_CASE(FCVT_XU) 10961 NODE_NAME_CASE(FCVT_W_RV64) 10962 NODE_NAME_CASE(FCVT_WU_RV64) 10963 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 10964 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 10965 NODE_NAME_CASE(READ_CYCLE_WIDE) 10966 NODE_NAME_CASE(GREV) 10967 NODE_NAME_CASE(GREVW) 10968 NODE_NAME_CASE(GORC) 10969 NODE_NAME_CASE(GORCW) 10970 NODE_NAME_CASE(SHFL) 10971 NODE_NAME_CASE(SHFLW) 10972 NODE_NAME_CASE(UNSHFL) 10973 NODE_NAME_CASE(UNSHFLW) 10974 NODE_NAME_CASE(BFP) 10975 NODE_NAME_CASE(BFPW) 10976 NODE_NAME_CASE(BCOMPRESS) 10977 NODE_NAME_CASE(BCOMPRESSW) 10978 NODE_NAME_CASE(BDECOMPRESS) 10979 NODE_NAME_CASE(BDECOMPRESSW) 10980 NODE_NAME_CASE(VMV_V_X_VL) 10981 NODE_NAME_CASE(VFMV_V_F_VL) 10982 NODE_NAME_CASE(VMV_X_S) 10983 NODE_NAME_CASE(VMV_S_X_VL) 10984 NODE_NAME_CASE(VFMV_S_F_VL) 10985 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 10986 NODE_NAME_CASE(READ_VLENB) 10987 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 10988 NODE_NAME_CASE(VSLIDEUP_VL) 10989 NODE_NAME_CASE(VSLIDE1UP_VL) 10990 NODE_NAME_CASE(VSLIDEDOWN_VL) 10991 NODE_NAME_CASE(VSLIDE1DOWN_VL) 10992 NODE_NAME_CASE(VID_VL) 10993 NODE_NAME_CASE(VFNCVT_ROD_VL) 10994 NODE_NAME_CASE(VECREDUCE_ADD_VL) 10995 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 10996 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 10997 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 10998 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 10999 NODE_NAME_CASE(VECREDUCE_AND_VL) 11000 NODE_NAME_CASE(VECREDUCE_OR_VL) 11001 NODE_NAME_CASE(VECREDUCE_XOR_VL) 11002 NODE_NAME_CASE(VECREDUCE_FADD_VL) 11003 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 11004 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 11005 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 11006 NODE_NAME_CASE(ADD_VL) 11007 NODE_NAME_CASE(AND_VL) 11008 NODE_NAME_CASE(MUL_VL) 11009 NODE_NAME_CASE(OR_VL) 11010 NODE_NAME_CASE(SDIV_VL) 11011 NODE_NAME_CASE(SHL_VL) 11012 NODE_NAME_CASE(SREM_VL) 11013 NODE_NAME_CASE(SRA_VL) 11014 NODE_NAME_CASE(SRL_VL) 11015 NODE_NAME_CASE(SUB_VL) 11016 NODE_NAME_CASE(UDIV_VL) 11017 NODE_NAME_CASE(UREM_VL) 11018 NODE_NAME_CASE(XOR_VL) 11019 NODE_NAME_CASE(SADDSAT_VL) 11020 NODE_NAME_CASE(UADDSAT_VL) 11021 NODE_NAME_CASE(SSUBSAT_VL) 11022 NODE_NAME_CASE(USUBSAT_VL) 11023 NODE_NAME_CASE(FADD_VL) 11024 NODE_NAME_CASE(FSUB_VL) 11025 NODE_NAME_CASE(FMUL_VL) 11026 NODE_NAME_CASE(FDIV_VL) 11027 NODE_NAME_CASE(FNEG_VL) 11028 NODE_NAME_CASE(FABS_VL) 11029 NODE_NAME_CASE(FSQRT_VL) 11030 NODE_NAME_CASE(FMA_VL) 11031 NODE_NAME_CASE(FCOPYSIGN_VL) 11032 NODE_NAME_CASE(SMIN_VL) 11033 NODE_NAME_CASE(SMAX_VL) 11034 NODE_NAME_CASE(UMIN_VL) 11035 NODE_NAME_CASE(UMAX_VL) 11036 NODE_NAME_CASE(FMINNUM_VL) 11037 NODE_NAME_CASE(FMAXNUM_VL) 11038 NODE_NAME_CASE(MULHS_VL) 11039 NODE_NAME_CASE(MULHU_VL) 11040 NODE_NAME_CASE(FP_TO_SINT_VL) 11041 NODE_NAME_CASE(FP_TO_UINT_VL) 11042 NODE_NAME_CASE(SINT_TO_FP_VL) 11043 NODE_NAME_CASE(UINT_TO_FP_VL) 11044 NODE_NAME_CASE(FP_EXTEND_VL) 11045 NODE_NAME_CASE(FP_ROUND_VL) 11046 NODE_NAME_CASE(VWMUL_VL) 11047 NODE_NAME_CASE(VWMULU_VL) 11048 NODE_NAME_CASE(VWMULSU_VL) 11049 NODE_NAME_CASE(VWADD_VL) 11050 NODE_NAME_CASE(VWADDU_VL) 11051 NODE_NAME_CASE(VWSUB_VL) 11052 NODE_NAME_CASE(VWSUBU_VL) 11053 NODE_NAME_CASE(VWADD_W_VL) 11054 NODE_NAME_CASE(VWADDU_W_VL) 11055 NODE_NAME_CASE(VWSUB_W_VL) 11056 NODE_NAME_CASE(VWSUBU_W_VL) 11057 NODE_NAME_CASE(SETCC_VL) 11058 NODE_NAME_CASE(VSELECT_VL) 11059 NODE_NAME_CASE(VP_MERGE_VL) 11060 NODE_NAME_CASE(VMAND_VL) 11061 NODE_NAME_CASE(VMOR_VL) 11062 NODE_NAME_CASE(VMXOR_VL) 11063 NODE_NAME_CASE(VMCLR_VL) 11064 NODE_NAME_CASE(VMSET_VL) 11065 NODE_NAME_CASE(VRGATHER_VX_VL) 11066 NODE_NAME_CASE(VRGATHER_VV_VL) 11067 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 11068 NODE_NAME_CASE(VSEXT_VL) 11069 NODE_NAME_CASE(VZEXT_VL) 11070 NODE_NAME_CASE(VCPOP_VL) 11071 NODE_NAME_CASE(READ_CSR) 11072 NODE_NAME_CASE(WRITE_CSR) 11073 NODE_NAME_CASE(SWAP_CSR) 11074 } 11075 // clang-format on 11076 return nullptr; 11077 #undef NODE_NAME_CASE 11078 } 11079 11080 /// getConstraintType - Given a constraint letter, return the type of 11081 /// constraint it is for this target. 11082 RISCVTargetLowering::ConstraintType 11083 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 11084 if (Constraint.size() == 1) { 11085 switch (Constraint[0]) { 11086 default: 11087 break; 11088 case 'f': 11089 return C_RegisterClass; 11090 case 'I': 11091 case 'J': 11092 case 'K': 11093 return C_Immediate; 11094 case 'A': 11095 return C_Memory; 11096 case 'S': // A symbolic address 11097 return C_Other; 11098 } 11099 } else { 11100 if (Constraint == "vr" || Constraint == "vm") 11101 return C_RegisterClass; 11102 } 11103 return TargetLowering::getConstraintType(Constraint); 11104 } 11105 11106 std::pair<unsigned, const TargetRegisterClass *> 11107 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11108 StringRef Constraint, 11109 MVT VT) const { 11110 // First, see if this is a constraint that directly corresponds to a 11111 // RISCV register class. 11112 if (Constraint.size() == 1) { 11113 switch (Constraint[0]) { 11114 case 'r': 11115 // TODO: Support fixed vectors up to XLen for P extension? 11116 if (VT.isVector()) 11117 break; 11118 return std::make_pair(0U, &RISCV::GPRRegClass); 11119 case 'f': 11120 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 11121 return std::make_pair(0U, &RISCV::FPR16RegClass); 11122 if (Subtarget.hasStdExtF() && VT == MVT::f32) 11123 return std::make_pair(0U, &RISCV::FPR32RegClass); 11124 if (Subtarget.hasStdExtD() && VT == MVT::f64) 11125 return std::make_pair(0U, &RISCV::FPR64RegClass); 11126 break; 11127 default: 11128 break; 11129 } 11130 } else if (Constraint == "vr") { 11131 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 11132 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11133 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 11134 return std::make_pair(0U, RC); 11135 } 11136 } else if (Constraint == "vm") { 11137 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 11138 return std::make_pair(0U, &RISCV::VMV0RegClass); 11139 } 11140 11141 // Clang will correctly decode the usage of register name aliases into their 11142 // official names. However, other frontends like `rustc` do not. This allows 11143 // users of these frontends to use the ABI names for registers in LLVM-style 11144 // register constraints. 11145 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 11146 .Case("{zero}", RISCV::X0) 11147 .Case("{ra}", RISCV::X1) 11148 .Case("{sp}", RISCV::X2) 11149 .Case("{gp}", RISCV::X3) 11150 .Case("{tp}", RISCV::X4) 11151 .Case("{t0}", RISCV::X5) 11152 .Case("{t1}", RISCV::X6) 11153 .Case("{t2}", RISCV::X7) 11154 .Cases("{s0}", "{fp}", RISCV::X8) 11155 .Case("{s1}", RISCV::X9) 11156 .Case("{a0}", RISCV::X10) 11157 .Case("{a1}", RISCV::X11) 11158 .Case("{a2}", RISCV::X12) 11159 .Case("{a3}", RISCV::X13) 11160 .Case("{a4}", RISCV::X14) 11161 .Case("{a5}", RISCV::X15) 11162 .Case("{a6}", RISCV::X16) 11163 .Case("{a7}", RISCV::X17) 11164 .Case("{s2}", RISCV::X18) 11165 .Case("{s3}", RISCV::X19) 11166 .Case("{s4}", RISCV::X20) 11167 .Case("{s5}", RISCV::X21) 11168 .Case("{s6}", RISCV::X22) 11169 .Case("{s7}", RISCV::X23) 11170 .Case("{s8}", RISCV::X24) 11171 .Case("{s9}", RISCV::X25) 11172 .Case("{s10}", RISCV::X26) 11173 .Case("{s11}", RISCV::X27) 11174 .Case("{t3}", RISCV::X28) 11175 .Case("{t4}", RISCV::X29) 11176 .Case("{t5}", RISCV::X30) 11177 .Case("{t6}", RISCV::X31) 11178 .Default(RISCV::NoRegister); 11179 if (XRegFromAlias != RISCV::NoRegister) 11180 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 11181 11182 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 11183 // TableGen record rather than the AsmName to choose registers for InlineAsm 11184 // constraints, plus we want to match those names to the widest floating point 11185 // register type available, manually select floating point registers here. 11186 // 11187 // The second case is the ABI name of the register, so that frontends can also 11188 // use the ABI names in register constraint lists. 11189 if (Subtarget.hasStdExtF()) { 11190 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 11191 .Cases("{f0}", "{ft0}", RISCV::F0_F) 11192 .Cases("{f1}", "{ft1}", RISCV::F1_F) 11193 .Cases("{f2}", "{ft2}", RISCV::F2_F) 11194 .Cases("{f3}", "{ft3}", RISCV::F3_F) 11195 .Cases("{f4}", "{ft4}", RISCV::F4_F) 11196 .Cases("{f5}", "{ft5}", RISCV::F5_F) 11197 .Cases("{f6}", "{ft6}", RISCV::F6_F) 11198 .Cases("{f7}", "{ft7}", RISCV::F7_F) 11199 .Cases("{f8}", "{fs0}", RISCV::F8_F) 11200 .Cases("{f9}", "{fs1}", RISCV::F9_F) 11201 .Cases("{f10}", "{fa0}", RISCV::F10_F) 11202 .Cases("{f11}", "{fa1}", RISCV::F11_F) 11203 .Cases("{f12}", "{fa2}", RISCV::F12_F) 11204 .Cases("{f13}", "{fa3}", RISCV::F13_F) 11205 .Cases("{f14}", "{fa4}", RISCV::F14_F) 11206 .Cases("{f15}", "{fa5}", RISCV::F15_F) 11207 .Cases("{f16}", "{fa6}", RISCV::F16_F) 11208 .Cases("{f17}", "{fa7}", RISCV::F17_F) 11209 .Cases("{f18}", "{fs2}", RISCV::F18_F) 11210 .Cases("{f19}", "{fs3}", RISCV::F19_F) 11211 .Cases("{f20}", "{fs4}", RISCV::F20_F) 11212 .Cases("{f21}", "{fs5}", RISCV::F21_F) 11213 .Cases("{f22}", "{fs6}", RISCV::F22_F) 11214 .Cases("{f23}", "{fs7}", RISCV::F23_F) 11215 .Cases("{f24}", "{fs8}", RISCV::F24_F) 11216 .Cases("{f25}", "{fs9}", RISCV::F25_F) 11217 .Cases("{f26}", "{fs10}", RISCV::F26_F) 11218 .Cases("{f27}", "{fs11}", RISCV::F27_F) 11219 .Cases("{f28}", "{ft8}", RISCV::F28_F) 11220 .Cases("{f29}", "{ft9}", RISCV::F29_F) 11221 .Cases("{f30}", "{ft10}", RISCV::F30_F) 11222 .Cases("{f31}", "{ft11}", RISCV::F31_F) 11223 .Default(RISCV::NoRegister); 11224 if (FReg != RISCV::NoRegister) { 11225 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 11226 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 11227 unsigned RegNo = FReg - RISCV::F0_F; 11228 unsigned DReg = RISCV::F0_D + RegNo; 11229 return std::make_pair(DReg, &RISCV::FPR64RegClass); 11230 } 11231 if (VT == MVT::f32 || VT == MVT::Other) 11232 return std::make_pair(FReg, &RISCV::FPR32RegClass); 11233 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 11234 unsigned RegNo = FReg - RISCV::F0_F; 11235 unsigned HReg = RISCV::F0_H + RegNo; 11236 return std::make_pair(HReg, &RISCV::FPR16RegClass); 11237 } 11238 } 11239 } 11240 11241 if (Subtarget.hasVInstructions()) { 11242 Register VReg = StringSwitch<Register>(Constraint.lower()) 11243 .Case("{v0}", RISCV::V0) 11244 .Case("{v1}", RISCV::V1) 11245 .Case("{v2}", RISCV::V2) 11246 .Case("{v3}", RISCV::V3) 11247 .Case("{v4}", RISCV::V4) 11248 .Case("{v5}", RISCV::V5) 11249 .Case("{v6}", RISCV::V6) 11250 .Case("{v7}", RISCV::V7) 11251 .Case("{v8}", RISCV::V8) 11252 .Case("{v9}", RISCV::V9) 11253 .Case("{v10}", RISCV::V10) 11254 .Case("{v11}", RISCV::V11) 11255 .Case("{v12}", RISCV::V12) 11256 .Case("{v13}", RISCV::V13) 11257 .Case("{v14}", RISCV::V14) 11258 .Case("{v15}", RISCV::V15) 11259 .Case("{v16}", RISCV::V16) 11260 .Case("{v17}", RISCV::V17) 11261 .Case("{v18}", RISCV::V18) 11262 .Case("{v19}", RISCV::V19) 11263 .Case("{v20}", RISCV::V20) 11264 .Case("{v21}", RISCV::V21) 11265 .Case("{v22}", RISCV::V22) 11266 .Case("{v23}", RISCV::V23) 11267 .Case("{v24}", RISCV::V24) 11268 .Case("{v25}", RISCV::V25) 11269 .Case("{v26}", RISCV::V26) 11270 .Case("{v27}", RISCV::V27) 11271 .Case("{v28}", RISCV::V28) 11272 .Case("{v29}", RISCV::V29) 11273 .Case("{v30}", RISCV::V30) 11274 .Case("{v31}", RISCV::V31) 11275 .Default(RISCV::NoRegister); 11276 if (VReg != RISCV::NoRegister) { 11277 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11278 return std::make_pair(VReg, &RISCV::VMRegClass); 11279 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11280 return std::make_pair(VReg, &RISCV::VRRegClass); 11281 for (const auto *RC : 11282 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11283 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11284 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11285 return std::make_pair(VReg, RC); 11286 } 11287 } 11288 } 11289 } 11290 11291 std::pair<Register, const TargetRegisterClass *> Res = 11292 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11293 11294 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11295 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11296 // Subtarget into account. 11297 if (Res.second == &RISCV::GPRF16RegClass || 11298 Res.second == &RISCV::GPRF32RegClass || 11299 Res.second == &RISCV::GPRF64RegClass) 11300 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11301 11302 return Res; 11303 } 11304 11305 unsigned 11306 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11307 // Currently only support length 1 constraints. 11308 if (ConstraintCode.size() == 1) { 11309 switch (ConstraintCode[0]) { 11310 case 'A': 11311 return InlineAsm::Constraint_A; 11312 default: 11313 break; 11314 } 11315 } 11316 11317 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11318 } 11319 11320 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11321 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11322 SelectionDAG &DAG) const { 11323 // Currently only support length 1 constraints. 11324 if (Constraint.length() == 1) { 11325 switch (Constraint[0]) { 11326 case 'I': 11327 // Validate & create a 12-bit signed immediate operand. 11328 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11329 uint64_t CVal = C->getSExtValue(); 11330 if (isInt<12>(CVal)) 11331 Ops.push_back( 11332 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11333 } 11334 return; 11335 case 'J': 11336 // Validate & create an integer zero operand. 11337 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11338 if (C->getZExtValue() == 0) 11339 Ops.push_back( 11340 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11341 return; 11342 case 'K': 11343 // Validate & create a 5-bit unsigned immediate operand. 11344 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11345 uint64_t CVal = C->getZExtValue(); 11346 if (isUInt<5>(CVal)) 11347 Ops.push_back( 11348 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11349 } 11350 return; 11351 case 'S': 11352 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11353 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11354 GA->getValueType(0))); 11355 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11356 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11357 BA->getValueType(0))); 11358 } 11359 return; 11360 default: 11361 break; 11362 } 11363 } 11364 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11365 } 11366 11367 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11368 Instruction *Inst, 11369 AtomicOrdering Ord) const { 11370 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 11371 return Builder.CreateFence(Ord); 11372 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 11373 return Builder.CreateFence(AtomicOrdering::Release); 11374 return nullptr; 11375 } 11376 11377 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11378 Instruction *Inst, 11379 AtomicOrdering Ord) const { 11380 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11381 return Builder.CreateFence(AtomicOrdering::Acquire); 11382 return nullptr; 11383 } 11384 11385 TargetLowering::AtomicExpansionKind 11386 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11387 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11388 // point operations can't be used in an lr/sc sequence without breaking the 11389 // forward-progress guarantee. 11390 if (AI->isFloatingPointOperation()) 11391 return AtomicExpansionKind::CmpXChg; 11392 11393 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11394 if (Size == 8 || Size == 16) 11395 return AtomicExpansionKind::MaskedIntrinsic; 11396 return AtomicExpansionKind::None; 11397 } 11398 11399 static Intrinsic::ID 11400 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11401 if (XLen == 32) { 11402 switch (BinOp) { 11403 default: 11404 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11405 case AtomicRMWInst::Xchg: 11406 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11407 case AtomicRMWInst::Add: 11408 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11409 case AtomicRMWInst::Sub: 11410 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11411 case AtomicRMWInst::Nand: 11412 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11413 case AtomicRMWInst::Max: 11414 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11415 case AtomicRMWInst::Min: 11416 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11417 case AtomicRMWInst::UMax: 11418 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11419 case AtomicRMWInst::UMin: 11420 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11421 } 11422 } 11423 11424 if (XLen == 64) { 11425 switch (BinOp) { 11426 default: 11427 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11428 case AtomicRMWInst::Xchg: 11429 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11430 case AtomicRMWInst::Add: 11431 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11432 case AtomicRMWInst::Sub: 11433 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11434 case AtomicRMWInst::Nand: 11435 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11436 case AtomicRMWInst::Max: 11437 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11438 case AtomicRMWInst::Min: 11439 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11440 case AtomicRMWInst::UMax: 11441 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11442 case AtomicRMWInst::UMin: 11443 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11444 } 11445 } 11446 11447 llvm_unreachable("Unexpected XLen\n"); 11448 } 11449 11450 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11451 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11452 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11453 unsigned XLen = Subtarget.getXLen(); 11454 Value *Ordering = 11455 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11456 Type *Tys[] = {AlignedAddr->getType()}; 11457 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11458 AI->getModule(), 11459 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11460 11461 if (XLen == 64) { 11462 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11463 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11464 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11465 } 11466 11467 Value *Result; 11468 11469 // Must pass the shift amount needed to sign extend the loaded value prior 11470 // to performing a signed comparison for min/max. ShiftAmt is the number of 11471 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11472 // is the number of bits to left+right shift the value in order to 11473 // sign-extend. 11474 if (AI->getOperation() == AtomicRMWInst::Min || 11475 AI->getOperation() == AtomicRMWInst::Max) { 11476 const DataLayout &DL = AI->getModule()->getDataLayout(); 11477 unsigned ValWidth = 11478 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11479 Value *SextShamt = 11480 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11481 Result = Builder.CreateCall(LrwOpScwLoop, 11482 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11483 } else { 11484 Result = 11485 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11486 } 11487 11488 if (XLen == 64) 11489 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11490 return Result; 11491 } 11492 11493 TargetLowering::AtomicExpansionKind 11494 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11495 AtomicCmpXchgInst *CI) const { 11496 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11497 if (Size == 8 || Size == 16) 11498 return AtomicExpansionKind::MaskedIntrinsic; 11499 return AtomicExpansionKind::None; 11500 } 11501 11502 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11503 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11504 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11505 unsigned XLen = Subtarget.getXLen(); 11506 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11507 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11508 if (XLen == 64) { 11509 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11510 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11511 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11512 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11513 } 11514 Type *Tys[] = {AlignedAddr->getType()}; 11515 Function *MaskedCmpXchg = 11516 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11517 Value *Result = Builder.CreateCall( 11518 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11519 if (XLen == 64) 11520 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11521 return Result; 11522 } 11523 11524 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const { 11525 return false; 11526 } 11527 11528 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11529 EVT VT) const { 11530 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11531 return false; 11532 11533 switch (FPVT.getSimpleVT().SimpleTy) { 11534 case MVT::f16: 11535 return Subtarget.hasStdExtZfh(); 11536 case MVT::f32: 11537 return Subtarget.hasStdExtF(); 11538 case MVT::f64: 11539 return Subtarget.hasStdExtD(); 11540 default: 11541 return false; 11542 } 11543 } 11544 11545 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11546 // If we are using the small code model, we can reduce size of jump table 11547 // entry to 4 bytes. 11548 if (Subtarget.is64Bit() && !isPositionIndependent() && 11549 getTargetMachine().getCodeModel() == CodeModel::Small) { 11550 return MachineJumpTableInfo::EK_Custom32; 11551 } 11552 return TargetLowering::getJumpTableEncoding(); 11553 } 11554 11555 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 11556 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 11557 unsigned uid, MCContext &Ctx) const { 11558 assert(Subtarget.is64Bit() && !isPositionIndependent() && 11559 getTargetMachine().getCodeModel() == CodeModel::Small); 11560 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 11561 } 11562 11563 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 11564 EVT VT) const { 11565 VT = VT.getScalarType(); 11566 11567 if (!VT.isSimple()) 11568 return false; 11569 11570 switch (VT.getSimpleVT().SimpleTy) { 11571 case MVT::f16: 11572 return Subtarget.hasStdExtZfh(); 11573 case MVT::f32: 11574 return Subtarget.hasStdExtF(); 11575 case MVT::f64: 11576 return Subtarget.hasStdExtD(); 11577 default: 11578 break; 11579 } 11580 11581 return false; 11582 } 11583 11584 Register RISCVTargetLowering::getExceptionPointerRegister( 11585 const Constant *PersonalityFn) const { 11586 return RISCV::X10; 11587 } 11588 11589 Register RISCVTargetLowering::getExceptionSelectorRegister( 11590 const Constant *PersonalityFn) const { 11591 return RISCV::X11; 11592 } 11593 11594 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 11595 // Return false to suppress the unnecessary extensions if the LibCall 11596 // arguments or return value is f32 type for LP64 ABI. 11597 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 11598 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 11599 return false; 11600 11601 return true; 11602 } 11603 11604 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 11605 if (Subtarget.is64Bit() && Type == MVT::i32) 11606 return true; 11607 11608 return IsSigned; 11609 } 11610 11611 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 11612 SDValue C) const { 11613 // Check integral scalar types. 11614 if (VT.isScalarInteger()) { 11615 // Omit the optimization if the sub target has the M extension and the data 11616 // size exceeds XLen. 11617 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 11618 return false; 11619 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 11620 // Break the MUL to a SLLI and an ADD/SUB. 11621 const APInt &Imm = ConstNode->getAPIntValue(); 11622 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 11623 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 11624 return true; 11625 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 11626 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 11627 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 11628 (Imm - 8).isPowerOf2())) 11629 return true; 11630 // Omit the following optimization if the sub target has the M extension 11631 // and the data size >= XLen. 11632 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 11633 return false; 11634 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 11635 // a pair of LUI/ADDI. 11636 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 11637 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 11638 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 11639 (1 - ImmS).isPowerOf2()) 11640 return true; 11641 } 11642 } 11643 } 11644 11645 return false; 11646 } 11647 11648 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 11649 SDValue ConstNode) const { 11650 // Let the DAGCombiner decide for vectors. 11651 EVT VT = AddNode.getValueType(); 11652 if (VT.isVector()) 11653 return true; 11654 11655 // Let the DAGCombiner decide for larger types. 11656 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 11657 return true; 11658 11659 // It is worse if c1 is simm12 while c1*c2 is not. 11660 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 11661 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 11662 const APInt &C1 = C1Node->getAPIntValue(); 11663 const APInt &C2 = C2Node->getAPIntValue(); 11664 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 11665 return false; 11666 11667 // Default to true and let the DAGCombiner decide. 11668 return true; 11669 } 11670 11671 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 11672 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 11673 bool *Fast) const { 11674 if (!VT.isVector()) 11675 return false; 11676 11677 EVT ElemVT = VT.getVectorElementType(); 11678 if (Alignment >= ElemVT.getStoreSize()) { 11679 if (Fast) 11680 *Fast = true; 11681 return true; 11682 } 11683 11684 return false; 11685 } 11686 11687 bool RISCVTargetLowering::splitValueIntoRegisterParts( 11688 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 11689 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 11690 bool IsABIRegCopy = CC.hasValue(); 11691 EVT ValueVT = Val.getValueType(); 11692 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11693 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 11694 // and cast to f32. 11695 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 11696 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 11697 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 11698 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 11699 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 11700 Parts[0] = Val; 11701 return true; 11702 } 11703 11704 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11705 LLVMContext &Context = *DAG.getContext(); 11706 EVT ValueEltVT = ValueVT.getVectorElementType(); 11707 EVT PartEltVT = PartVT.getVectorElementType(); 11708 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11709 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11710 if (PartVTBitSize % ValueVTBitSize == 0) { 11711 assert(PartVTBitSize >= ValueVTBitSize); 11712 // If the element types are different, bitcast to the same element type of 11713 // PartVT first. 11714 // Give an example here, we want copy a <vscale x 1 x i8> value to 11715 // <vscale x 4 x i16>. 11716 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 11717 // subvector, then we can bitcast to <vscale x 4 x i16>. 11718 if (ValueEltVT != PartEltVT) { 11719 if (PartVTBitSize > ValueVTBitSize) { 11720 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11721 assert(Count != 0 && "The number of element should not be zero."); 11722 EVT SameEltTypeVT = 11723 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11724 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 11725 DAG.getUNDEF(SameEltTypeVT), Val, 11726 DAG.getVectorIdxConstant(0, DL)); 11727 } 11728 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 11729 } else { 11730 Val = 11731 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 11732 Val, DAG.getVectorIdxConstant(0, DL)); 11733 } 11734 Parts[0] = Val; 11735 return true; 11736 } 11737 } 11738 return false; 11739 } 11740 11741 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 11742 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 11743 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 11744 bool IsABIRegCopy = CC.hasValue(); 11745 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11746 SDValue Val = Parts[0]; 11747 11748 // Cast the f32 to i32, truncate to i16, and cast back to f16. 11749 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 11750 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 11751 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 11752 return Val; 11753 } 11754 11755 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11756 LLVMContext &Context = *DAG.getContext(); 11757 SDValue Val = Parts[0]; 11758 EVT ValueEltVT = ValueVT.getVectorElementType(); 11759 EVT PartEltVT = PartVT.getVectorElementType(); 11760 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11761 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11762 if (PartVTBitSize % ValueVTBitSize == 0) { 11763 assert(PartVTBitSize >= ValueVTBitSize); 11764 EVT SameEltTypeVT = ValueVT; 11765 // If the element types are different, convert it to the same element type 11766 // of PartVT. 11767 // Give an example here, we want copy a <vscale x 1 x i8> value from 11768 // <vscale x 4 x i16>. 11769 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 11770 // then we can extract <vscale x 1 x i8>. 11771 if (ValueEltVT != PartEltVT) { 11772 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11773 assert(Count != 0 && "The number of element should not be zero."); 11774 SameEltTypeVT = 11775 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11776 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 11777 } 11778 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 11779 DAG.getVectorIdxConstant(0, DL)); 11780 return Val; 11781 } 11782 } 11783 return SDValue(); 11784 } 11785 11786 SDValue 11787 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11788 SelectionDAG &DAG, 11789 SmallVectorImpl<SDNode *> &Created) const { 11790 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11791 if (isIntDivCheap(N->getValueType(0), Attr)) 11792 return SDValue(N, 0); // Lower SDIV as SDIV 11793 11794 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 11795 "Unexpected divisor!"); 11796 11797 // Conditional move is needed, so do the transformation iff Zbt is enabled. 11798 if (!Subtarget.hasStdExtZbt()) 11799 return SDValue(); 11800 11801 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 11802 // Besides, more critical path instructions will be generated when dividing 11803 // by 2. So we keep using the original DAGs for these cases. 11804 unsigned Lg2 = Divisor.countTrailingZeros(); 11805 if (Lg2 == 1 || Lg2 >= 12) 11806 return SDValue(); 11807 11808 // fold (sdiv X, pow2) 11809 EVT VT = N->getValueType(0); 11810 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 11811 return SDValue(); 11812 11813 SDLoc DL(N); 11814 SDValue N0 = N->getOperand(0); 11815 SDValue Zero = DAG.getConstant(0, DL, VT); 11816 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11817 11818 // Add (N0 < 0) ? Pow2 - 1 : 0; 11819 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 11820 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11821 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 11822 11823 Created.push_back(Cmp.getNode()); 11824 Created.push_back(Add.getNode()); 11825 Created.push_back(Sel.getNode()); 11826 11827 // Divide by pow2. 11828 SDValue SRA = 11829 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 11830 11831 // If we're dividing by a positive value, we're done. Otherwise, we must 11832 // negate the result. 11833 if (Divisor.isNonNegative()) 11834 return SRA; 11835 11836 Created.push_back(SRA.getNode()); 11837 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11838 } 11839 11840 #define GET_REGISTER_MATCHER 11841 #include "RISCVGenAsmMatcher.inc" 11842 11843 Register 11844 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 11845 const MachineFunction &MF) const { 11846 Register Reg = MatchRegisterAltName(RegName); 11847 if (Reg == RISCV::NoRegister) 11848 Reg = MatchRegisterName(RegName); 11849 if (Reg == RISCV::NoRegister) 11850 report_fatal_error( 11851 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 11852 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 11853 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 11854 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 11855 StringRef(RegName) + "\".")); 11856 return Reg; 11857 } 11858 11859 namespace llvm { 11860 namespace RISCVVIntrinsicsTable { 11861 11862 #define GET_RISCVVIntrinsicsTable_IMPL 11863 #include "RISCVGenSearchableTables.inc" 11864 11865 } // namespace RISCVVIntrinsicsTable 11866 11867 } // namespace llvm 11868