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 setCondCodeAction(FPCCToExpand, MVT::f16, Expand); 311 setOperationAction(ISD::SELECT_CC, MVT::f16, Expand); 312 setOperationAction(ISD::SELECT, MVT::f16, Custom); 313 setOperationAction(ISD::BR_CC, MVT::f16, Expand); 314 315 setOperationAction({ISD::FREM, ISD::FCEIL, ISD::FFLOOR, ISD::FNEARBYINT, 316 ISD::FRINT, ISD::FROUND, ISD::FROUNDEVEN, ISD::FTRUNC, 317 ISD::FPOW, ISD::FPOWI, ISD::FCOS, ISD::FSIN, 318 ISD::FSINCOS, ISD::FEXP, ISD::FEXP2, ISD::FLOG, 319 ISD::FLOG2, ISD::FLOG10}, 320 MVT::f16, Promote); 321 322 // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have 323 // complete support for all operations in LegalizeDAG. 324 325 // We need to custom promote this. 326 if (Subtarget.is64Bit()) 327 setOperationAction(ISD::FPOWI, MVT::i32, Custom); 328 } 329 330 if (Subtarget.hasStdExtF()) { 331 for (auto NT : FPLegalNodeTypes) 332 setOperationAction(NT, MVT::f32, Legal); 333 setCondCodeAction(FPCCToExpand, MVT::f32, Expand); 334 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand); 335 setOperationAction(ISD::SELECT, MVT::f32, Custom); 336 setOperationAction(ISD::BR_CC, MVT::f32, Expand); 337 for (auto Op : FPOpToExpand) 338 setOperationAction(Op, MVT::f32, Expand); 339 setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand); 340 setTruncStoreAction(MVT::f32, MVT::f16, Expand); 341 } 342 343 if (Subtarget.hasStdExtF() && Subtarget.is64Bit()) 344 setOperationAction(ISD::BITCAST, MVT::i32, Custom); 345 346 if (Subtarget.hasStdExtD()) { 347 for (auto NT : FPLegalNodeTypes) 348 setOperationAction(NT, MVT::f64, Legal); 349 setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal); 350 setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal); 351 setCondCodeAction(FPCCToExpand, MVT::f64, Expand); 352 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand); 353 setOperationAction(ISD::SELECT, MVT::f64, Custom); 354 setOperationAction(ISD::BR_CC, MVT::f64, Expand); 355 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand); 356 setTruncStoreAction(MVT::f64, MVT::f32, Expand); 357 for (auto Op : FPOpToExpand) 358 setOperationAction(Op, MVT::f64, Expand); 359 setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand); 360 setTruncStoreAction(MVT::f64, MVT::f16, Expand); 361 } 362 363 if (Subtarget.is64Bit()) 364 setOperationAction({ISD::FP_TO_UINT, ISD::FP_TO_SINT, 365 ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT}, 366 MVT::i32, Custom); 367 368 if (Subtarget.hasStdExtF()) { 369 setOperationAction({ISD::FP_TO_UINT_SAT, ISD::FP_TO_SINT_SAT}, XLenVT, 370 Custom); 371 372 setOperationAction({ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT, 373 ISD::STRICT_UINT_TO_FP, ISD::STRICT_SINT_TO_FP}, 374 XLenVT, Legal); 375 376 setOperationAction(ISD::FLT_ROUNDS_, XLenVT, Custom); 377 setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom); 378 } 379 380 setOperationAction({ISD::GlobalAddress, ISD::BlockAddress, ISD::ConstantPool, 381 ISD::JumpTable}, 382 XLenVT, Custom); 383 384 setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom); 385 386 // TODO: On M-mode only targets, the cycle[h] CSR may not be present. 387 // Unfortunately this can't be determined just from the ISA naming string. 388 setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, 389 Subtarget.is64Bit() ? Legal : Custom); 390 391 setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Legal); 392 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom); 393 if (Subtarget.is64Bit()) 394 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom); 395 396 if (Subtarget.hasStdExtA()) { 397 setMaxAtomicSizeInBitsSupported(Subtarget.getXLen()); 398 setMinCmpXchgSizeInBits(32); 399 } else { 400 setMaxAtomicSizeInBitsSupported(0); 401 } 402 403 setBooleanContents(ZeroOrOneBooleanContent); 404 405 if (Subtarget.hasVInstructions()) { 406 setBooleanVectorContents(ZeroOrOneBooleanContent); 407 408 setOperationAction(ISD::VSCALE, XLenVT, Custom); 409 410 // RVV intrinsics may have illegal operands. 411 // We also need to custom legalize vmv.x.s. 412 setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN}, 413 {MVT::i8, MVT::i16}, Custom); 414 if (Subtarget.is64Bit()) 415 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom); 416 else 417 setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN}, 418 MVT::i64, Custom); 419 420 setOperationAction({ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID}, 421 MVT::Other, Custom); 422 423 static const unsigned IntegerVPOps[] = { 424 ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL, 425 ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM, 426 ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR, 427 ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR, 428 ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 429 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX, 430 ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN, 431 ISD::VP_MERGE, ISD::VP_SELECT, ISD::VP_FPTOSI, 432 ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_SIGN_EXTEND, 433 ISD::VP_ZERO_EXTEND, ISD::VP_TRUNCATE}; 434 435 static const unsigned FloatingPointVPOps[] = { 436 ISD::VP_FADD, ISD::VP_FSUB, 437 ISD::VP_FMUL, ISD::VP_FDIV, 438 ISD::VP_FNEG, ISD::VP_FMA, 439 ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD, 440 ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, 441 ISD::VP_MERGE, ISD::VP_SELECT, 442 ISD::VP_SITOFP, ISD::VP_UITOFP, 443 ISD::VP_SETCC, ISD::VP_FP_ROUND, 444 ISD::VP_FP_EXTEND}; 445 446 if (!Subtarget.is64Bit()) { 447 // We must custom-lower certain vXi64 operations on RV32 due to the vector 448 // element type being illegal. 449 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 450 MVT::i64, Custom); 451 452 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, 453 ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR, 454 ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 455 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}, 456 MVT::i64, Custom); 457 458 setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND, 459 ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, 460 ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN, 461 ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN}, 462 MVT::i64, Custom); 463 } 464 465 for (MVT VT : BoolVecVTs) { 466 setOperationAction(ISD::SPLAT_VECTOR, VT, Custom); 467 468 // Mask VTs are custom-expanded into a series of standard nodes 469 setOperationAction({ISD::TRUNCATE, ISD::CONCAT_VECTORS, 470 ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 471 VT, Custom); 472 473 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 474 Custom); 475 476 setOperationAction(ISD::SELECT, VT, Custom); 477 setOperationAction( 478 {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT, 479 Expand); 480 481 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom); 482 483 setOperationAction( 484 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 485 Custom); 486 487 setOperationAction( 488 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 489 Custom); 490 491 // RVV has native int->float & float->int conversions where the 492 // element type sizes are within one power-of-two of each other. Any 493 // wider distances between type sizes have to be lowered as sequences 494 // which progressively narrow the gap in stages. 495 setOperationAction( 496 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 497 VT, Custom); 498 499 // Expand all extending loads to types larger than this, and truncating 500 // stores from types larger than this. 501 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 502 setTruncStoreAction(OtherVT, VT, Expand); 503 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 504 VT, Expand); 505 } 506 507 setOperationAction( 508 {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_TRUNCATE, ISD::VP_SETCC}, VT, 509 Custom); 510 } 511 512 for (MVT VT : IntVecVTs) { 513 if (VT.getVectorElementType() == MVT::i64 && 514 !Subtarget.hasVInstructionsI64()) 515 continue; 516 517 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 518 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 519 520 // Vectors implement MULHS/MULHU. 521 setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand); 522 523 // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*. 524 if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV()) 525 setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand); 526 527 setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT, 528 Legal); 529 530 setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand); 531 532 setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP, ISD::BSWAP}, VT, 533 Expand); 534 535 setOperationAction(ISD::BSWAP, VT, Expand); 536 537 // Custom-lower extensions and truncations from/to mask types. 538 setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, 539 VT, Custom); 540 541 // RVV has native int->float & float->int conversions where the 542 // element type sizes are within one power-of-two of each other. Any 543 // wider distances between type sizes have to be lowered as sequences 544 // which progressively narrow the gap in stages. 545 setOperationAction( 546 {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT}, 547 VT, Custom); 548 549 setOperationAction( 550 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal); 551 552 // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL" 553 // nodes which truncate by one power of two at a time. 554 setOperationAction(ISD::TRUNCATE, VT, Custom); 555 556 // Custom-lower insert/extract operations to simplify patterns. 557 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 558 Custom); 559 560 // Custom-lower reduction operations to set up the corresponding custom 561 // nodes' operands. 562 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, 563 ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR, 564 ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN, 565 ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN}, 566 VT, Custom); 567 568 setOperationAction(IntegerVPOps, VT, Custom); 569 570 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 571 572 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 573 VT, Custom); 574 575 setOperationAction( 576 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 577 Custom); 578 579 setOperationAction( 580 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 581 VT, Custom); 582 583 setOperationAction(ISD::SELECT, VT, Custom); 584 setOperationAction(ISD::SELECT_CC, VT, Expand); 585 586 setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom); 587 588 for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) { 589 setTruncStoreAction(VT, OtherVT, Expand); 590 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT, 591 VT, Expand); 592 } 593 594 // Splice 595 setOperationAction(ISD::VECTOR_SPLICE, VT, Custom); 596 597 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 598 // type that can represent the value exactly. 599 if (VT.getVectorElementType() != MVT::i64) { 600 MVT FloatEltVT = 601 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 602 EVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 603 if (isTypeLegal(FloatVT)) { 604 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 605 Custom); 606 } 607 } 608 } 609 610 // Expand various CCs to best match the RVV ISA, which natively supports UNE 611 // but no other unordered comparisons, and supports all ordered comparisons 612 // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization 613 // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE), 614 // and we pattern-match those back to the "original", swapping operands once 615 // more. This way we catch both operations and both "vf" and "fv" forms with 616 // fewer patterns. 617 static const ISD::CondCode VFPCCToExpand[] = { 618 ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT, 619 ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO, 620 ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE, 621 }; 622 623 // Sets common operation actions on RVV floating-point vector types. 624 const auto SetCommonVFPActions = [&](MVT VT) { 625 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 626 // RVV has native FP_ROUND & FP_EXTEND conversions where the element type 627 // sizes are within one power-of-two of each other. Therefore conversions 628 // between vXf16 and vXf64 must be lowered as sequences which convert via 629 // vXf32. 630 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 631 // Custom-lower insert/extract operations to simplify patterns. 632 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT, 633 Custom); 634 // Expand various condition codes (explained above). 635 setCondCodeAction(VFPCCToExpand, VT, Expand); 636 637 setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal); 638 639 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 640 VT, Custom); 641 642 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 643 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 644 VT, Custom); 645 646 setOperationAction(ISD::FCOPYSIGN, VT, Legal); 647 648 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 649 650 setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, 651 VT, Custom); 652 653 setOperationAction( 654 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 655 Custom); 656 657 setOperationAction(ISD::SELECT, VT, Custom); 658 setOperationAction(ISD::SELECT_CC, VT, Expand); 659 660 setOperationAction( 661 {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, 662 VT, Custom); 663 664 setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom); 665 666 setOperationAction(FloatingPointVPOps, VT, Custom); 667 }; 668 669 // Sets common extload/truncstore actions on RVV floating-point vector 670 // types. 671 const auto SetCommonVFPExtLoadTruncStoreActions = 672 [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) { 673 for (auto SmallVT : SmallerVTs) { 674 setTruncStoreAction(VT, SmallVT, Expand); 675 setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand); 676 } 677 }; 678 679 if (Subtarget.hasVInstructionsF16()) 680 for (MVT VT : F16VecVTs) 681 SetCommonVFPActions(VT); 682 683 for (MVT VT : F32VecVTs) { 684 if (Subtarget.hasVInstructionsF32()) 685 SetCommonVFPActions(VT); 686 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 687 } 688 689 for (MVT VT : F64VecVTs) { 690 if (Subtarget.hasVInstructionsF64()) 691 SetCommonVFPActions(VT); 692 SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs); 693 SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs); 694 } 695 696 if (Subtarget.useRVVForFixedLengthVectors()) { 697 for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) { 698 if (!useRVVForFixedLengthVectorVT(VT)) 699 continue; 700 701 // By default everything must be expanded. 702 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 703 setOperationAction(Op, VT, Expand); 704 for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) { 705 setTruncStoreAction(VT, OtherVT, Expand); 706 setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, 707 OtherVT, VT, Expand); 708 } 709 710 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 711 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 712 Custom); 713 714 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT, 715 Custom); 716 717 setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, 718 VT, Custom); 719 720 setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom); 721 722 setOperationAction(ISD::SETCC, VT, Custom); 723 724 setOperationAction(ISD::SELECT, VT, Custom); 725 726 setOperationAction(ISD::TRUNCATE, VT, Custom); 727 728 setOperationAction(ISD::BITCAST, VT, Custom); 729 730 setOperationAction( 731 {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT, 732 Custom); 733 734 setOperationAction( 735 {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT, 736 Custom); 737 738 setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, 739 ISD::FP_TO_UINT}, 740 VT, Custom); 741 742 // Operations below are different for between masks and other vectors. 743 if (VT.getVectorElementType() == MVT::i1) { 744 setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND, 745 ISD::OR, ISD::XOR}, 746 VT, Custom); 747 748 setOperationAction( 749 {ISD::VP_FPTOSI, ISD::VP_FPTOUI, ISD::VP_SETCC, ISD::VP_TRUNCATE}, 750 VT, Custom); 751 continue; 752 } 753 754 // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to 755 // it before type legalization for i64 vectors on RV32. It will then be 756 // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle. 757 // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs 758 // improvements first. 759 if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) { 760 setOperationAction(ISD::SPLAT_VECTOR, VT, Legal); 761 setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom); 762 } 763 764 setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom); 765 setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom); 766 767 setOperationAction( 768 {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom); 769 770 setOperationAction( 771 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 772 Custom); 773 774 setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR, 775 ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV, 776 ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL}, 777 VT, Custom); 778 779 setOperationAction( 780 {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom); 781 782 // vXi64 MULHS/MULHU requires the V extension instead of Zve64*. 783 if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV()) 784 setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom); 785 786 setOperationAction( 787 {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, 788 Custom); 789 790 setOperationAction(ISD::VSELECT, VT, Custom); 791 setOperationAction(ISD::SELECT_CC, VT, Expand); 792 793 setOperationAction( 794 {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom); 795 796 // Custom-lower reduction operations to set up the corresponding custom 797 // nodes' operands. 798 setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX, 799 ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX, 800 ISD::VECREDUCE_UMIN}, 801 VT, Custom); 802 803 setOperationAction(IntegerVPOps, VT, Custom); 804 805 // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if we have a floating point 806 // type that can represent the value exactly. 807 if (VT.getVectorElementType() != MVT::i64) { 808 MVT FloatEltVT = 809 VT.getVectorElementType() == MVT::i32 ? MVT::f64 : MVT::f32; 810 EVT FloatVT = 811 MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 812 if (isTypeLegal(FloatVT)) 813 setOperationAction({ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT, 814 Custom); 815 } 816 } 817 818 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) { 819 if (!useRVVForFixedLengthVectorVT(VT)) 820 continue; 821 822 // By default everything must be expanded. 823 for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) 824 setOperationAction(Op, VT, Expand); 825 for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) { 826 setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand); 827 setTruncStoreAction(VT, OtherVT, Expand); 828 } 829 830 // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed. 831 setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT, 832 Custom); 833 834 setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS, 835 ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT, 836 ISD::EXTRACT_VECTOR_ELT}, 837 VT, Custom); 838 839 setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE, 840 ISD::MGATHER, ISD::MSCATTER}, 841 VT, Custom); 842 843 setOperationAction( 844 {ISD::VP_LOAD, ISD::VP_STORE, ISD::VP_GATHER, ISD::VP_SCATTER}, VT, 845 Custom); 846 847 setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV, 848 ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT, 849 ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM}, 850 VT, Custom); 851 852 setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom); 853 854 setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND}, 855 VT, Custom); 856 857 for (auto CC : VFPCCToExpand) 858 setCondCodeAction(CC, VT, Expand); 859 860 setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom); 861 setOperationAction(ISD::SELECT_CC, VT, Expand); 862 863 setOperationAction(ISD::BITCAST, VT, Custom); 864 865 setOperationAction({ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, 866 ISD::VECREDUCE_FMIN, ISD::VECREDUCE_FMAX}, 867 VT, Custom); 868 869 setOperationAction(FloatingPointVPOps, VT, Custom); 870 } 871 872 // Custom-legalize bitcasts from fixed-length vectors to scalar types. 873 setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64}, 874 Custom); 875 if (Subtarget.hasStdExtZfh()) 876 setOperationAction(ISD::BITCAST, MVT::f16, Custom); 877 if (Subtarget.hasStdExtF()) 878 setOperationAction(ISD::BITCAST, MVT::f32, Custom); 879 if (Subtarget.hasStdExtD()) 880 setOperationAction(ISD::BITCAST, MVT::f64, Custom); 881 } 882 } 883 884 // Function alignments. 885 const Align FunctionAlignment(Subtarget.hasStdExtC() ? 2 : 4); 886 setMinFunctionAlignment(FunctionAlignment); 887 setPrefFunctionAlignment(FunctionAlignment); 888 889 setMinimumJumpTableEntries(5); 890 891 // Jumps are expensive, compared to logic 892 setJumpIsExpensive(); 893 894 setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND, 895 ISD::OR, ISD::XOR}); 896 897 if (Subtarget.hasStdExtF()) 898 setTargetDAGCombine({ISD::FADD, ISD::FMAXNUM, ISD::FMINNUM}); 899 900 if (Subtarget.hasStdExtZbp()) 901 setTargetDAGCombine({ISD::ROTL, ISD::ROTR}); 902 903 if (Subtarget.hasStdExtZbb()) 904 setTargetDAGCombine({ISD::UMAX, ISD::UMIN, ISD::SMAX, ISD::SMIN}); 905 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 // RVV instructions only support register addressing. 1011 if (Subtarget.hasVInstructions() && isa<VectorType>(Ty)) 1012 return AM.HasBaseReg && AM.Scale == 0 && !AM.BaseOffs; 1013 1014 // Require a 12-bit signed offset. 1015 if (!isInt<12>(AM.BaseOffs)) 1016 return false; 1017 1018 switch (AM.Scale) { 1019 case 0: // "r+i" or just "i", depending on HasBaseReg. 1020 break; 1021 case 1: 1022 if (!AM.HasBaseReg) // allow "r+i". 1023 break; 1024 return false; // disallow "r+r" or "r+r+i". 1025 default: 1026 return false; 1027 } 1028 1029 return true; 1030 } 1031 1032 bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const { 1033 return isInt<12>(Imm); 1034 } 1035 1036 bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const { 1037 return isInt<12>(Imm); 1038 } 1039 1040 // On RV32, 64-bit integers are split into their high and low parts and held 1041 // in two different registers, so the trunc is free since the low register can 1042 // just be used. 1043 bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const { 1044 if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy()) 1045 return false; 1046 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits(); 1047 unsigned DestBits = DstTy->getPrimitiveSizeInBits(); 1048 return (SrcBits == 64 && DestBits == 32); 1049 } 1050 1051 bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const { 1052 if (Subtarget.is64Bit() || SrcVT.isVector() || DstVT.isVector() || 1053 !SrcVT.isInteger() || !DstVT.isInteger()) 1054 return false; 1055 unsigned SrcBits = SrcVT.getSizeInBits(); 1056 unsigned DestBits = DstVT.getSizeInBits(); 1057 return (SrcBits == 64 && DestBits == 32); 1058 } 1059 1060 bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const { 1061 // Zexts are free if they can be combined with a load. 1062 // Don't advertise i32->i64 zextload as being free for RV64. It interacts 1063 // poorly with type legalization of compares preferring sext. 1064 if (auto *LD = dyn_cast<LoadSDNode>(Val)) { 1065 EVT MemVT = LD->getMemoryVT(); 1066 if ((MemVT == MVT::i8 || MemVT == MVT::i16) && 1067 (LD->getExtensionType() == ISD::NON_EXTLOAD || 1068 LD->getExtensionType() == ISD::ZEXTLOAD)) 1069 return true; 1070 } 1071 1072 return TargetLowering::isZExtFree(Val, VT2); 1073 } 1074 1075 bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const { 1076 return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64; 1077 } 1078 1079 bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const { 1080 return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32); 1081 } 1082 1083 bool RISCVTargetLowering::isCheapToSpeculateCttz() const { 1084 return Subtarget.hasStdExtZbb(); 1085 } 1086 1087 bool RISCVTargetLowering::isCheapToSpeculateCtlz() const { 1088 return Subtarget.hasStdExtZbb(); 1089 } 1090 1091 bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const { 1092 EVT VT = Y.getValueType(); 1093 1094 // FIXME: Support vectors once we have tests. 1095 if (VT.isVector()) 1096 return false; 1097 1098 return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp() || 1099 Subtarget.hasStdExtZbkb()) && 1100 !isa<ConstantSDNode>(Y); 1101 } 1102 1103 bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const { 1104 // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position. 1105 auto *C = dyn_cast<ConstantSDNode>(Y); 1106 return C && C->getAPIntValue().ule(10); 1107 } 1108 1109 bool RISCVTargetLowering:: 1110 shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd( 1111 SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y, 1112 unsigned OldShiftOpcode, unsigned NewShiftOpcode, 1113 SelectionDAG &DAG) const { 1114 // One interesting pattern that we'd want to form is 'bit extract': 1115 // ((1 >> Y) & 1) ==/!= 0 1116 // But we also need to be careful not to try to reverse that fold. 1117 1118 // Is this '((1 >> Y) & 1)'? 1119 if (XC && OldShiftOpcode == ISD::SRL && XC->isOne()) 1120 return false; // Keep the 'bit extract' pattern. 1121 1122 // Will this be '((1 >> Y) & 1)' after the transform? 1123 if (NewShiftOpcode == ISD::SRL && CC->isOne()) 1124 return true; // Do form the 'bit extract' pattern. 1125 1126 // If 'X' is a constant, and we transform, then we will immediately 1127 // try to undo the fold, thus causing endless combine loop. 1128 // So only do the transform if X is not a constant. This matches the default 1129 // implementation of this function. 1130 return !XC; 1131 } 1132 1133 /// Check if sinking \p I's operands to I's basic block is profitable, because 1134 /// the operands can be folded into a target instruction, e.g. 1135 /// splats of scalars can fold into vector instructions. 1136 bool RISCVTargetLowering::shouldSinkOperands( 1137 Instruction *I, SmallVectorImpl<Use *> &Ops) const { 1138 using namespace llvm::PatternMatch; 1139 1140 if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions()) 1141 return false; 1142 1143 auto IsSinker = [&](Instruction *I, int Operand) { 1144 switch (I->getOpcode()) { 1145 case Instruction::Add: 1146 case Instruction::Sub: 1147 case Instruction::Mul: 1148 case Instruction::And: 1149 case Instruction::Or: 1150 case Instruction::Xor: 1151 case Instruction::FAdd: 1152 case Instruction::FSub: 1153 case Instruction::FMul: 1154 case Instruction::FDiv: 1155 case Instruction::ICmp: 1156 case Instruction::FCmp: 1157 return true; 1158 case Instruction::Shl: 1159 case Instruction::LShr: 1160 case Instruction::AShr: 1161 case Instruction::UDiv: 1162 case Instruction::SDiv: 1163 case Instruction::URem: 1164 case Instruction::SRem: 1165 return Operand == 1; 1166 case Instruction::Call: 1167 if (auto *II = dyn_cast<IntrinsicInst>(I)) { 1168 switch (II->getIntrinsicID()) { 1169 case Intrinsic::fma: 1170 case Intrinsic::vp_fma: 1171 return Operand == 0 || Operand == 1; 1172 // FIXME: Our patterns can only match vx/vf instructions when the splat 1173 // it on the RHS, because TableGen doesn't recognize our VP operations 1174 // as commutative. 1175 case Intrinsic::vp_add: 1176 case Intrinsic::vp_mul: 1177 case Intrinsic::vp_and: 1178 case Intrinsic::vp_or: 1179 case Intrinsic::vp_xor: 1180 case Intrinsic::vp_fadd: 1181 case Intrinsic::vp_fmul: 1182 case Intrinsic::vp_shl: 1183 case Intrinsic::vp_lshr: 1184 case Intrinsic::vp_ashr: 1185 case Intrinsic::vp_udiv: 1186 case Intrinsic::vp_sdiv: 1187 case Intrinsic::vp_urem: 1188 case Intrinsic::vp_srem: 1189 return Operand == 1; 1190 // ... with the exception of vp.sub/vp.fsub/vp.fdiv, which have 1191 // explicit patterns for both LHS and RHS (as 'vr' versions). 1192 case Intrinsic::vp_sub: 1193 case Intrinsic::vp_fsub: 1194 case Intrinsic::vp_fdiv: 1195 return Operand == 0 || Operand == 1; 1196 default: 1197 return false; 1198 } 1199 } 1200 return false; 1201 default: 1202 return false; 1203 } 1204 }; 1205 1206 for (auto OpIdx : enumerate(I->operands())) { 1207 if (!IsSinker(I, OpIdx.index())) 1208 continue; 1209 1210 Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get()); 1211 // Make sure we are not already sinking this operand 1212 if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; })) 1213 continue; 1214 1215 // We are looking for a splat that can be sunk. 1216 if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()), 1217 m_Undef(), m_ZeroMask()))) 1218 continue; 1219 1220 // All uses of the shuffle should be sunk to avoid duplicating it across gpr 1221 // and vector registers 1222 for (Use &U : Op->uses()) { 1223 Instruction *Insn = cast<Instruction>(U.getUser()); 1224 if (!IsSinker(Insn, U.getOperandNo())) 1225 return false; 1226 } 1227 1228 Ops.push_back(&Op->getOperandUse(0)); 1229 Ops.push_back(&OpIdx.value()); 1230 } 1231 return true; 1232 } 1233 1234 bool RISCVTargetLowering::isOffsetFoldingLegal( 1235 const GlobalAddressSDNode *GA) const { 1236 // In order to maximise the opportunity for common subexpression elimination, 1237 // keep a separate ADD node for the global address offset instead of folding 1238 // it in the global address node. Later peephole optimisations may choose to 1239 // fold it back in when profitable. 1240 return false; 1241 } 1242 1243 bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT, 1244 bool ForCodeSize) const { 1245 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1246 if (VT == MVT::f16 && !Subtarget.hasStdExtZfh()) 1247 return false; 1248 if (VT == MVT::f32 && !Subtarget.hasStdExtF()) 1249 return false; 1250 if (VT == MVT::f64 && !Subtarget.hasStdExtD()) 1251 return false; 1252 return Imm.isZero(); 1253 } 1254 1255 bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const { 1256 return (VT == MVT::f16 && Subtarget.hasStdExtZfh()) || 1257 (VT == MVT::f32 && Subtarget.hasStdExtF()) || 1258 (VT == MVT::f64 && Subtarget.hasStdExtD()); 1259 } 1260 1261 MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context, 1262 CallingConv::ID CC, 1263 EVT VT) const { 1264 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1265 // We might still end up using a GPR but that will be decided based on ABI. 1266 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1267 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1268 return MVT::f32; 1269 1270 return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT); 1271 } 1272 1273 unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context, 1274 CallingConv::ID CC, 1275 EVT VT) const { 1276 // Use f32 to pass f16 if it is legal and Zfh is not enabled. 1277 // We might still end up using a GPR but that will be decided based on ABI. 1278 // FIXME: Change to Zfhmin once f16 becomes a legal type with Zfhmin. 1279 if (VT == MVT::f16 && Subtarget.hasStdExtF() && !Subtarget.hasStdExtZfh()) 1280 return 1; 1281 1282 return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT); 1283 } 1284 1285 // Changes the condition code and swaps operands if necessary, so the SetCC 1286 // operation matches one of the comparisons supported directly by branches 1287 // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare 1288 // with 1/-1. 1289 static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS, 1290 ISD::CondCode &CC, SelectionDAG &DAG) { 1291 // Convert X > -1 to X >= 0. 1292 if (CC == ISD::SETGT && isAllOnesConstant(RHS)) { 1293 RHS = DAG.getConstant(0, DL, RHS.getValueType()); 1294 CC = ISD::SETGE; 1295 return; 1296 } 1297 // Convert X < 1 to 0 >= X. 1298 if (CC == ISD::SETLT && isOneConstant(RHS)) { 1299 RHS = LHS; 1300 LHS = DAG.getConstant(0, DL, RHS.getValueType()); 1301 CC = ISD::SETGE; 1302 return; 1303 } 1304 1305 switch (CC) { 1306 default: 1307 break; 1308 case ISD::SETGT: 1309 case ISD::SETLE: 1310 case ISD::SETUGT: 1311 case ISD::SETULE: 1312 CC = ISD::getSetCCSwappedOperands(CC); 1313 std::swap(LHS, RHS); 1314 break; 1315 } 1316 } 1317 1318 RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) { 1319 assert(VT.isScalableVector() && "Expecting a scalable vector type"); 1320 unsigned KnownSize = VT.getSizeInBits().getKnownMinValue(); 1321 if (VT.getVectorElementType() == MVT::i1) 1322 KnownSize *= 8; 1323 1324 switch (KnownSize) { 1325 default: 1326 llvm_unreachable("Invalid LMUL."); 1327 case 8: 1328 return RISCVII::VLMUL::LMUL_F8; 1329 case 16: 1330 return RISCVII::VLMUL::LMUL_F4; 1331 case 32: 1332 return RISCVII::VLMUL::LMUL_F2; 1333 case 64: 1334 return RISCVII::VLMUL::LMUL_1; 1335 case 128: 1336 return RISCVII::VLMUL::LMUL_2; 1337 case 256: 1338 return RISCVII::VLMUL::LMUL_4; 1339 case 512: 1340 return RISCVII::VLMUL::LMUL_8; 1341 } 1342 } 1343 1344 unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) { 1345 switch (LMul) { 1346 default: 1347 llvm_unreachable("Invalid LMUL."); 1348 case RISCVII::VLMUL::LMUL_F8: 1349 case RISCVII::VLMUL::LMUL_F4: 1350 case RISCVII::VLMUL::LMUL_F2: 1351 case RISCVII::VLMUL::LMUL_1: 1352 return RISCV::VRRegClassID; 1353 case RISCVII::VLMUL::LMUL_2: 1354 return RISCV::VRM2RegClassID; 1355 case RISCVII::VLMUL::LMUL_4: 1356 return RISCV::VRM4RegClassID; 1357 case RISCVII::VLMUL::LMUL_8: 1358 return RISCV::VRM8RegClassID; 1359 } 1360 } 1361 1362 unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) { 1363 RISCVII::VLMUL LMUL = getLMUL(VT); 1364 if (LMUL == RISCVII::VLMUL::LMUL_F8 || 1365 LMUL == RISCVII::VLMUL::LMUL_F4 || 1366 LMUL == RISCVII::VLMUL::LMUL_F2 || 1367 LMUL == RISCVII::VLMUL::LMUL_1) { 1368 static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7, 1369 "Unexpected subreg numbering"); 1370 return RISCV::sub_vrm1_0 + Index; 1371 } 1372 if (LMUL == RISCVII::VLMUL::LMUL_2) { 1373 static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3, 1374 "Unexpected subreg numbering"); 1375 return RISCV::sub_vrm2_0 + Index; 1376 } 1377 if (LMUL == RISCVII::VLMUL::LMUL_4) { 1378 static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1, 1379 "Unexpected subreg numbering"); 1380 return RISCV::sub_vrm4_0 + Index; 1381 } 1382 llvm_unreachable("Invalid vector type."); 1383 } 1384 1385 unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) { 1386 if (VT.getVectorElementType() == MVT::i1) 1387 return RISCV::VRRegClassID; 1388 return getRegClassIDForLMUL(getLMUL(VT)); 1389 } 1390 1391 // Attempt to decompose a subvector insert/extract between VecVT and 1392 // SubVecVT via subregister indices. Returns the subregister index that 1393 // can perform the subvector insert/extract with the given element index, as 1394 // well as the index corresponding to any leftover subvectors that must be 1395 // further inserted/extracted within the register class for SubVecVT. 1396 std::pair<unsigned, unsigned> 1397 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 1398 MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx, 1399 const RISCVRegisterInfo *TRI) { 1400 static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID && 1401 RISCV::VRM4RegClassID > RISCV::VRM2RegClassID && 1402 RISCV::VRM2RegClassID > RISCV::VRRegClassID), 1403 "Register classes not ordered"); 1404 unsigned VecRegClassID = getRegClassIDForVecVT(VecVT); 1405 unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT); 1406 // Try to compose a subregister index that takes us from the incoming 1407 // LMUL>1 register class down to the outgoing one. At each step we half 1408 // the LMUL: 1409 // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0 1410 // Note that this is not guaranteed to find a subregister index, such as 1411 // when we are extracting from one VR type to another. 1412 unsigned SubRegIdx = RISCV::NoSubRegister; 1413 for (const unsigned RCID : 1414 {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID}) 1415 if (VecRegClassID > RCID && SubRegClassID <= RCID) { 1416 VecVT = VecVT.getHalfNumVectorElementsVT(); 1417 bool IsHi = 1418 InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue(); 1419 SubRegIdx = TRI->composeSubRegIndices(SubRegIdx, 1420 getSubregIndexByMVT(VecVT, IsHi)); 1421 if (IsHi) 1422 InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue(); 1423 } 1424 return {SubRegIdx, InsertExtractIdx}; 1425 } 1426 1427 // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar 1428 // stores for those types. 1429 bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const { 1430 return !Subtarget.useRVVForFixedLengthVectors() || 1431 (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1); 1432 } 1433 1434 bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const { 1435 if (ScalarTy->isPointerTy()) 1436 return true; 1437 1438 if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) || 1439 ScalarTy->isIntegerTy(32)) 1440 return true; 1441 1442 if (ScalarTy->isIntegerTy(64)) 1443 return Subtarget.hasVInstructionsI64(); 1444 1445 if (ScalarTy->isHalfTy()) 1446 return Subtarget.hasVInstructionsF16(); 1447 if (ScalarTy->isFloatTy()) 1448 return Subtarget.hasVInstructionsF32(); 1449 if (ScalarTy->isDoubleTy()) 1450 return Subtarget.hasVInstructionsF64(); 1451 1452 return false; 1453 } 1454 1455 static SDValue getVLOperand(SDValue Op) { 1456 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 1457 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 1458 "Unexpected opcode"); 1459 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 1460 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 1461 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 1462 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 1463 if (!II) 1464 return SDValue(); 1465 return Op.getOperand(II->VLOperand + 1 + HasChain); 1466 } 1467 1468 static bool useRVVForFixedLengthVectorVT(MVT VT, 1469 const RISCVSubtarget &Subtarget) { 1470 assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!"); 1471 if (!Subtarget.useRVVForFixedLengthVectors()) 1472 return false; 1473 1474 // We only support a set of vector types with a consistent maximum fixed size 1475 // across all supported vector element types to avoid legalization issues. 1476 // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest 1477 // fixed-length vector type we support is 1024 bytes. 1478 if (VT.getFixedSizeInBits() > 1024 * 8) 1479 return false; 1480 1481 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1482 1483 MVT EltVT = VT.getVectorElementType(); 1484 1485 // Don't use RVV for vectors we cannot scalarize if required. 1486 switch (EltVT.SimpleTy) { 1487 // i1 is supported but has different rules. 1488 default: 1489 return false; 1490 case MVT::i1: 1491 // Masks can only use a single register. 1492 if (VT.getVectorNumElements() > MinVLen) 1493 return false; 1494 MinVLen /= 8; 1495 break; 1496 case MVT::i8: 1497 case MVT::i16: 1498 case MVT::i32: 1499 break; 1500 case MVT::i64: 1501 if (!Subtarget.hasVInstructionsI64()) 1502 return false; 1503 break; 1504 case MVT::f16: 1505 if (!Subtarget.hasVInstructionsF16()) 1506 return false; 1507 break; 1508 case MVT::f32: 1509 if (!Subtarget.hasVInstructionsF32()) 1510 return false; 1511 break; 1512 case MVT::f64: 1513 if (!Subtarget.hasVInstructionsF64()) 1514 return false; 1515 break; 1516 } 1517 1518 // Reject elements larger than ELEN. 1519 if (EltVT.getSizeInBits() > Subtarget.getELEN()) 1520 return false; 1521 1522 unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen); 1523 // Don't use RVV for types that don't fit. 1524 if (LMul > Subtarget.getMaxLMULForFixedLengthVectors()) 1525 return false; 1526 1527 // TODO: Perhaps an artificial restriction, but worth having whilst getting 1528 // the base fixed length RVV support in place. 1529 if (!VT.isPow2VectorType()) 1530 return false; 1531 1532 return true; 1533 } 1534 1535 bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const { 1536 return ::useRVVForFixedLengthVectorVT(VT, Subtarget); 1537 } 1538 1539 // Return the largest legal scalable vector type that matches VT's element type. 1540 static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT, 1541 const RISCVSubtarget &Subtarget) { 1542 // This may be called before legal types are setup. 1543 assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) || 1544 useRVVForFixedLengthVectorVT(VT, Subtarget)) && 1545 "Expected legal fixed length vector!"); 1546 1547 unsigned MinVLen = Subtarget.getMinRVVVectorSizeInBits(); 1548 unsigned MaxELen = Subtarget.getELEN(); 1549 1550 MVT EltVT = VT.getVectorElementType(); 1551 switch (EltVT.SimpleTy) { 1552 default: 1553 llvm_unreachable("unexpected element type for RVV container"); 1554 case MVT::i1: 1555 case MVT::i8: 1556 case MVT::i16: 1557 case MVT::i32: 1558 case MVT::i64: 1559 case MVT::f16: 1560 case MVT::f32: 1561 case MVT::f64: { 1562 // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for 1563 // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within 1564 // each fractional LMUL we support SEW between 8 and LMUL*ELEN. 1565 unsigned NumElts = 1566 (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen; 1567 NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen); 1568 assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts"); 1569 return MVT::getScalableVectorVT(EltVT, NumElts); 1570 } 1571 } 1572 } 1573 1574 static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT, 1575 const RISCVSubtarget &Subtarget) { 1576 return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT, 1577 Subtarget); 1578 } 1579 1580 MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const { 1581 return ::getContainerForFixedLengthVector(*this, VT, getSubtarget()); 1582 } 1583 1584 // Grow V to consume an entire RVV register. 1585 static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1586 const RISCVSubtarget &Subtarget) { 1587 assert(VT.isScalableVector() && 1588 "Expected to convert into a scalable vector!"); 1589 assert(V.getValueType().isFixedLengthVector() && 1590 "Expected a fixed length vector operand!"); 1591 SDLoc DL(V); 1592 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1593 return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero); 1594 } 1595 1596 // Shrink V so it's just big enough to maintain a VT's worth of data. 1597 static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG, 1598 const RISCVSubtarget &Subtarget) { 1599 assert(VT.isFixedLengthVector() && 1600 "Expected to convert into a fixed length vector!"); 1601 assert(V.getValueType().isScalableVector() && 1602 "Expected a scalable vector operand!"); 1603 SDLoc DL(V); 1604 SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 1605 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero); 1606 } 1607 1608 /// Return the type of the mask type suitable for masking the provided 1609 /// vector type. This is simply an i1 element type vector of the same 1610 /// (possibly scalable) length. 1611 static MVT getMaskTypeFor(EVT VecVT) { 1612 assert(VecVT.isVector()); 1613 ElementCount EC = VecVT.getVectorElementCount(); 1614 return MVT::getVectorVT(MVT::i1, EC); 1615 } 1616 1617 /// Creates an all ones mask suitable for masking a vector of type VecTy with 1618 /// vector length VL. . 1619 static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL, 1620 SelectionDAG &DAG) { 1621 MVT MaskVT = getMaskTypeFor(VecVT); 1622 return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL); 1623 } 1624 1625 // Gets the two common "VL" operands: an all-ones mask and the vector length. 1626 // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is 1627 // the vector type that it is contained in. 1628 static std::pair<SDValue, SDValue> 1629 getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG, 1630 const RISCVSubtarget &Subtarget) { 1631 assert(ContainerVT.isScalableVector() && "Expecting scalable container type"); 1632 MVT XLenVT = Subtarget.getXLenVT(); 1633 SDValue VL = VecVT.isFixedLengthVector() 1634 ? DAG.getConstant(VecVT.getVectorNumElements(), DL, XLenVT) 1635 : DAG.getRegister(RISCV::X0, XLenVT); 1636 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 1637 return {Mask, VL}; 1638 } 1639 1640 // As above but assuming the given type is a scalable vector type. 1641 static std::pair<SDValue, SDValue> 1642 getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG, 1643 const RISCVSubtarget &Subtarget) { 1644 assert(VecVT.isScalableVector() && "Expecting a scalable vector"); 1645 return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget); 1646 } 1647 1648 // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few 1649 // of either is (currently) supported. This can get us into an infinite loop 1650 // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR 1651 // as a ..., etc. 1652 // Until either (or both) of these can reliably lower any node, reporting that 1653 // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks 1654 // the infinite loop. Note that this lowers BUILD_VECTOR through the stack, 1655 // which is not desirable. 1656 bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles( 1657 EVT VT, unsigned DefinedValues) const { 1658 return false; 1659 } 1660 1661 static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG, 1662 const RISCVSubtarget &Subtarget) { 1663 // RISCV FP-to-int conversions saturate to the destination register size, but 1664 // don't produce 0 for nan. We can use a conversion instruction and fix the 1665 // nan case with a compare and a select. 1666 SDValue Src = Op.getOperand(0); 1667 1668 EVT DstVT = Op.getValueType(); 1669 EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT(); 1670 1671 bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT; 1672 unsigned Opc; 1673 if (SatVT == DstVT) 1674 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 1675 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 1676 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 1677 else 1678 return SDValue(); 1679 // FIXME: Support other SatVTs by clamping before or after the conversion. 1680 1681 SDLoc DL(Op); 1682 SDValue FpToInt = DAG.getNode( 1683 Opc, DL, DstVT, Src, 1684 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT())); 1685 1686 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 1687 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 1688 } 1689 1690 // Expand vector FTRUNC, FCEIL, and FFLOOR by converting to the integer domain 1691 // and back. Taking care to avoid converting values that are nan or already 1692 // correct. 1693 // TODO: Floor and ceil could be shorter by changing rounding mode, but we don't 1694 // have FRM dependencies modeled yet. 1695 static SDValue lowerFTRUNC_FCEIL_FFLOOR(SDValue Op, SelectionDAG &DAG) { 1696 MVT VT = Op.getSimpleValueType(); 1697 assert(VT.isVector() && "Unexpected type"); 1698 1699 SDLoc DL(Op); 1700 1701 // Freeze the source since we are increasing the number of uses. 1702 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1703 1704 // Truncate to integer and convert back to FP. 1705 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1706 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Src); 1707 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1708 1709 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1710 1711 if (Op.getOpcode() == ISD::FCEIL) { 1712 // If the truncated value is the greater than or equal to the original 1713 // value, we've computed the ceil. Otherwise, we went the wrong way and 1714 // need to increase by 1. 1715 // FIXME: This should use a masked operation. Handle here or in isel? 1716 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Truncated, 1717 DAG.getConstantFP(1.0, DL, VT)); 1718 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOLT); 1719 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1720 } else if (Op.getOpcode() == ISD::FFLOOR) { 1721 // If the truncated value is the less than or equal to the original value, 1722 // we've computed the floor. Otherwise, we went the wrong way and need to 1723 // decrease by 1. 1724 // FIXME: This should use a masked operation. Handle here or in isel? 1725 SDValue Adjust = DAG.getNode(ISD::FSUB, DL, VT, Truncated, 1726 DAG.getConstantFP(1.0, DL, VT)); 1727 SDValue NeedAdjust = DAG.getSetCC(DL, SetccVT, Truncated, Src, ISD::SETOGT); 1728 Truncated = DAG.getSelect(DL, VT, NeedAdjust, Adjust, Truncated); 1729 } 1730 1731 // Restore the original sign so that -0.0 is preserved. 1732 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1733 1734 // Determine the largest integer that can be represented exactly. This and 1735 // values larger than it don't have any fractional bits so don't need to 1736 // be converted. 1737 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1738 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1739 APFloat MaxVal = APFloat(FltSem); 1740 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1741 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1742 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1743 1744 // If abs(Src) was larger than MaxVal or nan, keep it. 1745 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1746 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1747 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1748 } 1749 1750 // ISD::FROUND is defined to round to nearest with ties rounding away from 0. 1751 // This mode isn't supported in vector hardware on RISCV. But as long as we 1752 // aren't compiling with trapping math, we can emulate this with 1753 // floor(X + copysign(nextafter(0.5, 0.0), X)). 1754 // FIXME: Could be shorter by changing rounding mode, but we don't have FRM 1755 // dependencies modeled yet. 1756 // FIXME: Use masked operations to avoid final merge. 1757 static SDValue lowerFROUND(SDValue Op, SelectionDAG &DAG) { 1758 MVT VT = Op.getSimpleValueType(); 1759 assert(VT.isVector() && "Unexpected type"); 1760 1761 SDLoc DL(Op); 1762 1763 // Freeze the source since we are increasing the number of uses. 1764 SDValue Src = DAG.getFreeze(Op.getOperand(0)); 1765 1766 // We do the conversion on the absolute value and fix the sign at the end. 1767 SDValue Abs = DAG.getNode(ISD::FABS, DL, VT, Src); 1768 1769 const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT); 1770 bool Ignored; 1771 APFloat Point5Pred = APFloat(0.5f); 1772 Point5Pred.convert(FltSem, APFloat::rmNearestTiesToEven, &Ignored); 1773 Point5Pred.next(/*nextDown*/ true); 1774 1775 // Add the adjustment. 1776 SDValue Adjust = DAG.getNode(ISD::FADD, DL, VT, Abs, 1777 DAG.getConstantFP(Point5Pred, DL, VT)); 1778 1779 // Truncate to integer and convert back to fp. 1780 MVT IntVT = VT.changeVectorElementTypeToInteger(); 1781 SDValue Truncated = DAG.getNode(ISD::FP_TO_SINT, DL, IntVT, Adjust); 1782 Truncated = DAG.getNode(ISD::SINT_TO_FP, DL, VT, Truncated); 1783 1784 // Restore the original sign. 1785 Truncated = DAG.getNode(ISD::FCOPYSIGN, DL, VT, Truncated, Src); 1786 1787 // Determine the largest integer that can be represented exactly. This and 1788 // values larger than it don't have any fractional bits so don't need to 1789 // be converted. 1790 unsigned Precision = APFloat::semanticsPrecision(FltSem); 1791 APFloat MaxVal = APFloat(FltSem); 1792 MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1), 1793 /*IsSigned*/ false, APFloat::rmNearestTiesToEven); 1794 SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT); 1795 1796 // If abs(Src) was larger than MaxVal or nan, keep it. 1797 MVT SetccVT = MVT::getVectorVT(MVT::i1, VT.getVectorElementCount()); 1798 SDValue Setcc = DAG.getSetCC(DL, SetccVT, Abs, MaxValNode, ISD::SETOLT); 1799 return DAG.getSelect(DL, VT, Setcc, Truncated, Src); 1800 } 1801 1802 struct VIDSequence { 1803 int64_t StepNumerator; 1804 unsigned StepDenominator; 1805 int64_t Addend; 1806 }; 1807 1808 // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S] 1809 // to the (non-zero) step S and start value X. This can be then lowered as the 1810 // RVV sequence (VID * S) + X, for example. 1811 // The step S is represented as an integer numerator divided by a positive 1812 // denominator. Note that the implementation currently only identifies 1813 // sequences in which either the numerator is +/- 1 or the denominator is 1. It 1814 // cannot detect 2/3, for example. 1815 // Note that this method will also match potentially unappealing index 1816 // sequences, like <i32 0, i32 50939494>, however it is left to the caller to 1817 // determine whether this is worth generating code for. 1818 static Optional<VIDSequence> isSimpleVIDSequence(SDValue Op) { 1819 unsigned NumElts = Op.getNumOperands(); 1820 assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR"); 1821 if (!Op.getValueType().isInteger()) 1822 return None; 1823 1824 Optional<unsigned> SeqStepDenom; 1825 Optional<int64_t> SeqStepNum, SeqAddend; 1826 Optional<std::pair<uint64_t, unsigned>> PrevElt; 1827 unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits(); 1828 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1829 // Assume undef elements match the sequence; we just have to be careful 1830 // when interpolating across them. 1831 if (Op.getOperand(Idx).isUndef()) 1832 continue; 1833 // The BUILD_VECTOR must be all constants. 1834 if (!isa<ConstantSDNode>(Op.getOperand(Idx))) 1835 return None; 1836 1837 uint64_t Val = Op.getConstantOperandVal(Idx) & 1838 maskTrailingOnes<uint64_t>(EltSizeInBits); 1839 1840 if (PrevElt) { 1841 // Calculate the step since the last non-undef element, and ensure 1842 // it's consistent across the entire sequence. 1843 unsigned IdxDiff = Idx - PrevElt->second; 1844 int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits); 1845 1846 // A zero-value value difference means that we're somewhere in the middle 1847 // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a 1848 // step change before evaluating the sequence. 1849 if (ValDiff == 0) 1850 continue; 1851 1852 int64_t Remainder = ValDiff % IdxDiff; 1853 // Normalize the step if it's greater than 1. 1854 if (Remainder != ValDiff) { 1855 // The difference must cleanly divide the element span. 1856 if (Remainder != 0) 1857 return None; 1858 ValDiff /= IdxDiff; 1859 IdxDiff = 1; 1860 } 1861 1862 if (!SeqStepNum) 1863 SeqStepNum = ValDiff; 1864 else if (ValDiff != SeqStepNum) 1865 return None; 1866 1867 if (!SeqStepDenom) 1868 SeqStepDenom = IdxDiff; 1869 else if (IdxDiff != *SeqStepDenom) 1870 return None; 1871 } 1872 1873 // Record this non-undef element for later. 1874 if (!PrevElt || PrevElt->first != Val) 1875 PrevElt = std::make_pair(Val, Idx); 1876 } 1877 1878 // We need to have logged a step for this to count as a legal index sequence. 1879 if (!SeqStepNum || !SeqStepDenom) 1880 return None; 1881 1882 // Loop back through the sequence and validate elements we might have skipped 1883 // while waiting for a valid step. While doing this, log any sequence addend. 1884 for (unsigned Idx = 0; Idx < NumElts; Idx++) { 1885 if (Op.getOperand(Idx).isUndef()) 1886 continue; 1887 uint64_t Val = Op.getConstantOperandVal(Idx) & 1888 maskTrailingOnes<uint64_t>(EltSizeInBits); 1889 uint64_t ExpectedVal = 1890 (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom; 1891 int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits); 1892 if (!SeqAddend) 1893 SeqAddend = Addend; 1894 else if (Addend != SeqAddend) 1895 return None; 1896 } 1897 1898 assert(SeqAddend && "Must have an addend if we have a step"); 1899 1900 return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend}; 1901 } 1902 1903 // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT 1904 // and lower it as a VRGATHER_VX_VL from the source vector. 1905 static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL, 1906 SelectionDAG &DAG, 1907 const RISCVSubtarget &Subtarget) { 1908 if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT) 1909 return SDValue(); 1910 SDValue Vec = SplatVal.getOperand(0); 1911 // Only perform this optimization on vectors of the same size for simplicity. 1912 if (Vec.getValueType() != VT) 1913 return SDValue(); 1914 SDValue Idx = SplatVal.getOperand(1); 1915 // The index must be a legal type. 1916 if (Idx.getValueType() != Subtarget.getXLenVT()) 1917 return SDValue(); 1918 1919 MVT ContainerVT = VT; 1920 if (VT.isFixedLengthVector()) { 1921 ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1922 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 1923 } 1924 1925 SDValue Mask, VL; 1926 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1927 1928 SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec, 1929 Idx, Mask, VL); 1930 1931 if (!VT.isFixedLengthVector()) 1932 return Gather; 1933 1934 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 1935 } 1936 1937 static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG, 1938 const RISCVSubtarget &Subtarget) { 1939 MVT VT = Op.getSimpleValueType(); 1940 assert(VT.isFixedLengthVector() && "Unexpected vector!"); 1941 1942 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 1943 1944 SDLoc DL(Op); 1945 SDValue Mask, VL; 1946 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 1947 1948 MVT XLenVT = Subtarget.getXLenVT(); 1949 unsigned NumElts = Op.getNumOperands(); 1950 1951 if (VT.getVectorElementType() == MVT::i1) { 1952 if (ISD::isBuildVectorAllZeros(Op.getNode())) { 1953 SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL); 1954 return convertFromScalableVector(VT, VMClr, DAG, Subtarget); 1955 } 1956 1957 if (ISD::isBuildVectorAllOnes(Op.getNode())) { 1958 SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 1959 return convertFromScalableVector(VT, VMSet, DAG, Subtarget); 1960 } 1961 1962 // Lower constant mask BUILD_VECTORs via an integer vector type, in 1963 // scalar integer chunks whose bit-width depends on the number of mask 1964 // bits and XLEN. 1965 // First, determine the most appropriate scalar integer type to use. This 1966 // is at most XLenVT, but may be shrunk to a smaller vector element type 1967 // according to the size of the final vector - use i8 chunks rather than 1968 // XLenVT if we're producing a v8i1. This results in more consistent 1969 // codegen across RV32 and RV64. 1970 unsigned NumViaIntegerBits = 1971 std::min(std::max(NumElts, 8u), Subtarget.getXLen()); 1972 NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN()); 1973 if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) { 1974 // If we have to use more than one INSERT_VECTOR_ELT then this 1975 // optimization is likely to increase code size; avoid peforming it in 1976 // such a case. We can use a load from a constant pool in this case. 1977 if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits) 1978 return SDValue(); 1979 // Now we can create our integer vector type. Note that it may be larger 1980 // than the resulting mask type: v4i1 would use v1i8 as its integer type. 1981 MVT IntegerViaVecVT = 1982 MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits), 1983 divideCeil(NumElts, NumViaIntegerBits)); 1984 1985 uint64_t Bits = 0; 1986 unsigned BitPos = 0, IntegerEltIdx = 0; 1987 SDValue Vec = DAG.getUNDEF(IntegerViaVecVT); 1988 1989 for (unsigned I = 0; I < NumElts; I++, BitPos++) { 1990 // Once we accumulate enough bits to fill our scalar type, insert into 1991 // our vector and clear our accumulated data. 1992 if (I != 0 && I % NumViaIntegerBits == 0) { 1993 if (NumViaIntegerBits <= 32) 1994 Bits = SignExtend64<32>(Bits); 1995 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 1996 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, 1997 Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 1998 Bits = 0; 1999 BitPos = 0; 2000 IntegerEltIdx++; 2001 } 2002 SDValue V = Op.getOperand(I); 2003 bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue(); 2004 Bits |= ((uint64_t)BitValue << BitPos); 2005 } 2006 2007 // Insert the (remaining) scalar value into position in our integer 2008 // vector type. 2009 if (NumViaIntegerBits <= 32) 2010 Bits = SignExtend64<32>(Bits); 2011 SDValue Elt = DAG.getConstant(Bits, DL, XLenVT); 2012 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt, 2013 DAG.getConstant(IntegerEltIdx, DL, XLenVT)); 2014 2015 if (NumElts < NumViaIntegerBits) { 2016 // If we're producing a smaller vector than our minimum legal integer 2017 // type, bitcast to the equivalent (known-legal) mask type, and extract 2018 // our final mask. 2019 assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type"); 2020 Vec = DAG.getBitcast(MVT::v8i1, Vec); 2021 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec, 2022 DAG.getConstant(0, DL, XLenVT)); 2023 } else { 2024 // Else we must have produced an integer type with the same size as the 2025 // mask type; bitcast for the final result. 2026 assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits()); 2027 Vec = DAG.getBitcast(VT, Vec); 2028 } 2029 2030 return Vec; 2031 } 2032 2033 // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask 2034 // vector type, we have a legal equivalently-sized i8 type, so we can use 2035 // that. 2036 MVT WideVecVT = VT.changeVectorElementType(MVT::i8); 2037 SDValue VecZero = DAG.getConstant(0, DL, WideVecVT); 2038 2039 SDValue WideVec; 2040 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2041 // For a splat, perform a scalar truncate before creating the wider 2042 // vector. 2043 assert(Splat.getValueType() == XLenVT && 2044 "Unexpected type for i1 splat value"); 2045 Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat, 2046 DAG.getConstant(1, DL, XLenVT)); 2047 WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat); 2048 } else { 2049 SmallVector<SDValue, 8> Ops(Op->op_values()); 2050 WideVec = DAG.getBuildVector(WideVecVT, DL, Ops); 2051 SDValue VecOne = DAG.getConstant(1, DL, WideVecVT); 2052 WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne); 2053 } 2054 2055 return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE); 2056 } 2057 2058 if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) { 2059 if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget)) 2060 return Gather; 2061 unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL 2062 : RISCVISD::VMV_V_X_VL; 2063 Splat = 2064 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL); 2065 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2066 } 2067 2068 // Try and match index sequences, which we can lower to the vid instruction 2069 // with optional modifications. An all-undef vector is matched by 2070 // getSplatValue, above. 2071 if (auto SimpleVID = isSimpleVIDSequence(Op)) { 2072 int64_t StepNumerator = SimpleVID->StepNumerator; 2073 unsigned StepDenominator = SimpleVID->StepDenominator; 2074 int64_t Addend = SimpleVID->Addend; 2075 2076 assert(StepNumerator != 0 && "Invalid step"); 2077 bool Negate = false; 2078 int64_t SplatStepVal = StepNumerator; 2079 unsigned StepOpcode = ISD::MUL; 2080 if (StepNumerator != 1) { 2081 if (isPowerOf2_64(std::abs(StepNumerator))) { 2082 Negate = StepNumerator < 0; 2083 StepOpcode = ISD::SHL; 2084 SplatStepVal = Log2_64(std::abs(StepNumerator)); 2085 } 2086 } 2087 2088 // Only emit VIDs with suitably-small steps/addends. We use imm5 is a 2089 // threshold since it's the immediate value many RVV instructions accept. 2090 // There is no vmul.vi instruction so ensure multiply constant can fit in 2091 // a single addi instruction. 2092 if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) || 2093 (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) && 2094 isPowerOf2_32(StepDenominator) && 2095 (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) { 2096 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, ContainerVT, Mask, VL); 2097 // Convert right out of the scalable type so we can use standard ISD 2098 // nodes for the rest of the computation. If we used scalable types with 2099 // these, we'd lose the fixed-length vector info and generate worse 2100 // vsetvli code. 2101 VID = convertFromScalableVector(VT, VID, DAG, Subtarget); 2102 if ((StepOpcode == ISD::MUL && SplatStepVal != 1) || 2103 (StepOpcode == ISD::SHL && SplatStepVal != 0)) { 2104 SDValue SplatStep = DAG.getSplatBuildVector( 2105 VT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT)); 2106 VID = DAG.getNode(StepOpcode, DL, VT, VID, SplatStep); 2107 } 2108 if (StepDenominator != 1) { 2109 SDValue SplatStep = DAG.getSplatBuildVector( 2110 VT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT)); 2111 VID = DAG.getNode(ISD::SRL, DL, VT, VID, SplatStep); 2112 } 2113 if (Addend != 0 || Negate) { 2114 SDValue SplatAddend = DAG.getSplatBuildVector( 2115 VT, DL, DAG.getConstant(Addend, DL, XLenVT)); 2116 VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VT, SplatAddend, VID); 2117 } 2118 return VID; 2119 } 2120 } 2121 2122 // Attempt to detect "hidden" splats, which only reveal themselves as splats 2123 // when re-interpreted as a vector with a larger element type. For example, 2124 // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1 2125 // could be instead splat as 2126 // v2i32 = build_vector i32 0x00010000, i32 0x00010000 2127 // TODO: This optimization could also work on non-constant splats, but it 2128 // would require bit-manipulation instructions to construct the splat value. 2129 SmallVector<SDValue> Sequence; 2130 unsigned EltBitSize = VT.getScalarSizeInBits(); 2131 const auto *BV = cast<BuildVectorSDNode>(Op); 2132 if (VT.isInteger() && EltBitSize < 64 && 2133 ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) && 2134 BV->getRepeatedSequence(Sequence) && 2135 (Sequence.size() * EltBitSize) <= 64) { 2136 unsigned SeqLen = Sequence.size(); 2137 MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen); 2138 MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen); 2139 assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 || 2140 ViaIntVT == MVT::i64) && 2141 "Unexpected sequence type"); 2142 2143 unsigned EltIdx = 0; 2144 uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize); 2145 uint64_t SplatValue = 0; 2146 // Construct the amalgamated value which can be splatted as this larger 2147 // vector type. 2148 for (const auto &SeqV : Sequence) { 2149 if (!SeqV.isUndef()) 2150 SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask) 2151 << (EltIdx * EltBitSize)); 2152 EltIdx++; 2153 } 2154 2155 // On RV64, sign-extend from 32 to 64 bits where possible in order to 2156 // achieve better constant materializion. 2157 if (Subtarget.is64Bit() && ViaIntVT == MVT::i32) 2158 SplatValue = SignExtend64<32>(SplatValue); 2159 2160 // Since we can't introduce illegal i64 types at this stage, we can only 2161 // perform an i64 splat on RV32 if it is its own sign-extended value. That 2162 // way we can use RVV instructions to splat. 2163 assert((ViaIntVT.bitsLE(XLenVT) || 2164 (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) && 2165 "Unexpected bitcast sequence"); 2166 if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) { 2167 SDValue ViaVL = 2168 DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT); 2169 MVT ViaContainerVT = 2170 getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget); 2171 SDValue Splat = 2172 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT, 2173 DAG.getUNDEF(ViaContainerVT), 2174 DAG.getConstant(SplatValue, DL, XLenVT), ViaVL); 2175 Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget); 2176 return DAG.getBitcast(VT, Splat); 2177 } 2178 } 2179 2180 // Try and optimize BUILD_VECTORs with "dominant values" - these are values 2181 // which constitute a large proportion of the elements. In such cases we can 2182 // splat a vector with the dominant element and make up the shortfall with 2183 // INSERT_VECTOR_ELTs. 2184 // Note that this includes vectors of 2 elements by association. The 2185 // upper-most element is the "dominant" one, allowing us to use a splat to 2186 // "insert" the upper element, and an insert of the lower element at position 2187 // 0, which improves codegen. 2188 SDValue DominantValue; 2189 unsigned MostCommonCount = 0; 2190 DenseMap<SDValue, unsigned> ValueCounts; 2191 unsigned NumUndefElts = 2192 count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); }); 2193 2194 // Track the number of scalar loads we know we'd be inserting, estimated as 2195 // any non-zero floating-point constant. Other kinds of element are either 2196 // already in registers or are materialized on demand. The threshold at which 2197 // a vector load is more desirable than several scalar materializion and 2198 // vector-insertion instructions is not known. 2199 unsigned NumScalarLoads = 0; 2200 2201 for (SDValue V : Op->op_values()) { 2202 if (V.isUndef()) 2203 continue; 2204 2205 ValueCounts.insert(std::make_pair(V, 0)); 2206 unsigned &Count = ValueCounts[V]; 2207 2208 if (auto *CFP = dyn_cast<ConstantFPSDNode>(V)) 2209 NumScalarLoads += !CFP->isExactlyValue(+0.0); 2210 2211 // Is this value dominant? In case of a tie, prefer the highest element as 2212 // it's cheaper to insert near the beginning of a vector than it is at the 2213 // end. 2214 if (++Count >= MostCommonCount) { 2215 DominantValue = V; 2216 MostCommonCount = Count; 2217 } 2218 } 2219 2220 assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR"); 2221 unsigned NumDefElts = NumElts - NumUndefElts; 2222 unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2; 2223 2224 // Don't perform this optimization when optimizing for size, since 2225 // materializing elements and inserting them tends to cause code bloat. 2226 if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts && 2227 ((MostCommonCount > DominantValueCountThreshold) || 2228 (ValueCounts.size() <= Log2_32(NumDefElts)))) { 2229 // Start by splatting the most common element. 2230 SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue); 2231 2232 DenseSet<SDValue> Processed{DominantValue}; 2233 MVT SelMaskTy = VT.changeVectorElementType(MVT::i1); 2234 for (const auto &OpIdx : enumerate(Op->ops())) { 2235 const SDValue &V = OpIdx.value(); 2236 if (V.isUndef() || !Processed.insert(V).second) 2237 continue; 2238 if (ValueCounts[V] == 1) { 2239 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V, 2240 DAG.getConstant(OpIdx.index(), DL, XLenVT)); 2241 } else { 2242 // Blend in all instances of this value using a VSELECT, using a 2243 // mask where each bit signals whether that element is the one 2244 // we're after. 2245 SmallVector<SDValue> Ops; 2246 transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) { 2247 return DAG.getConstant(V == V1, DL, XLenVT); 2248 }); 2249 Vec = DAG.getNode(ISD::VSELECT, DL, VT, 2250 DAG.getBuildVector(SelMaskTy, DL, Ops), 2251 DAG.getSplatBuildVector(VT, DL, V), Vec); 2252 } 2253 } 2254 2255 return Vec; 2256 } 2257 2258 return SDValue(); 2259 } 2260 2261 static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2262 SDValue Lo, SDValue Hi, SDValue VL, 2263 SelectionDAG &DAG) { 2264 if (!Passthru) 2265 Passthru = DAG.getUNDEF(VT); 2266 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 2267 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 2268 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 2269 // If Hi constant is all the same sign bit as Lo, lower this as a custom 2270 // node in order to try and match RVV vector/scalar instructions. 2271 if ((LoC >> 31) == HiC) 2272 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL); 2273 2274 // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use 2275 // vmv.v.x whose EEW = 32 to lower it. 2276 auto *Const = dyn_cast<ConstantSDNode>(VL); 2277 if (LoC == HiC && Const && Const->isAllOnesValue()) { 2278 MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 2279 // TODO: if vl <= min(VLMAX), we can also do this. But we could not 2280 // access the subtarget here now. 2281 auto InterVec = DAG.getNode( 2282 RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo, 2283 DAG.getRegister(RISCV::X0, MVT::i32)); 2284 return DAG.getNode(ISD::BITCAST, DL, VT, InterVec); 2285 } 2286 } 2287 2288 // Fall back to a stack store and stride x0 vector load. 2289 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo, 2290 Hi, VL); 2291 } 2292 2293 // Called by type legalization to handle splat of i64 on RV32. 2294 // FIXME: We can optimize this when the type has sign or zero bits in one 2295 // of the halves. 2296 static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru, 2297 SDValue Scalar, SDValue VL, 2298 SelectionDAG &DAG) { 2299 assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!"); 2300 SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2301 DAG.getConstant(0, DL, MVT::i32)); 2302 SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar, 2303 DAG.getConstant(1, DL, MVT::i32)); 2304 return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG); 2305 } 2306 2307 // This function lowers a splat of a scalar operand Splat with the vector 2308 // length VL. It ensures the final sequence is type legal, which is useful when 2309 // lowering a splat after type legalization. 2310 static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL, 2311 MVT VT, SDLoc DL, SelectionDAG &DAG, 2312 const RISCVSubtarget &Subtarget) { 2313 bool HasPassthru = Passthru && !Passthru.isUndef(); 2314 if (!HasPassthru && !Passthru) 2315 Passthru = DAG.getUNDEF(VT); 2316 if (VT.isFloatingPoint()) { 2317 // If VL is 1, we could use vfmv.s.f. 2318 if (isOneConstant(VL)) 2319 return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL); 2320 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL); 2321 } 2322 2323 MVT XLenVT = Subtarget.getXLenVT(); 2324 2325 // Simplest case is that the operand needs to be promoted to XLenVT. 2326 if (Scalar.getValueType().bitsLE(XLenVT)) { 2327 // If the operand is a constant, sign extend to increase our chances 2328 // of being able to use a .vi instruction. ANY_EXTEND would become a 2329 // a zero extend and the simm5 check in isel would fail. 2330 // FIXME: Should we ignore the upper bits in isel instead? 2331 unsigned ExtOpc = 2332 isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 2333 Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar); 2334 ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar); 2335 // If VL is 1 and the scalar value won't benefit from immediate, we could 2336 // use vmv.s.x. 2337 if (isOneConstant(VL) && 2338 (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue()))) 2339 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL); 2340 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL); 2341 } 2342 2343 assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 && 2344 "Unexpected scalar for splat lowering!"); 2345 2346 if (isOneConstant(VL) && isNullConstant(Scalar)) 2347 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, 2348 DAG.getConstant(0, DL, XLenVT), VL); 2349 2350 // Otherwise use the more complicated splatting algorithm. 2351 return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG); 2352 } 2353 2354 static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources, 2355 const RISCVSubtarget &Subtarget) { 2356 // We need to be able to widen elements to the next larger integer type. 2357 if (VT.getScalarSizeInBits() >= Subtarget.getELEN()) 2358 return false; 2359 2360 int Size = Mask.size(); 2361 assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size"); 2362 2363 int Srcs[] = {-1, -1}; 2364 for (int i = 0; i != Size; ++i) { 2365 // Ignore undef elements. 2366 if (Mask[i] < 0) 2367 continue; 2368 2369 // Is this an even or odd element. 2370 int Pol = i % 2; 2371 2372 // Ensure we consistently use the same source for this element polarity. 2373 int Src = Mask[i] / Size; 2374 if (Srcs[Pol] < 0) 2375 Srcs[Pol] = Src; 2376 if (Srcs[Pol] != Src) 2377 return false; 2378 2379 // Make sure the element within the source is appropriate for this element 2380 // in the destination. 2381 int Elt = Mask[i] % Size; 2382 if (Elt != i / 2) 2383 return false; 2384 } 2385 2386 // We need to find a source for each polarity and they can't be the same. 2387 if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1]) 2388 return false; 2389 2390 // Swap the sources if the second source was in the even polarity. 2391 SwapSources = Srcs[0] > Srcs[1]; 2392 2393 return true; 2394 } 2395 2396 /// Match shuffles that concatenate two vectors, rotate the concatenation, 2397 /// and then extract the original number of elements from the rotated result. 2398 /// This is equivalent to vector.splice or X86's PALIGNR instruction. The 2399 /// returned rotation amount is for a rotate right, where elements move from 2400 /// higher elements to lower elements. \p LoSrc indicates the first source 2401 /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector 2402 /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be 2403 /// 0 or 1 if a rotation is found. 2404 /// 2405 /// NOTE: We talk about rotate to the right which matches how bit shift and 2406 /// rotate instructions are described where LSBs are on the right, but LLVM IR 2407 /// and the table below write vectors with the lowest elements on the left. 2408 static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) { 2409 int Size = Mask.size(); 2410 2411 // We need to detect various ways of spelling a rotation: 2412 // [11, 12, 13, 14, 15, 0, 1, 2] 2413 // [-1, 12, 13, 14, -1, -1, 1, -1] 2414 // [-1, -1, -1, -1, -1, -1, 1, 2] 2415 // [ 3, 4, 5, 6, 7, 8, 9, 10] 2416 // [-1, 4, 5, 6, -1, -1, 9, -1] 2417 // [-1, 4, 5, 6, -1, -1, -1, -1] 2418 int Rotation = 0; 2419 LoSrc = -1; 2420 HiSrc = -1; 2421 for (int i = 0; i != Size; ++i) { 2422 int M = Mask[i]; 2423 if (M < 0) 2424 continue; 2425 2426 // Determine where a rotate vector would have started. 2427 int StartIdx = i - (M % Size); 2428 // The identity rotation isn't interesting, stop. 2429 if (StartIdx == 0) 2430 return -1; 2431 2432 // If we found the tail of a vector the rotation must be the missing 2433 // front. If we found the head of a vector, it must be how much of the 2434 // head. 2435 int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx; 2436 2437 if (Rotation == 0) 2438 Rotation = CandidateRotation; 2439 else if (Rotation != CandidateRotation) 2440 // The rotations don't match, so we can't match this mask. 2441 return -1; 2442 2443 // Compute which value this mask is pointing at. 2444 int MaskSrc = M < Size ? 0 : 1; 2445 2446 // Compute which of the two target values this index should be assigned to. 2447 // This reflects whether the high elements are remaining or the low elemnts 2448 // are remaining. 2449 int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc; 2450 2451 // Either set up this value if we've not encountered it before, or check 2452 // that it remains consistent. 2453 if (TargetSrc < 0) 2454 TargetSrc = MaskSrc; 2455 else if (TargetSrc != MaskSrc) 2456 // This may be a rotation, but it pulls from the inputs in some 2457 // unsupported interleaving. 2458 return -1; 2459 } 2460 2461 // Check that we successfully analyzed the mask, and normalize the results. 2462 assert(Rotation != 0 && "Failed to locate a viable rotation!"); 2463 assert((LoSrc >= 0 || HiSrc >= 0) && 2464 "Failed to find a rotated input vector!"); 2465 2466 return Rotation; 2467 } 2468 2469 static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG, 2470 const RISCVSubtarget &Subtarget) { 2471 SDValue V1 = Op.getOperand(0); 2472 SDValue V2 = Op.getOperand(1); 2473 SDLoc DL(Op); 2474 MVT XLenVT = Subtarget.getXLenVT(); 2475 MVT VT = Op.getSimpleValueType(); 2476 unsigned NumElts = VT.getVectorNumElements(); 2477 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode()); 2478 2479 MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget); 2480 2481 SDValue TrueMask, VL; 2482 std::tie(TrueMask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 2483 2484 if (SVN->isSplat()) { 2485 const int Lane = SVN->getSplatIndex(); 2486 if (Lane >= 0) { 2487 MVT SVT = VT.getVectorElementType(); 2488 2489 // Turn splatted vector load into a strided load with an X0 stride. 2490 SDValue V = V1; 2491 // Peek through CONCAT_VECTORS as VectorCombine can concat a vector 2492 // with undef. 2493 // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts? 2494 int Offset = Lane; 2495 if (V.getOpcode() == ISD::CONCAT_VECTORS) { 2496 int OpElements = 2497 V.getOperand(0).getSimpleValueType().getVectorNumElements(); 2498 V = V.getOperand(Offset / OpElements); 2499 Offset %= OpElements; 2500 } 2501 2502 // We need to ensure the load isn't atomic or volatile. 2503 if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) { 2504 auto *Ld = cast<LoadSDNode>(V); 2505 Offset *= SVT.getStoreSize(); 2506 SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), 2507 TypeSize::Fixed(Offset), DL); 2508 2509 // If this is SEW=64 on RV32, use a strided load with a stride of x0. 2510 if (SVT.isInteger() && SVT.bitsGT(XLenVT)) { 2511 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 2512 SDValue IntID = 2513 DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT); 2514 SDValue Ops[] = {Ld->getChain(), 2515 IntID, 2516 DAG.getUNDEF(ContainerVT), 2517 NewAddr, 2518 DAG.getRegister(RISCV::X0, XLenVT), 2519 VL}; 2520 SDValue NewLoad = DAG.getMemIntrinsicNode( 2521 ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT, 2522 DAG.getMachineFunction().getMachineMemOperand( 2523 Ld->getMemOperand(), Offset, SVT.getStoreSize())); 2524 DAG.makeEquivalentMemoryOrdering(Ld, NewLoad); 2525 return convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 2526 } 2527 2528 // Otherwise use a scalar load and splat. This will give the best 2529 // opportunity to fold a splat into the operation. ISel can turn it into 2530 // the x0 strided load if we aren't able to fold away the select. 2531 if (SVT.isFloatingPoint()) 2532 V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr, 2533 Ld->getPointerInfo().getWithOffset(Offset), 2534 Ld->getOriginalAlign(), 2535 Ld->getMemOperand()->getFlags()); 2536 else 2537 V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr, 2538 Ld->getPointerInfo().getWithOffset(Offset), SVT, 2539 Ld->getOriginalAlign(), 2540 Ld->getMemOperand()->getFlags()); 2541 DAG.makeEquivalentMemoryOrdering(Ld, V); 2542 2543 unsigned Opc = 2544 VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL; 2545 SDValue Splat = 2546 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL); 2547 return convertFromScalableVector(VT, Splat, DAG, Subtarget); 2548 } 2549 2550 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2551 assert(Lane < (int)NumElts && "Unexpected lane!"); 2552 SDValue Gather = 2553 DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, V1, 2554 DAG.getConstant(Lane, DL, XLenVT), TrueMask, VL); 2555 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2556 } 2557 } 2558 2559 ArrayRef<int> Mask = SVN->getMask(); 2560 2561 // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may 2562 // be undef which can be handled with a single SLIDEDOWN/UP. 2563 int LoSrc, HiSrc; 2564 int Rotation = isElementRotate(LoSrc, HiSrc, Mask); 2565 if (Rotation > 0) { 2566 SDValue LoV, HiV; 2567 if (LoSrc >= 0) { 2568 LoV = LoSrc == 0 ? V1 : V2; 2569 LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget); 2570 } 2571 if (HiSrc >= 0) { 2572 HiV = HiSrc == 0 ? V1 : V2; 2573 HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget); 2574 } 2575 2576 // We found a rotation. We need to slide HiV down by Rotation. Then we need 2577 // to slide LoV up by (NumElts - Rotation). 2578 unsigned InvRotate = NumElts - Rotation; 2579 2580 SDValue Res = DAG.getUNDEF(ContainerVT); 2581 if (HiV) { 2582 // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN. 2583 // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it 2584 // causes multiple vsetvlis in some test cases such as lowering 2585 // reduce.mul 2586 SDValue DownVL = VL; 2587 if (LoV) 2588 DownVL = DAG.getConstant(InvRotate, DL, XLenVT); 2589 Res = 2590 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, Res, HiV, 2591 DAG.getConstant(Rotation, DL, XLenVT), TrueMask, DownVL); 2592 } 2593 if (LoV) 2594 Res = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Res, LoV, 2595 DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL); 2596 2597 return convertFromScalableVector(VT, Res, DAG, Subtarget); 2598 } 2599 2600 // Detect an interleave shuffle and lower to 2601 // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1)) 2602 bool SwapSources; 2603 if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) { 2604 // Swap sources if needed. 2605 if (SwapSources) 2606 std::swap(V1, V2); 2607 2608 // Extract the lower half of the vectors. 2609 MVT HalfVT = VT.getHalfNumVectorElementsVT(); 2610 V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1, 2611 DAG.getConstant(0, DL, XLenVT)); 2612 V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2, 2613 DAG.getConstant(0, DL, XLenVT)); 2614 2615 // Double the element width and halve the number of elements in an int type. 2616 unsigned EltBits = VT.getScalarSizeInBits(); 2617 MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2); 2618 MVT WideIntVT = 2619 MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2); 2620 // Convert this to a scalable vector. We need to base this on the 2621 // destination size to ensure there's always a type with a smaller LMUL. 2622 MVT WideIntContainerVT = 2623 getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget); 2624 2625 // Convert sources to scalable vectors with the same element count as the 2626 // larger type. 2627 MVT HalfContainerVT = MVT::getVectorVT( 2628 VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount()); 2629 V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget); 2630 V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget); 2631 2632 // Cast sources to integer. 2633 MVT IntEltVT = MVT::getIntegerVT(EltBits); 2634 MVT IntHalfVT = 2635 MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount()); 2636 V1 = DAG.getBitcast(IntHalfVT, V1); 2637 V2 = DAG.getBitcast(IntHalfVT, V2); 2638 2639 // Freeze V2 since we use it twice and we need to be sure that the add and 2640 // multiply see the same value. 2641 V2 = DAG.getFreeze(V2); 2642 2643 // Recreate TrueMask using the widened type's element count. 2644 TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG); 2645 2646 // Widen V1 and V2 with 0s and add one copy of V2 to V1. 2647 SDValue Add = DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, 2648 V2, TrueMask, VL); 2649 // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer. 2650 SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT, 2651 DAG.getUNDEF(IntHalfVT), 2652 DAG.getAllOnesConstant(DL, XLenVT)); 2653 SDValue WidenMul = DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, 2654 V2, Multiplier, TrueMask, VL); 2655 // Add the new copies to our previous addition giving us 2^eltbits copies of 2656 // V2. This is equivalent to shifting V2 left by eltbits. This should 2657 // combine with the vwmulu.vv above to form vwmaccu.vv. 2658 Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul, 2659 TrueMask, VL); 2660 // Cast back to ContainerVT. We need to re-create a new ContainerVT in case 2661 // WideIntContainerVT is a larger fractional LMUL than implied by the fixed 2662 // vector VT. 2663 ContainerVT = 2664 MVT::getVectorVT(VT.getVectorElementType(), 2665 WideIntContainerVT.getVectorElementCount() * 2); 2666 Add = DAG.getBitcast(ContainerVT, Add); 2667 return convertFromScalableVector(VT, Add, DAG, Subtarget); 2668 } 2669 2670 // Detect shuffles which can be re-expressed as vector selects; these are 2671 // shuffles in which each element in the destination is taken from an element 2672 // at the corresponding index in either source vectors. 2673 bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) { 2674 int MaskIndex = MaskIdx.value(); 2675 return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts; 2676 }); 2677 2678 assert(!V1.isUndef() && "Unexpected shuffle canonicalization"); 2679 2680 SmallVector<SDValue> MaskVals; 2681 // As a backup, shuffles can be lowered via a vrgather instruction, possibly 2682 // merged with a second vrgather. 2683 SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS; 2684 2685 // By default we preserve the original operand order, and use a mask to 2686 // select LHS as true and RHS as false. However, since RVV vector selects may 2687 // feature splats but only on the LHS, we may choose to invert our mask and 2688 // instead select between RHS and LHS. 2689 bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1); 2690 bool InvertMask = IsSelect == SwapOps; 2691 2692 // Keep a track of which non-undef indices are used by each LHS/RHS shuffle 2693 // half. 2694 DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts; 2695 2696 // Now construct the mask that will be used by the vselect or blended 2697 // vrgather operation. For vrgathers, construct the appropriate indices into 2698 // each vector. 2699 for (int MaskIndex : Mask) { 2700 bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask; 2701 MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT)); 2702 if (!IsSelect) { 2703 bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts; 2704 GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0 2705 ? DAG.getConstant(MaskIndex, DL, XLenVT) 2706 : DAG.getUNDEF(XLenVT)); 2707 GatherIndicesRHS.push_back( 2708 IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT) 2709 : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT)); 2710 if (IsLHSOrUndefIndex && MaskIndex >= 0) 2711 ++LHSIndexCounts[MaskIndex]; 2712 if (!IsLHSOrUndefIndex) 2713 ++RHSIndexCounts[MaskIndex - NumElts]; 2714 } 2715 } 2716 2717 if (SwapOps) { 2718 std::swap(V1, V2); 2719 std::swap(GatherIndicesLHS, GatherIndicesRHS); 2720 } 2721 2722 assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle"); 2723 MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts); 2724 SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals); 2725 2726 if (IsSelect) 2727 return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2); 2728 2729 if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) { 2730 // On such a large vector we're unable to use i8 as the index type. 2731 // FIXME: We could promote the index to i16 and use vrgatherei16, but that 2732 // may involve vector splitting if we're already at LMUL=8, or our 2733 // user-supplied maximum fixed-length LMUL. 2734 return SDValue(); 2735 } 2736 2737 unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL; 2738 unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL; 2739 MVT IndexVT = VT.changeTypeToInteger(); 2740 // Since we can't introduce illegal index types at this stage, use i16 and 2741 // vrgatherei16 if the corresponding index type for plain vrgather is greater 2742 // than XLenVT. 2743 if (IndexVT.getScalarType().bitsGT(XLenVT)) { 2744 GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL; 2745 IndexVT = IndexVT.changeVectorElementType(MVT::i16); 2746 } 2747 2748 MVT IndexContainerVT = 2749 ContainerVT.changeVectorElementType(IndexVT.getScalarType()); 2750 2751 SDValue Gather; 2752 // TODO: This doesn't trigger for i64 vectors on RV32, since there we 2753 // encounter a bitcasted BUILD_VECTOR with low/high i32 values. 2754 if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) { 2755 Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG, 2756 Subtarget); 2757 } else { 2758 V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget); 2759 // If only one index is used, we can use a "splat" vrgather. 2760 // TODO: We can splat the most-common index and fix-up any stragglers, if 2761 // that's beneficial. 2762 if (LHSIndexCounts.size() == 1) { 2763 int SplatIndex = LHSIndexCounts.begin()->getFirst(); 2764 Gather = 2765 DAG.getNode(GatherVXOpc, DL, ContainerVT, V1, 2766 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2767 } else { 2768 SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS); 2769 LHSIndices = 2770 convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget); 2771 2772 Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices, 2773 TrueMask, VL); 2774 } 2775 } 2776 2777 // If a second vector operand is used by this shuffle, blend it in with an 2778 // additional vrgather. 2779 if (!V2.isUndef()) { 2780 V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget); 2781 // If only one index is used, we can use a "splat" vrgather. 2782 // TODO: We can splat the most-common index and fix-up any stragglers, if 2783 // that's beneficial. 2784 if (RHSIndexCounts.size() == 1) { 2785 int SplatIndex = RHSIndexCounts.begin()->getFirst(); 2786 V2 = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2, 2787 DAG.getConstant(SplatIndex, DL, XLenVT), TrueMask, VL); 2788 } else { 2789 SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS); 2790 RHSIndices = 2791 convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget); 2792 V2 = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, TrueMask, 2793 VL); 2794 } 2795 2796 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 2797 SelectMask = 2798 convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget); 2799 2800 Gather = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, SelectMask, V2, 2801 Gather, VL); 2802 } 2803 2804 return convertFromScalableVector(VT, Gather, DAG, Subtarget); 2805 } 2806 2807 bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const { 2808 // Support splats for any type. These should type legalize well. 2809 if (ShuffleVectorSDNode::isSplatMask(M.data(), VT)) 2810 return true; 2811 2812 // Only support legal VTs for other shuffles for now. 2813 if (!isTypeLegal(VT)) 2814 return false; 2815 2816 MVT SVT = VT.getSimpleVT(); 2817 2818 bool SwapSources; 2819 int LoSrc, HiSrc; 2820 return (isElementRotate(LoSrc, HiSrc, M) > 0) || 2821 isInterleaveShuffle(M, SVT, SwapSources, Subtarget); 2822 } 2823 2824 // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting 2825 // the exponent. 2826 static SDValue lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) { 2827 MVT VT = Op.getSimpleValueType(); 2828 unsigned EltSize = VT.getScalarSizeInBits(); 2829 SDValue Src = Op.getOperand(0); 2830 SDLoc DL(Op); 2831 2832 // We need a FP type that can represent the value. 2833 // TODO: Use f16 for i8 when possible? 2834 MVT FloatEltVT = EltSize == 32 ? MVT::f64 : MVT::f32; 2835 MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount()); 2836 2837 // Legal types should have been checked in the RISCVTargetLowering 2838 // constructor. 2839 // TODO: Splitting may make sense in some cases. 2840 assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) && 2841 "Expected legal float type!"); 2842 2843 // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X. 2844 // The trailing zero count is equal to log2 of this single bit value. 2845 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) { 2846 SDValue Neg = 2847 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Src); 2848 Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg); 2849 } 2850 2851 // We have a legal FP type, convert to it. 2852 SDValue FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src); 2853 // Bitcast to integer and shift the exponent to the LSB. 2854 EVT IntVT = FloatVT.changeVectorElementTypeToInteger(); 2855 SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal); 2856 unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23; 2857 SDValue Shift = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast, 2858 DAG.getConstant(ShiftAmt, DL, IntVT)); 2859 // Truncate back to original type to allow vnsrl. 2860 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, Shift); 2861 // The exponent contains log2 of the value in biased form. 2862 unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127; 2863 2864 // For trailing zeros, we just need to subtract the bias. 2865 if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) 2866 return DAG.getNode(ISD::SUB, DL, VT, Trunc, 2867 DAG.getConstant(ExponentBias, DL, VT)); 2868 2869 // For leading zeros, we need to remove the bias and convert from log2 to 2870 // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)). 2871 unsigned Adjust = ExponentBias + (EltSize - 1); 2872 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Trunc); 2873 } 2874 2875 // While RVV has alignment restrictions, we should always be able to load as a 2876 // legal equivalently-sized byte-typed vector instead. This method is 2877 // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If 2878 // the load is already correctly-aligned, it returns SDValue(). 2879 SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op, 2880 SelectionDAG &DAG) const { 2881 auto *Load = cast<LoadSDNode>(Op); 2882 assert(Load && Load->getMemoryVT().isVector() && "Expected vector load"); 2883 2884 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2885 Load->getMemoryVT(), 2886 *Load->getMemOperand())) 2887 return SDValue(); 2888 2889 SDLoc DL(Op); 2890 MVT VT = Op.getSimpleValueType(); 2891 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2892 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2893 "Unexpected unaligned RVV load type"); 2894 MVT NewVT = 2895 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2896 assert(NewVT.isValid() && 2897 "Expecting equally-sized RVV vector types to be legal"); 2898 SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(), 2899 Load->getPointerInfo(), Load->getOriginalAlign(), 2900 Load->getMemOperand()->getFlags()); 2901 return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL); 2902 } 2903 2904 // While RVV has alignment restrictions, we should always be able to store as a 2905 // legal equivalently-sized byte-typed vector instead. This method is 2906 // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It 2907 // returns SDValue() if the store is already correctly aligned. 2908 SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op, 2909 SelectionDAG &DAG) const { 2910 auto *Store = cast<StoreSDNode>(Op); 2911 assert(Store && Store->getValue().getValueType().isVector() && 2912 "Expected vector store"); 2913 2914 if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 2915 Store->getMemoryVT(), 2916 *Store->getMemOperand())) 2917 return SDValue(); 2918 2919 SDLoc DL(Op); 2920 SDValue StoredVal = Store->getValue(); 2921 MVT VT = StoredVal.getSimpleValueType(); 2922 unsigned EltSizeBits = VT.getScalarSizeInBits(); 2923 assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) && 2924 "Unexpected unaligned RVV store type"); 2925 MVT NewVT = 2926 MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8)); 2927 assert(NewVT.isValid() && 2928 "Expecting equally-sized RVV vector types to be legal"); 2929 StoredVal = DAG.getBitcast(NewVT, StoredVal); 2930 return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(), 2931 Store->getPointerInfo(), Store->getOriginalAlign(), 2932 Store->getMemOperand()->getFlags()); 2933 } 2934 2935 SDValue RISCVTargetLowering::LowerOperation(SDValue Op, 2936 SelectionDAG &DAG) const { 2937 switch (Op.getOpcode()) { 2938 default: 2939 report_fatal_error("unimplemented operand"); 2940 case ISD::GlobalAddress: 2941 return lowerGlobalAddress(Op, DAG); 2942 case ISD::BlockAddress: 2943 return lowerBlockAddress(Op, DAG); 2944 case ISD::ConstantPool: 2945 return lowerConstantPool(Op, DAG); 2946 case ISD::JumpTable: 2947 return lowerJumpTable(Op, DAG); 2948 case ISD::GlobalTLSAddress: 2949 return lowerGlobalTLSAddress(Op, DAG); 2950 case ISD::SELECT: 2951 return lowerSELECT(Op, DAG); 2952 case ISD::BRCOND: 2953 return lowerBRCOND(Op, DAG); 2954 case ISD::VASTART: 2955 return lowerVASTART(Op, DAG); 2956 case ISD::FRAMEADDR: 2957 return lowerFRAMEADDR(Op, DAG); 2958 case ISD::RETURNADDR: 2959 return lowerRETURNADDR(Op, DAG); 2960 case ISD::SHL_PARTS: 2961 return lowerShiftLeftParts(Op, DAG); 2962 case ISD::SRA_PARTS: 2963 return lowerShiftRightParts(Op, DAG, true); 2964 case ISD::SRL_PARTS: 2965 return lowerShiftRightParts(Op, DAG, false); 2966 case ISD::BITCAST: { 2967 SDLoc DL(Op); 2968 EVT VT = Op.getValueType(); 2969 SDValue Op0 = Op.getOperand(0); 2970 EVT Op0VT = Op0.getValueType(); 2971 MVT XLenVT = Subtarget.getXLenVT(); 2972 if (VT == MVT::f16 && Op0VT == MVT::i16 && Subtarget.hasStdExtZfh()) { 2973 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0); 2974 SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0); 2975 return FPConv; 2976 } 2977 if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() && 2978 Subtarget.hasStdExtF()) { 2979 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0); 2980 SDValue FPConv = 2981 DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0); 2982 return FPConv; 2983 } 2984 2985 // Consider other scalar<->scalar casts as legal if the types are legal. 2986 // Otherwise expand them. 2987 if (!VT.isVector() && !Op0VT.isVector()) { 2988 if (isTypeLegal(VT) && isTypeLegal(Op0VT)) 2989 return Op; 2990 return SDValue(); 2991 } 2992 2993 assert(!VT.isScalableVector() && !Op0VT.isScalableVector() && 2994 "Unexpected types"); 2995 2996 if (VT.isFixedLengthVector()) { 2997 // We can handle fixed length vector bitcasts with a simple replacement 2998 // in isel. 2999 if (Op0VT.isFixedLengthVector()) 3000 return Op; 3001 // When bitcasting from scalar to fixed-length vector, insert the scalar 3002 // into a one-element vector of the result type, and perform a vector 3003 // bitcast. 3004 if (!Op0VT.isVector()) { 3005 EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1); 3006 if (!isTypeLegal(BVT)) 3007 return SDValue(); 3008 return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT, 3009 DAG.getUNDEF(BVT), Op0, 3010 DAG.getConstant(0, DL, XLenVT))); 3011 } 3012 return SDValue(); 3013 } 3014 // Custom-legalize bitcasts from fixed-length vector types to scalar types 3015 // thus: bitcast the vector to a one-element vector type whose element type 3016 // is the same as the result type, and extract the first element. 3017 if (!VT.isVector() && Op0VT.isFixedLengthVector()) { 3018 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 3019 if (!isTypeLegal(BVT)) 3020 return SDValue(); 3021 SDValue BVec = DAG.getBitcast(BVT, Op0); 3022 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 3023 DAG.getConstant(0, DL, XLenVT)); 3024 } 3025 return SDValue(); 3026 } 3027 case ISD::INTRINSIC_WO_CHAIN: 3028 return LowerINTRINSIC_WO_CHAIN(Op, DAG); 3029 case ISD::INTRINSIC_W_CHAIN: 3030 return LowerINTRINSIC_W_CHAIN(Op, DAG); 3031 case ISD::INTRINSIC_VOID: 3032 return LowerINTRINSIC_VOID(Op, DAG); 3033 case ISD::BSWAP: 3034 case ISD::BITREVERSE: { 3035 MVT VT = Op.getSimpleValueType(); 3036 SDLoc DL(Op); 3037 if (Subtarget.hasStdExtZbp()) { 3038 // Convert BSWAP/BITREVERSE to GREVI to enable GREVI combinining. 3039 // Start with the maximum immediate value which is the bitwidth - 1. 3040 unsigned Imm = VT.getSizeInBits() - 1; 3041 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 3042 if (Op.getOpcode() == ISD::BSWAP) 3043 Imm &= ~0x7U; 3044 return DAG.getNode(RISCVISD::GREV, DL, VT, Op.getOperand(0), 3045 DAG.getConstant(Imm, DL, VT)); 3046 } 3047 assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization"); 3048 assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode"); 3049 // Expand bitreverse to a bswap(rev8) followed by brev8. 3050 SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0)); 3051 // We use the Zbp grevi encoding for rev.b/brev8 which will be recognized 3052 // as brev8 by an isel pattern. 3053 return DAG.getNode(RISCVISD::GREV, DL, VT, BSwap, 3054 DAG.getConstant(7, DL, VT)); 3055 } 3056 case ISD::FSHL: 3057 case ISD::FSHR: { 3058 MVT VT = Op.getSimpleValueType(); 3059 assert(VT == Subtarget.getXLenVT() && "Unexpected custom legalization"); 3060 SDLoc DL(Op); 3061 // FSL/FSR take a log2(XLen)+1 bit shift amount but XLenVT FSHL/FSHR only 3062 // use log(XLen) bits. Mask the shift amount accordingly to prevent 3063 // accidentally setting the extra bit. 3064 unsigned ShAmtWidth = Subtarget.getXLen() - 1; 3065 SDValue ShAmt = DAG.getNode(ISD::AND, DL, VT, Op.getOperand(2), 3066 DAG.getConstant(ShAmtWidth, DL, VT)); 3067 // fshl and fshr concatenate their operands in the same order. fsr and fsl 3068 // instruction use different orders. fshl will return its first operand for 3069 // shift of zero, fshr will return its second operand. fsl and fsr both 3070 // return rs1 so the ISD nodes need to have different operand orders. 3071 // Shift amount is in rs2. 3072 SDValue Op0 = Op.getOperand(0); 3073 SDValue Op1 = Op.getOperand(1); 3074 unsigned Opc = RISCVISD::FSL; 3075 if (Op.getOpcode() == ISD::FSHR) { 3076 std::swap(Op0, Op1); 3077 Opc = RISCVISD::FSR; 3078 } 3079 return DAG.getNode(Opc, DL, VT, Op0, Op1, ShAmt); 3080 } 3081 case ISD::TRUNCATE: 3082 // Only custom-lower vector truncates 3083 if (!Op.getSimpleValueType().isVector()) 3084 return Op; 3085 return lowerVectorTruncLike(Op, DAG); 3086 case ISD::ANY_EXTEND: 3087 case ISD::ZERO_EXTEND: 3088 if (Op.getOperand(0).getValueType().isVector() && 3089 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3090 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1); 3091 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL); 3092 case ISD::SIGN_EXTEND: 3093 if (Op.getOperand(0).getValueType().isVector() && 3094 Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3095 return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1); 3096 return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL); 3097 case ISD::SPLAT_VECTOR_PARTS: 3098 return lowerSPLAT_VECTOR_PARTS(Op, DAG); 3099 case ISD::INSERT_VECTOR_ELT: 3100 return lowerINSERT_VECTOR_ELT(Op, DAG); 3101 case ISD::EXTRACT_VECTOR_ELT: 3102 return lowerEXTRACT_VECTOR_ELT(Op, DAG); 3103 case ISD::VSCALE: { 3104 MVT VT = Op.getSimpleValueType(); 3105 SDLoc DL(Op); 3106 SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT); 3107 // We define our scalable vector types for lmul=1 to use a 64 bit known 3108 // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate 3109 // vscale as VLENB / 8. 3110 static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!"); 3111 if (Subtarget.getMinVLen() < RISCV::RVVBitsPerBlock) 3112 report_fatal_error("Support for VLEN==32 is incomplete."); 3113 // We assume VLENB is a multiple of 8. We manually choose the best shift 3114 // here because SimplifyDemandedBits isn't always able to simplify it. 3115 uint64_t Val = Op.getConstantOperandVal(0); 3116 if (isPowerOf2_64(Val)) { 3117 uint64_t Log2 = Log2_64(Val); 3118 if (Log2 < 3) 3119 return DAG.getNode(ISD::SRL, DL, VT, VLENB, 3120 DAG.getConstant(3 - Log2, DL, VT)); 3121 if (Log2 > 3) 3122 return DAG.getNode(ISD::SHL, DL, VT, VLENB, 3123 DAG.getConstant(Log2 - 3, DL, VT)); 3124 return VLENB; 3125 } 3126 // If the multiplier is a multiple of 8, scale it down to avoid needing 3127 // to shift the VLENB value. 3128 if ((Val % 8) == 0) 3129 return DAG.getNode(ISD::MUL, DL, VT, VLENB, 3130 DAG.getConstant(Val / 8, DL, VT)); 3131 3132 SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB, 3133 DAG.getConstant(3, DL, VT)); 3134 return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0)); 3135 } 3136 case ISD::FPOWI: { 3137 // Custom promote f16 powi with illegal i32 integer type on RV64. Once 3138 // promoted this will be legalized into a libcall by LegalizeIntegerTypes. 3139 if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() && 3140 Op.getOperand(1).getValueType() == MVT::i32) { 3141 SDLoc DL(Op); 3142 SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0)); 3143 SDValue Powi = 3144 DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1)); 3145 return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi, 3146 DAG.getIntPtrConstant(0, DL)); 3147 } 3148 return SDValue(); 3149 } 3150 case ISD::FP_EXTEND: 3151 case ISD::FP_ROUND: 3152 if (!Op.getValueType().isVector()) 3153 return Op; 3154 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3155 case ISD::FP_TO_SINT: 3156 case ISD::FP_TO_UINT: 3157 case ISD::SINT_TO_FP: 3158 case ISD::UINT_TO_FP: { 3159 // RVV can only do fp<->int conversions to types half/double the size as 3160 // the source. We custom-lower any conversions that do two hops into 3161 // sequences. 3162 MVT VT = Op.getSimpleValueType(); 3163 if (!VT.isVector()) 3164 return Op; 3165 SDLoc DL(Op); 3166 SDValue Src = Op.getOperand(0); 3167 MVT EltVT = VT.getVectorElementType(); 3168 MVT SrcVT = Src.getSimpleValueType(); 3169 MVT SrcEltVT = SrcVT.getVectorElementType(); 3170 unsigned EltSize = EltVT.getSizeInBits(); 3171 unsigned SrcEltSize = SrcEltVT.getSizeInBits(); 3172 assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) && 3173 "Unexpected vector element types"); 3174 3175 bool IsInt2FP = SrcEltVT.isInteger(); 3176 // Widening conversions 3177 if (EltSize > (2 * SrcEltSize)) { 3178 if (IsInt2FP) { 3179 // Do a regular integer sign/zero extension then convert to float. 3180 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), 3181 VT.getVectorElementCount()); 3182 unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP 3183 ? ISD::ZERO_EXTEND 3184 : ISD::SIGN_EXTEND; 3185 SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src); 3186 return DAG.getNode(Op.getOpcode(), DL, VT, Ext); 3187 } 3188 // FP2Int 3189 assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering"); 3190 // Do one doubling fp_extend then complete the operation by converting 3191 // to int. 3192 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3193 SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT); 3194 return DAG.getNode(Op.getOpcode(), DL, VT, FExt); 3195 } 3196 3197 // Narrowing conversions 3198 if (SrcEltSize > (2 * EltSize)) { 3199 if (IsInt2FP) { 3200 // One narrowing int_to_fp, then an fp_round. 3201 assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering"); 3202 MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount()); 3203 SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src); 3204 return DAG.getFPExtendOrRound(Int2FP, DL, VT); 3205 } 3206 // FP2Int 3207 // One narrowing fp_to_int, then truncate the integer. If the float isn't 3208 // representable by the integer, the result is poison. 3209 MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 3210 VT.getVectorElementCount()); 3211 SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src); 3212 return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int); 3213 } 3214 3215 // Scalable vectors can exit here. Patterns will handle equally-sized 3216 // conversions halving/doubling ones. 3217 if (!VT.isFixedLengthVector()) 3218 return Op; 3219 3220 // For fixed-length vectors we lower to a custom "VL" node. 3221 unsigned RVVOpc = 0; 3222 switch (Op.getOpcode()) { 3223 default: 3224 llvm_unreachable("Impossible opcode"); 3225 case ISD::FP_TO_SINT: 3226 RVVOpc = RISCVISD::FP_TO_SINT_VL; 3227 break; 3228 case ISD::FP_TO_UINT: 3229 RVVOpc = RISCVISD::FP_TO_UINT_VL; 3230 break; 3231 case ISD::SINT_TO_FP: 3232 RVVOpc = RISCVISD::SINT_TO_FP_VL; 3233 break; 3234 case ISD::UINT_TO_FP: 3235 RVVOpc = RISCVISD::UINT_TO_FP_VL; 3236 break; 3237 } 3238 3239 MVT ContainerVT, SrcContainerVT; 3240 // Derive the reference container type from the larger vector type. 3241 if (SrcEltSize > EltSize) { 3242 SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 3243 ContainerVT = 3244 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 3245 } else { 3246 ContainerVT = getContainerForFixedLengthVector(VT); 3247 SrcContainerVT = ContainerVT.changeVectorElementType(SrcEltVT); 3248 } 3249 3250 SDValue Mask, VL; 3251 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 3252 3253 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 3254 Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL); 3255 return convertFromScalableVector(VT, Src, DAG, Subtarget); 3256 } 3257 case ISD::FP_TO_SINT_SAT: 3258 case ISD::FP_TO_UINT_SAT: 3259 return lowerFP_TO_INT_SAT(Op, DAG, Subtarget); 3260 case ISD::FTRUNC: 3261 case ISD::FCEIL: 3262 case ISD::FFLOOR: 3263 return lowerFTRUNC_FCEIL_FFLOOR(Op, DAG); 3264 case ISD::FROUND: 3265 return lowerFROUND(Op, DAG); 3266 case ISD::VECREDUCE_ADD: 3267 case ISD::VECREDUCE_UMAX: 3268 case ISD::VECREDUCE_SMAX: 3269 case ISD::VECREDUCE_UMIN: 3270 case ISD::VECREDUCE_SMIN: 3271 return lowerVECREDUCE(Op, DAG); 3272 case ISD::VECREDUCE_AND: 3273 case ISD::VECREDUCE_OR: 3274 case ISD::VECREDUCE_XOR: 3275 if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1) 3276 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false); 3277 return lowerVECREDUCE(Op, DAG); 3278 case ISD::VECREDUCE_FADD: 3279 case ISD::VECREDUCE_SEQ_FADD: 3280 case ISD::VECREDUCE_FMIN: 3281 case ISD::VECREDUCE_FMAX: 3282 return lowerFPVECREDUCE(Op, DAG); 3283 case ISD::VP_REDUCE_ADD: 3284 case ISD::VP_REDUCE_UMAX: 3285 case ISD::VP_REDUCE_SMAX: 3286 case ISD::VP_REDUCE_UMIN: 3287 case ISD::VP_REDUCE_SMIN: 3288 case ISD::VP_REDUCE_FADD: 3289 case ISD::VP_REDUCE_SEQ_FADD: 3290 case ISD::VP_REDUCE_FMIN: 3291 case ISD::VP_REDUCE_FMAX: 3292 return lowerVPREDUCE(Op, DAG); 3293 case ISD::VP_REDUCE_AND: 3294 case ISD::VP_REDUCE_OR: 3295 case ISD::VP_REDUCE_XOR: 3296 if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1) 3297 return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true); 3298 return lowerVPREDUCE(Op, DAG); 3299 case ISD::INSERT_SUBVECTOR: 3300 return lowerINSERT_SUBVECTOR(Op, DAG); 3301 case ISD::EXTRACT_SUBVECTOR: 3302 return lowerEXTRACT_SUBVECTOR(Op, DAG); 3303 case ISD::STEP_VECTOR: 3304 return lowerSTEP_VECTOR(Op, DAG); 3305 case ISD::VECTOR_REVERSE: 3306 return lowerVECTOR_REVERSE(Op, DAG); 3307 case ISD::VECTOR_SPLICE: 3308 return lowerVECTOR_SPLICE(Op, DAG); 3309 case ISD::BUILD_VECTOR: 3310 return lowerBUILD_VECTOR(Op, DAG, Subtarget); 3311 case ISD::SPLAT_VECTOR: 3312 if (Op.getValueType().getVectorElementType() == MVT::i1) 3313 return lowerVectorMaskSplat(Op, DAG); 3314 return SDValue(); 3315 case ISD::VECTOR_SHUFFLE: 3316 return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget); 3317 case ISD::CONCAT_VECTORS: { 3318 // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is 3319 // better than going through the stack, as the default expansion does. 3320 SDLoc DL(Op); 3321 MVT VT = Op.getSimpleValueType(); 3322 unsigned NumOpElts = 3323 Op.getOperand(0).getSimpleValueType().getVectorMinNumElements(); 3324 SDValue Vec = DAG.getUNDEF(VT); 3325 for (const auto &OpIdx : enumerate(Op->ops())) { 3326 SDValue SubVec = OpIdx.value(); 3327 // Don't insert undef subvectors. 3328 if (SubVec.isUndef()) 3329 continue; 3330 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec, 3331 DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL)); 3332 } 3333 return Vec; 3334 } 3335 case ISD::LOAD: 3336 if (auto V = expandUnalignedRVVLoad(Op, DAG)) 3337 return V; 3338 if (Op.getValueType().isFixedLengthVector()) 3339 return lowerFixedLengthVectorLoadToRVV(Op, DAG); 3340 return Op; 3341 case ISD::STORE: 3342 if (auto V = expandUnalignedRVVStore(Op, DAG)) 3343 return V; 3344 if (Op.getOperand(1).getValueType().isFixedLengthVector()) 3345 return lowerFixedLengthVectorStoreToRVV(Op, DAG); 3346 return Op; 3347 case ISD::MLOAD: 3348 case ISD::VP_LOAD: 3349 return lowerMaskedLoad(Op, DAG); 3350 case ISD::MSTORE: 3351 case ISD::VP_STORE: 3352 return lowerMaskedStore(Op, DAG); 3353 case ISD::SETCC: 3354 return lowerFixedLengthVectorSetccToRVV(Op, DAG); 3355 case ISD::ADD: 3356 return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL); 3357 case ISD::SUB: 3358 return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL); 3359 case ISD::MUL: 3360 return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL); 3361 case ISD::MULHS: 3362 return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL); 3363 case ISD::MULHU: 3364 return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL); 3365 case ISD::AND: 3366 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL, 3367 RISCVISD::AND_VL); 3368 case ISD::OR: 3369 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL, 3370 RISCVISD::OR_VL); 3371 case ISD::XOR: 3372 return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL, 3373 RISCVISD::XOR_VL); 3374 case ISD::SDIV: 3375 return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL); 3376 case ISD::SREM: 3377 return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL); 3378 case ISD::UDIV: 3379 return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL); 3380 case ISD::UREM: 3381 return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL); 3382 case ISD::SHL: 3383 case ISD::SRA: 3384 case ISD::SRL: 3385 if (Op.getSimpleValueType().isFixedLengthVector()) 3386 return lowerFixedLengthVectorShiftToRVV(Op, DAG); 3387 // This can be called for an i32 shift amount that needs to be promoted. 3388 assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() && 3389 "Unexpected custom legalisation"); 3390 return SDValue(); 3391 case ISD::SADDSAT: 3392 return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL); 3393 case ISD::UADDSAT: 3394 return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL); 3395 case ISD::SSUBSAT: 3396 return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL); 3397 case ISD::USUBSAT: 3398 return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL); 3399 case ISD::FADD: 3400 return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL); 3401 case ISD::FSUB: 3402 return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL); 3403 case ISD::FMUL: 3404 return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL); 3405 case ISD::FDIV: 3406 return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL); 3407 case ISD::FNEG: 3408 return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL); 3409 case ISD::FABS: 3410 return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL); 3411 case ISD::FSQRT: 3412 return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL); 3413 case ISD::FMA: 3414 return lowerToScalableOp(Op, DAG, RISCVISD::FMA_VL); 3415 case ISD::SMIN: 3416 return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL); 3417 case ISD::SMAX: 3418 return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL); 3419 case ISD::UMIN: 3420 return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL); 3421 case ISD::UMAX: 3422 return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL); 3423 case ISD::FMINNUM: 3424 return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL); 3425 case ISD::FMAXNUM: 3426 return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL); 3427 case ISD::ABS: 3428 return lowerABS(Op, DAG); 3429 case ISD::CTLZ_ZERO_UNDEF: 3430 case ISD::CTTZ_ZERO_UNDEF: 3431 return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG); 3432 case ISD::VSELECT: 3433 return lowerFixedLengthVectorSelectToRVV(Op, DAG); 3434 case ISD::FCOPYSIGN: 3435 return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG); 3436 case ISD::MGATHER: 3437 case ISD::VP_GATHER: 3438 return lowerMaskedGather(Op, DAG); 3439 case ISD::MSCATTER: 3440 case ISD::VP_SCATTER: 3441 return lowerMaskedScatter(Op, DAG); 3442 case ISD::FLT_ROUNDS_: 3443 return lowerGET_ROUNDING(Op, DAG); 3444 case ISD::SET_ROUNDING: 3445 return lowerSET_ROUNDING(Op, DAG); 3446 case ISD::VP_SELECT: 3447 return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL); 3448 case ISD::VP_MERGE: 3449 return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL); 3450 case ISD::VP_ADD: 3451 return lowerVPOp(Op, DAG, RISCVISD::ADD_VL); 3452 case ISD::VP_SUB: 3453 return lowerVPOp(Op, DAG, RISCVISD::SUB_VL); 3454 case ISD::VP_MUL: 3455 return lowerVPOp(Op, DAG, RISCVISD::MUL_VL); 3456 case ISD::VP_SDIV: 3457 return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL); 3458 case ISD::VP_UDIV: 3459 return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL); 3460 case ISD::VP_SREM: 3461 return lowerVPOp(Op, DAG, RISCVISD::SREM_VL); 3462 case ISD::VP_UREM: 3463 return lowerVPOp(Op, DAG, RISCVISD::UREM_VL); 3464 case ISD::VP_AND: 3465 return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL); 3466 case ISD::VP_OR: 3467 return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL); 3468 case ISD::VP_XOR: 3469 return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL); 3470 case ISD::VP_ASHR: 3471 return lowerVPOp(Op, DAG, RISCVISD::SRA_VL); 3472 case ISD::VP_LSHR: 3473 return lowerVPOp(Op, DAG, RISCVISD::SRL_VL); 3474 case ISD::VP_SHL: 3475 return lowerVPOp(Op, DAG, RISCVISD::SHL_VL); 3476 case ISD::VP_FADD: 3477 return lowerVPOp(Op, DAG, RISCVISD::FADD_VL); 3478 case ISD::VP_FSUB: 3479 return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL); 3480 case ISD::VP_FMUL: 3481 return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL); 3482 case ISD::VP_FDIV: 3483 return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL); 3484 case ISD::VP_FNEG: 3485 return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL); 3486 case ISD::VP_FMA: 3487 return lowerVPOp(Op, DAG, RISCVISD::FMA_VL); 3488 case ISD::VP_SIGN_EXTEND: 3489 case ISD::VP_ZERO_EXTEND: 3490 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3491 return lowerVPExtMaskOp(Op, DAG); 3492 return lowerVPOp(Op, DAG, 3493 Op.getOpcode() == ISD::VP_SIGN_EXTEND 3494 ? RISCVISD::VSEXT_VL 3495 : RISCVISD::VZEXT_VL); 3496 case ISD::VP_TRUNCATE: 3497 return lowerVectorTruncLike(Op, DAG); 3498 case ISD::VP_FP_EXTEND: 3499 case ISD::VP_FP_ROUND: 3500 return lowerVectorFPExtendOrRoundLike(Op, DAG); 3501 case ISD::VP_FPTOSI: 3502 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_SINT_VL); 3503 case ISD::VP_FPTOUI: 3504 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::FP_TO_UINT_VL); 3505 case ISD::VP_SITOFP: 3506 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL); 3507 case ISD::VP_UITOFP: 3508 return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL); 3509 case ISD::VP_SETCC: 3510 if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1) 3511 return lowerVPSetCCMaskOp(Op, DAG); 3512 return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL); 3513 } 3514 } 3515 3516 static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty, 3517 SelectionDAG &DAG, unsigned Flags) { 3518 return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags); 3519 } 3520 3521 static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty, 3522 SelectionDAG &DAG, unsigned Flags) { 3523 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(), 3524 Flags); 3525 } 3526 3527 static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty, 3528 SelectionDAG &DAG, unsigned Flags) { 3529 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(), 3530 N->getOffset(), Flags); 3531 } 3532 3533 static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty, 3534 SelectionDAG &DAG, unsigned Flags) { 3535 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags); 3536 } 3537 3538 template <class NodeTy> 3539 SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG, 3540 bool IsLocal) const { 3541 SDLoc DL(N); 3542 EVT Ty = getPointerTy(DAG.getDataLayout()); 3543 3544 if (isPositionIndependent()) { 3545 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3546 if (IsLocal) 3547 // Use PC-relative addressing to access the symbol. This generates the 3548 // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym)) 3549 // %pcrel_lo(auipc)). 3550 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3551 3552 // Use PC-relative addressing to access the GOT for this symbol, then load 3553 // the address from the GOT. This generates the pattern (PseudoLA sym), 3554 // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))). 3555 SDValue Load = 3556 SDValue(DAG.getMachineNode(RISCV::PseudoLA, DL, Ty, Addr), 0); 3557 MachineFunction &MF = DAG.getMachineFunction(); 3558 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3559 MachinePointerInfo::getGOT(MF), 3560 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3561 MachineMemOperand::MOInvariant, 3562 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3563 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3564 return Load; 3565 } 3566 3567 switch (getTargetMachine().getCodeModel()) { 3568 default: 3569 report_fatal_error("Unsupported code model for lowering"); 3570 case CodeModel::Small: { 3571 // Generate a sequence for accessing addresses within the first 2 GiB of 3572 // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)). 3573 SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI); 3574 SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO); 3575 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3576 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNHi, AddrLo), 0); 3577 } 3578 case CodeModel::Medium: { 3579 // Generate a sequence for accessing addresses within any 2GiB range within 3580 // the address space. This generates the pattern (PseudoLLA sym), which 3581 // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)). 3582 SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0); 3583 return SDValue(DAG.getMachineNode(RISCV::PseudoLLA, DL, Ty, Addr), 0); 3584 } 3585 } 3586 } 3587 3588 template SDValue RISCVTargetLowering::getAddr<GlobalAddressSDNode>( 3589 GlobalAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3590 template SDValue RISCVTargetLowering::getAddr<BlockAddressSDNode>( 3591 BlockAddressSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3592 template SDValue RISCVTargetLowering::getAddr<ConstantPoolSDNode>( 3593 ConstantPoolSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3594 template SDValue RISCVTargetLowering::getAddr<JumpTableSDNode>( 3595 JumpTableSDNode *N, SelectionDAG &DAG, bool IsLocal) const; 3596 3597 SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op, 3598 SelectionDAG &DAG) const { 3599 SDLoc DL(Op); 3600 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3601 assert(N->getOffset() == 0 && "unexpected offset in global node"); 3602 3603 const GlobalValue *GV = N->getGlobal(); 3604 bool IsLocal = getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV); 3605 return getAddr(N, DAG, IsLocal); 3606 } 3607 3608 SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op, 3609 SelectionDAG &DAG) const { 3610 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op); 3611 3612 return getAddr(N, DAG); 3613 } 3614 3615 SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op, 3616 SelectionDAG &DAG) const { 3617 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op); 3618 3619 return getAddr(N, DAG); 3620 } 3621 3622 SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op, 3623 SelectionDAG &DAG) const { 3624 JumpTableSDNode *N = cast<JumpTableSDNode>(Op); 3625 3626 return getAddr(N, DAG); 3627 } 3628 3629 SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N, 3630 SelectionDAG &DAG, 3631 bool UseGOT) const { 3632 SDLoc DL(N); 3633 EVT Ty = getPointerTy(DAG.getDataLayout()); 3634 const GlobalValue *GV = N->getGlobal(); 3635 MVT XLenVT = Subtarget.getXLenVT(); 3636 3637 if (UseGOT) { 3638 // Use PC-relative addressing to access the GOT for this TLS symbol, then 3639 // load the address from the GOT and add the thread pointer. This generates 3640 // the pattern (PseudoLA_TLS_IE sym), which expands to 3641 // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)). 3642 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3643 SDValue Load = 3644 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_IE, DL, Ty, Addr), 0); 3645 MachineFunction &MF = DAG.getMachineFunction(); 3646 MachineMemOperand *MemOp = MF.getMachineMemOperand( 3647 MachinePointerInfo::getGOT(MF), 3648 MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable | 3649 MachineMemOperand::MOInvariant, 3650 LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8)); 3651 DAG.setNodeMemRefs(cast<MachineSDNode>(Load.getNode()), {MemOp}); 3652 3653 // Add the thread pointer. 3654 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3655 return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg); 3656 } 3657 3658 // Generate a sequence for accessing the address relative to the thread 3659 // pointer, with the appropriate adjustment for the thread pointer offset. 3660 // This generates the pattern 3661 // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym)) 3662 SDValue AddrHi = 3663 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI); 3664 SDValue AddrAdd = 3665 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD); 3666 SDValue AddrLo = 3667 DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO); 3668 3669 SDValue MNHi = SDValue(DAG.getMachineNode(RISCV::LUI, DL, Ty, AddrHi), 0); 3670 SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT); 3671 SDValue MNAdd = SDValue( 3672 DAG.getMachineNode(RISCV::PseudoAddTPRel, DL, Ty, MNHi, TPReg, AddrAdd), 3673 0); 3674 return SDValue(DAG.getMachineNode(RISCV::ADDI, DL, Ty, MNAdd, AddrLo), 0); 3675 } 3676 3677 SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N, 3678 SelectionDAG &DAG) const { 3679 SDLoc DL(N); 3680 EVT Ty = getPointerTy(DAG.getDataLayout()); 3681 IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits()); 3682 const GlobalValue *GV = N->getGlobal(); 3683 3684 // Use a PC-relative addressing mode to access the global dynamic GOT address. 3685 // This generates the pattern (PseudoLA_TLS_GD sym), which expands to 3686 // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)). 3687 SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0); 3688 SDValue Load = 3689 SDValue(DAG.getMachineNode(RISCV::PseudoLA_TLS_GD, DL, Ty, Addr), 0); 3690 3691 // Prepare argument list to generate call. 3692 ArgListTy Args; 3693 ArgListEntry Entry; 3694 Entry.Node = Load; 3695 Entry.Ty = CallTy; 3696 Args.push_back(Entry); 3697 3698 // Setup call to __tls_get_addr. 3699 TargetLowering::CallLoweringInfo CLI(DAG); 3700 CLI.setDebugLoc(DL) 3701 .setChain(DAG.getEntryNode()) 3702 .setLibCallee(CallingConv::C, CallTy, 3703 DAG.getExternalSymbol("__tls_get_addr", Ty), 3704 std::move(Args)); 3705 3706 return LowerCallTo(CLI).first; 3707 } 3708 3709 SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op, 3710 SelectionDAG &DAG) const { 3711 SDLoc DL(Op); 3712 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op); 3713 assert(N->getOffset() == 0 && "unexpected offset in global node"); 3714 3715 TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal()); 3716 3717 if (DAG.getMachineFunction().getFunction().getCallingConv() == 3718 CallingConv::GHC) 3719 report_fatal_error("In GHC calling convention TLS is not supported"); 3720 3721 SDValue Addr; 3722 switch (Model) { 3723 case TLSModel::LocalExec: 3724 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false); 3725 break; 3726 case TLSModel::InitialExec: 3727 Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true); 3728 break; 3729 case TLSModel::LocalDynamic: 3730 case TLSModel::GeneralDynamic: 3731 Addr = getDynamicTLSAddr(N, DAG); 3732 break; 3733 } 3734 3735 return Addr; 3736 } 3737 3738 SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const { 3739 SDValue CondV = Op.getOperand(0); 3740 SDValue TrueV = Op.getOperand(1); 3741 SDValue FalseV = Op.getOperand(2); 3742 SDLoc DL(Op); 3743 MVT VT = Op.getSimpleValueType(); 3744 MVT XLenVT = Subtarget.getXLenVT(); 3745 3746 // Lower vector SELECTs to VSELECTs by splatting the condition. 3747 if (VT.isVector()) { 3748 MVT SplatCondVT = VT.changeVectorElementType(MVT::i1); 3749 SDValue CondSplat = VT.isScalableVector() 3750 ? DAG.getSplatVector(SplatCondVT, DL, CondV) 3751 : DAG.getSplatBuildVector(SplatCondVT, DL, CondV); 3752 return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV); 3753 } 3754 3755 // If the result type is XLenVT and CondV is the output of a SETCC node 3756 // which also operated on XLenVT inputs, then merge the SETCC node into the 3757 // lowered RISCVISD::SELECT_CC to take advantage of the integer 3758 // compare+branch instructions. i.e.: 3759 // (select (setcc lhs, rhs, cc), truev, falsev) 3760 // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev) 3761 if (VT == XLenVT && CondV.getOpcode() == ISD::SETCC && 3762 CondV.getOperand(0).getSimpleValueType() == XLenVT) { 3763 SDValue LHS = CondV.getOperand(0); 3764 SDValue RHS = CondV.getOperand(1); 3765 const auto *CC = cast<CondCodeSDNode>(CondV.getOperand(2)); 3766 ISD::CondCode CCVal = CC->get(); 3767 3768 // Special case for a select of 2 constants that have a diffence of 1. 3769 // Normally this is done by DAGCombine, but if the select is introduced by 3770 // type legalization or op legalization, we miss it. Restricting to SETLT 3771 // case for now because that is what signed saturating add/sub need. 3772 // FIXME: We don't need the condition to be SETLT or even a SETCC, 3773 // but we would probably want to swap the true/false values if the condition 3774 // is SETGE/SETLE to avoid an XORI. 3775 if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) && 3776 CCVal == ISD::SETLT) { 3777 const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue(); 3778 const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue(); 3779 if (TrueVal - 1 == FalseVal) 3780 return DAG.getNode(ISD::ADD, DL, Op.getValueType(), CondV, FalseV); 3781 if (TrueVal + 1 == FalseVal) 3782 return DAG.getNode(ISD::SUB, DL, Op.getValueType(), FalseV, CondV); 3783 } 3784 3785 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3786 3787 SDValue TargetCC = DAG.getCondCode(CCVal); 3788 SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV}; 3789 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3790 } 3791 3792 // Otherwise: 3793 // (select condv, truev, falsev) 3794 // -> (riscvisd::select_cc condv, zero, setne, truev, falsev) 3795 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 3796 SDValue SetNE = DAG.getCondCode(ISD::SETNE); 3797 3798 SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV}; 3799 3800 return DAG.getNode(RISCVISD::SELECT_CC, DL, Op.getValueType(), Ops); 3801 } 3802 3803 SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const { 3804 SDValue CondV = Op.getOperand(1); 3805 SDLoc DL(Op); 3806 MVT XLenVT = Subtarget.getXLenVT(); 3807 3808 if (CondV.getOpcode() == ISD::SETCC && 3809 CondV.getOperand(0).getValueType() == XLenVT) { 3810 SDValue LHS = CondV.getOperand(0); 3811 SDValue RHS = CondV.getOperand(1); 3812 ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get(); 3813 3814 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 3815 3816 SDValue TargetCC = DAG.getCondCode(CCVal); 3817 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3818 LHS, RHS, TargetCC, Op.getOperand(2)); 3819 } 3820 3821 return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0), 3822 CondV, DAG.getConstant(0, DL, XLenVT), 3823 DAG.getCondCode(ISD::SETNE), Op.getOperand(2)); 3824 } 3825 3826 SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const { 3827 MachineFunction &MF = DAG.getMachineFunction(); 3828 RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>(); 3829 3830 SDLoc DL(Op); 3831 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), 3832 getPointerTy(MF.getDataLayout())); 3833 3834 // vastart just stores the address of the VarArgsFrameIndex slot into the 3835 // memory location argument. 3836 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue(); 3837 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1), 3838 MachinePointerInfo(SV)); 3839 } 3840 3841 SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op, 3842 SelectionDAG &DAG) const { 3843 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3844 MachineFunction &MF = DAG.getMachineFunction(); 3845 MachineFrameInfo &MFI = MF.getFrameInfo(); 3846 MFI.setFrameAddressIsTaken(true); 3847 Register FrameReg = RI.getFrameRegister(MF); 3848 int XLenInBytes = Subtarget.getXLen() / 8; 3849 3850 EVT VT = Op.getValueType(); 3851 SDLoc DL(Op); 3852 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT); 3853 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3854 while (Depth--) { 3855 int Offset = -(XLenInBytes * 2); 3856 SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr, 3857 DAG.getIntPtrConstant(Offset, DL)); 3858 FrameAddr = 3859 DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo()); 3860 } 3861 return FrameAddr; 3862 } 3863 3864 SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op, 3865 SelectionDAG &DAG) const { 3866 const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo(); 3867 MachineFunction &MF = DAG.getMachineFunction(); 3868 MachineFrameInfo &MFI = MF.getFrameInfo(); 3869 MFI.setReturnAddressIsTaken(true); 3870 MVT XLenVT = Subtarget.getXLenVT(); 3871 int XLenInBytes = Subtarget.getXLen() / 8; 3872 3873 if (verifyReturnAddressArgumentIsConstant(Op, DAG)) 3874 return SDValue(); 3875 3876 EVT VT = Op.getValueType(); 3877 SDLoc DL(Op); 3878 unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue(); 3879 if (Depth) { 3880 int Off = -XLenInBytes; 3881 SDValue FrameAddr = lowerFRAMEADDR(Op, DAG); 3882 SDValue Offset = DAG.getConstant(Off, DL, VT); 3883 return DAG.getLoad(VT, DL, DAG.getEntryNode(), 3884 DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), 3885 MachinePointerInfo()); 3886 } 3887 3888 // Return the value of the return address register, marking it an implicit 3889 // live-in. 3890 Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT)); 3891 return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT); 3892 } 3893 3894 SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op, 3895 SelectionDAG &DAG) const { 3896 SDLoc DL(Op); 3897 SDValue Lo = Op.getOperand(0); 3898 SDValue Hi = Op.getOperand(1); 3899 SDValue Shamt = Op.getOperand(2); 3900 EVT VT = Lo.getValueType(); 3901 3902 // if Shamt-XLEN < 0: // Shamt < XLEN 3903 // Lo = Lo << Shamt 3904 // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt)) 3905 // else: 3906 // Lo = 0 3907 // Hi = Lo << (Shamt-XLEN) 3908 3909 SDValue Zero = DAG.getConstant(0, DL, VT); 3910 SDValue One = DAG.getConstant(1, DL, VT); 3911 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3912 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3913 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3914 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 3915 3916 SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt); 3917 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One); 3918 SDValue ShiftRightLo = 3919 DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt); 3920 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt); 3921 SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo); 3922 SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen); 3923 3924 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3925 3926 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero); 3927 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3928 3929 SDValue Parts[2] = {Lo, Hi}; 3930 return DAG.getMergeValues(Parts, DL); 3931 } 3932 3933 SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG, 3934 bool IsSRA) const { 3935 SDLoc DL(Op); 3936 SDValue Lo = Op.getOperand(0); 3937 SDValue Hi = Op.getOperand(1); 3938 SDValue Shamt = Op.getOperand(2); 3939 EVT VT = Lo.getValueType(); 3940 3941 // SRA expansion: 3942 // if Shamt-XLEN < 0: // Shamt < XLEN 3943 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 3944 // Hi = Hi >>s Shamt 3945 // else: 3946 // Lo = Hi >>s (Shamt-XLEN); 3947 // Hi = Hi >>s (XLEN-1) 3948 // 3949 // SRL expansion: 3950 // if Shamt-XLEN < 0: // Shamt < XLEN 3951 // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1)) 3952 // Hi = Hi >>u Shamt 3953 // else: 3954 // Lo = Hi >>u (Shamt-XLEN); 3955 // Hi = 0; 3956 3957 unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL; 3958 3959 SDValue Zero = DAG.getConstant(0, DL, VT); 3960 SDValue One = DAG.getConstant(1, DL, VT); 3961 SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT); 3962 SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT); 3963 SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen); 3964 SDValue XLenMinus1Shamt = DAG.getNode(ISD::XOR, DL, VT, Shamt, XLenMinus1); 3965 3966 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt); 3967 SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One); 3968 SDValue ShiftLeftHi = 3969 DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt); 3970 SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi); 3971 SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt); 3972 SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen); 3973 SDValue HiFalse = 3974 IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero; 3975 3976 SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT); 3977 3978 Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse); 3979 Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse); 3980 3981 SDValue Parts[2] = {Lo, Hi}; 3982 return DAG.getMergeValues(Parts, DL); 3983 } 3984 3985 // Lower splats of i1 types to SETCC. For each mask vector type, we have a 3986 // legal equivalently-sized i8 type, so we can use that as a go-between. 3987 SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op, 3988 SelectionDAG &DAG) const { 3989 SDLoc DL(Op); 3990 MVT VT = Op.getSimpleValueType(); 3991 SDValue SplatVal = Op.getOperand(0); 3992 // All-zeros or all-ones splats are handled specially. 3993 if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) { 3994 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3995 return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL); 3996 } 3997 if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) { 3998 SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second; 3999 return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL); 4000 } 4001 MVT XLenVT = Subtarget.getXLenVT(); 4002 assert(SplatVal.getValueType() == XLenVT && 4003 "Unexpected type for i1 splat value"); 4004 MVT InterVT = VT.changeVectorElementType(MVT::i8); 4005 SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal, 4006 DAG.getConstant(1, DL, XLenVT)); 4007 SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal); 4008 SDValue Zero = DAG.getConstant(0, DL, InterVT); 4009 return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE); 4010 } 4011 4012 // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is 4013 // illegal (currently only vXi64 RV32). 4014 // FIXME: We could also catch non-constant sign-extended i32 values and lower 4015 // them to VMV_V_X_VL. 4016 SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op, 4017 SelectionDAG &DAG) const { 4018 SDLoc DL(Op); 4019 MVT VecVT = Op.getSimpleValueType(); 4020 assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 && 4021 "Unexpected SPLAT_VECTOR_PARTS lowering"); 4022 4023 assert(Op.getNumOperands() == 2 && "Unexpected number of operands!"); 4024 SDValue Lo = Op.getOperand(0); 4025 SDValue Hi = Op.getOperand(1); 4026 4027 if (VecVT.isFixedLengthVector()) { 4028 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4029 SDLoc DL(Op); 4030 SDValue Mask, VL; 4031 std::tie(Mask, VL) = 4032 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4033 4034 SDValue Res = 4035 splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG); 4036 return convertFromScalableVector(VecVT, Res, DAG, Subtarget); 4037 } 4038 4039 if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) { 4040 int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue(); 4041 int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue(); 4042 // If Hi constant is all the same sign bit as Lo, lower this as a custom 4043 // node in order to try and match RVV vector/scalar instructions. 4044 if ((LoC >> 31) == HiC) 4045 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 4046 Lo, DAG.getRegister(RISCV::X0, MVT::i32)); 4047 } 4048 4049 // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended. 4050 if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo && 4051 isa<ConstantSDNode>(Hi.getOperand(1)) && 4052 Hi.getConstantOperandVal(1) == 31) 4053 return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo, 4054 DAG.getRegister(RISCV::X0, MVT::i32)); 4055 4056 // Fall back to use a stack store and stride x0 vector load. Use X0 as VL. 4057 return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT, 4058 DAG.getUNDEF(VecVT), Lo, Hi, 4059 DAG.getRegister(RISCV::X0, MVT::i32)); 4060 } 4061 4062 // Custom-lower extensions from mask vectors by using a vselect either with 1 4063 // for zero/any-extension or -1 for sign-extension: 4064 // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0) 4065 // Note that any-extension is lowered identically to zero-extension. 4066 SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG, 4067 int64_t ExtTrueVal) const { 4068 SDLoc DL(Op); 4069 MVT VecVT = Op.getSimpleValueType(); 4070 SDValue Src = Op.getOperand(0); 4071 // Only custom-lower extensions from mask types 4072 assert(Src.getValueType().isVector() && 4073 Src.getValueType().getVectorElementType() == MVT::i1); 4074 4075 if (VecVT.isScalableVector()) { 4076 SDValue SplatZero = DAG.getConstant(0, DL, VecVT); 4077 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT); 4078 return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero); 4079 } 4080 4081 MVT ContainerVT = getContainerForFixedLengthVector(VecVT); 4082 MVT I1ContainerVT = 4083 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 4084 4085 SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget); 4086 4087 SDValue Mask, VL; 4088 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4089 4090 MVT XLenVT = Subtarget.getXLenVT(); 4091 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 4092 SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT); 4093 4094 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4095 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4096 SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4097 DAG.getUNDEF(ContainerVT), SplatTrueVal, VL); 4098 SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, 4099 SplatTrueVal, SplatZero, VL); 4100 4101 return convertFromScalableVector(VecVT, Select, DAG, Subtarget); 4102 } 4103 4104 SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV( 4105 SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const { 4106 MVT ExtVT = Op.getSimpleValueType(); 4107 // Only custom-lower extensions from fixed-length vector types. 4108 if (!ExtVT.isFixedLengthVector()) 4109 return Op; 4110 MVT VT = Op.getOperand(0).getSimpleValueType(); 4111 // Grab the canonical container type for the extended type. Infer the smaller 4112 // type from that to ensure the same number of vector elements, as we know 4113 // the LMUL will be sufficient to hold the smaller type. 4114 MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT); 4115 // Get the extended container type manually to ensure the same number of 4116 // vector elements between source and dest. 4117 MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(), 4118 ContainerExtVT.getVectorElementCount()); 4119 4120 SDValue Op1 = 4121 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 4122 4123 SDLoc DL(Op); 4124 SDValue Mask, VL; 4125 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 4126 4127 SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL); 4128 4129 return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget); 4130 } 4131 4132 // Custom-lower truncations from vectors to mask vectors by using a mask and a 4133 // setcc operation: 4134 // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne) 4135 SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op, 4136 SelectionDAG &DAG) const { 4137 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4138 SDLoc DL(Op); 4139 EVT MaskVT = Op.getValueType(); 4140 // Only expect to custom-lower truncations to mask types 4141 assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 && 4142 "Unexpected type for vector mask lowering"); 4143 SDValue Src = Op.getOperand(0); 4144 MVT VecVT = Src.getSimpleValueType(); 4145 SDValue Mask, VL; 4146 if (IsVPTrunc) { 4147 Mask = Op.getOperand(1); 4148 VL = Op.getOperand(2); 4149 } 4150 // If this is a fixed vector, we need to convert it to a scalable vector. 4151 MVT ContainerVT = VecVT; 4152 4153 if (VecVT.isFixedLengthVector()) { 4154 ContainerVT = getContainerForFixedLengthVector(VecVT); 4155 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4156 if (IsVPTrunc) { 4157 MVT MaskContainerVT = 4158 getContainerForFixedLengthVector(Mask.getSimpleValueType()); 4159 Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget); 4160 } 4161 } 4162 4163 if (!IsVPTrunc) { 4164 std::tie(Mask, VL) = 4165 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4166 } 4167 4168 SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT()); 4169 SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT()); 4170 4171 SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4172 DAG.getUNDEF(ContainerVT), SplatOne, VL); 4173 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 4174 DAG.getUNDEF(ContainerVT), SplatZero, VL); 4175 4176 MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1); 4177 SDValue Trunc = 4178 DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne, Mask, VL); 4179 Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT, Trunc, SplatZero, 4180 DAG.getCondCode(ISD::SETNE), Mask, VL); 4181 if (MaskVT.isFixedLengthVector()) 4182 Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget); 4183 return Trunc; 4184 } 4185 4186 SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op, 4187 SelectionDAG &DAG) const { 4188 bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE; 4189 SDLoc DL(Op); 4190 4191 MVT VT = Op.getSimpleValueType(); 4192 // Only custom-lower vector truncates 4193 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4194 4195 // Truncates to mask types are handled differently 4196 if (VT.getVectorElementType() == MVT::i1) 4197 return lowerVectorMaskTruncLike(Op, DAG); 4198 4199 // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary 4200 // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which 4201 // truncate by one power of two at a time. 4202 MVT DstEltVT = VT.getVectorElementType(); 4203 4204 SDValue Src = Op.getOperand(0); 4205 MVT SrcVT = Src.getSimpleValueType(); 4206 MVT SrcEltVT = SrcVT.getVectorElementType(); 4207 4208 assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) && 4209 isPowerOf2_64(SrcEltVT.getSizeInBits()) && 4210 "Unexpected vector truncate lowering"); 4211 4212 MVT ContainerVT = SrcVT; 4213 SDValue Mask, VL; 4214 if (IsVPTrunc) { 4215 Mask = Op.getOperand(1); 4216 VL = Op.getOperand(2); 4217 } 4218 if (SrcVT.isFixedLengthVector()) { 4219 ContainerVT = getContainerForFixedLengthVector(SrcVT); 4220 Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget); 4221 if (IsVPTrunc) { 4222 MVT MaskVT = getMaskTypeFor(ContainerVT); 4223 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4224 } 4225 } 4226 4227 SDValue Result = Src; 4228 if (!IsVPTrunc) { 4229 std::tie(Mask, VL) = 4230 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4231 } 4232 4233 LLVMContext &Context = *DAG.getContext(); 4234 const ElementCount Count = ContainerVT.getVectorElementCount(); 4235 do { 4236 SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2); 4237 EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count); 4238 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result, 4239 Mask, VL); 4240 } while (SrcEltVT != DstEltVT); 4241 4242 if (SrcVT.isFixedLengthVector()) 4243 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4244 4245 return Result; 4246 } 4247 4248 SDValue 4249 RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op, 4250 SelectionDAG &DAG) const { 4251 bool IsVP = 4252 Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND; 4253 bool IsExtend = 4254 Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND; 4255 // RVV can only do truncate fp to types half the size as the source. We 4256 // custom-lower f64->f16 rounds via RVV's round-to-odd float 4257 // conversion instruction. 4258 SDLoc DL(Op); 4259 MVT VT = Op.getSimpleValueType(); 4260 4261 assert(VT.isVector() && "Unexpected type for vector truncate lowering"); 4262 4263 SDValue Src = Op.getOperand(0); 4264 MVT SrcVT = Src.getSimpleValueType(); 4265 4266 bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 || 4267 SrcVT.getVectorElementType() != MVT::f16); 4268 bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 || 4269 SrcVT.getVectorElementType() != MVT::f64); 4270 4271 bool IsDirectConv = IsDirectExtend || IsDirectTrunc; 4272 4273 // Prepare any fixed-length vector operands. 4274 MVT ContainerVT = VT; 4275 SDValue Mask, VL; 4276 if (IsVP) { 4277 Mask = Op.getOperand(1); 4278 VL = Op.getOperand(2); 4279 } 4280 if (VT.isFixedLengthVector()) { 4281 MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT); 4282 ContainerVT = 4283 SrcContainerVT.changeVectorElementType(VT.getVectorElementType()); 4284 Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget); 4285 if (IsVP) { 4286 MVT MaskVT = getMaskTypeFor(ContainerVT); 4287 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4288 } 4289 } 4290 4291 if (!IsVP) 4292 std::tie(Mask, VL) = 4293 getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget); 4294 4295 unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL; 4296 4297 if (IsDirectConv) { 4298 Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL); 4299 if (VT.isFixedLengthVector()) 4300 Src = convertFromScalableVector(VT, Src, DAG, Subtarget); 4301 return Src; 4302 } 4303 4304 unsigned InterConvOpc = 4305 IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL; 4306 4307 MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32); 4308 SDValue IntermediateConv = 4309 DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL); 4310 SDValue Result = 4311 DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL); 4312 if (VT.isFixedLengthVector()) 4313 return convertFromScalableVector(VT, Result, DAG, Subtarget); 4314 return Result; 4315 } 4316 4317 // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the 4318 // first position of a vector, and that vector is slid up to the insert index. 4319 // By limiting the active vector length to index+1 and merging with the 4320 // original vector (with an undisturbed tail policy for elements >= VL), we 4321 // achieve the desired result of leaving all elements untouched except the one 4322 // at VL-1, which is replaced with the desired value. 4323 SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op, 4324 SelectionDAG &DAG) const { 4325 SDLoc DL(Op); 4326 MVT VecVT = Op.getSimpleValueType(); 4327 SDValue Vec = Op.getOperand(0); 4328 SDValue Val = Op.getOperand(1); 4329 SDValue Idx = Op.getOperand(2); 4330 4331 if (VecVT.getVectorElementType() == MVT::i1) { 4332 // FIXME: For now we just promote to an i8 vector and insert into that, 4333 // but this is probably not optimal. 4334 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4335 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4336 Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx); 4337 return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec); 4338 } 4339 4340 MVT ContainerVT = VecVT; 4341 // If the operand is a fixed-length vector, convert to a scalable one. 4342 if (VecVT.isFixedLengthVector()) { 4343 ContainerVT = getContainerForFixedLengthVector(VecVT); 4344 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4345 } 4346 4347 MVT XLenVT = Subtarget.getXLenVT(); 4348 4349 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 4350 bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64; 4351 // Even i64-element vectors on RV32 can be lowered without scalar 4352 // legalization if the most-significant 32 bits of the value are not affected 4353 // by the sign-extension of the lower 32 bits. 4354 // TODO: We could also catch sign extensions of a 32-bit value. 4355 if (!IsLegalInsert && isa<ConstantSDNode>(Val)) { 4356 const auto *CVal = cast<ConstantSDNode>(Val); 4357 if (isInt<32>(CVal->getSExtValue())) { 4358 IsLegalInsert = true; 4359 Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32); 4360 } 4361 } 4362 4363 SDValue Mask, VL; 4364 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 4365 4366 SDValue ValInVec; 4367 4368 if (IsLegalInsert) { 4369 unsigned Opc = 4370 VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL; 4371 if (isNullConstant(Idx)) { 4372 Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL); 4373 if (!VecVT.isFixedLengthVector()) 4374 return Vec; 4375 return convertFromScalableVector(VecVT, Vec, DAG, Subtarget); 4376 } 4377 ValInVec = 4378 DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Val, VL); 4379 } else { 4380 // On RV32, i64-element vectors must be specially handled to place the 4381 // value at element 0, by using two vslide1up instructions in sequence on 4382 // the i32 split lo/hi value. Use an equivalently-sized i32 vector for 4383 // this. 4384 SDValue One = DAG.getConstant(1, DL, XLenVT); 4385 SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero); 4386 SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One); 4387 MVT I32ContainerVT = 4388 MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2); 4389 SDValue I32Mask = 4390 getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first; 4391 // Limit the active VL to two. 4392 SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT); 4393 // Note: We can't pass a UNDEF to the first VSLIDE1UP_VL since an untied 4394 // undef doesn't obey the earlyclobber constraint. Just splat a zero value. 4395 ValInVec = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, I32ContainerVT, 4396 DAG.getUNDEF(I32ContainerVT), Zero, InsertI64VL); 4397 // First slide in the hi value, then the lo in underneath it. 4398 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4399 DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi, 4400 I32Mask, InsertI64VL); 4401 ValInVec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32ContainerVT, 4402 DAG.getUNDEF(I32ContainerVT), ValInVec, ValLo, 4403 I32Mask, InsertI64VL); 4404 // Bitcast back to the right container type. 4405 ValInVec = DAG.getBitcast(ContainerVT, ValInVec); 4406 } 4407 4408 // Now that the value is in a vector, slide it into position. 4409 SDValue InsertVL = 4410 DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT)); 4411 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 4412 ValInVec, Idx, Mask, InsertVL); 4413 if (!VecVT.isFixedLengthVector()) 4414 return Slideup; 4415 return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 4416 } 4417 4418 // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then 4419 // extract the first element: (extractelt (slidedown vec, idx), 0). For integer 4420 // types this is done using VMV_X_S to allow us to glean information about the 4421 // sign bits of the result. 4422 SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op, 4423 SelectionDAG &DAG) const { 4424 SDLoc DL(Op); 4425 SDValue Idx = Op.getOperand(1); 4426 SDValue Vec = Op.getOperand(0); 4427 EVT EltVT = Op.getValueType(); 4428 MVT VecVT = Vec.getSimpleValueType(); 4429 MVT XLenVT = Subtarget.getXLenVT(); 4430 4431 if (VecVT.getVectorElementType() == MVT::i1) { 4432 if (VecVT.isFixedLengthVector()) { 4433 unsigned NumElts = VecVT.getVectorNumElements(); 4434 if (NumElts >= 8) { 4435 MVT WideEltVT; 4436 unsigned WidenVecLen; 4437 SDValue ExtractElementIdx; 4438 SDValue ExtractBitIdx; 4439 unsigned MaxEEW = Subtarget.getELEN(); 4440 MVT LargestEltVT = MVT::getIntegerVT( 4441 std::min(MaxEEW, unsigned(XLenVT.getSizeInBits()))); 4442 if (NumElts <= LargestEltVT.getSizeInBits()) { 4443 assert(isPowerOf2_32(NumElts) && 4444 "the number of elements should be power of 2"); 4445 WideEltVT = MVT::getIntegerVT(NumElts); 4446 WidenVecLen = 1; 4447 ExtractElementIdx = DAG.getConstant(0, DL, XLenVT); 4448 ExtractBitIdx = Idx; 4449 } else { 4450 WideEltVT = LargestEltVT; 4451 WidenVecLen = NumElts / WideEltVT.getSizeInBits(); 4452 // extract element index = index / element width 4453 ExtractElementIdx = DAG.getNode( 4454 ISD::SRL, DL, XLenVT, Idx, 4455 DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT)); 4456 // mask bit index = index % element width 4457 ExtractBitIdx = DAG.getNode( 4458 ISD::AND, DL, XLenVT, Idx, 4459 DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT)); 4460 } 4461 MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen); 4462 Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec); 4463 SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT, 4464 Vec, ExtractElementIdx); 4465 // Extract the bit from GPR. 4466 SDValue ShiftRight = 4467 DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx); 4468 return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight, 4469 DAG.getConstant(1, DL, XLenVT)); 4470 } 4471 } 4472 // Otherwise, promote to an i8 vector and extract from that. 4473 MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount()); 4474 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec); 4475 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx); 4476 } 4477 4478 // If this is a fixed vector, we need to convert it to a scalable vector. 4479 MVT ContainerVT = VecVT; 4480 if (VecVT.isFixedLengthVector()) { 4481 ContainerVT = getContainerForFixedLengthVector(VecVT); 4482 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 4483 } 4484 4485 // If the index is 0, the vector is already in the right position. 4486 if (!isNullConstant(Idx)) { 4487 // Use a VL of 1 to avoid processing more elements than we need. 4488 SDValue VL = DAG.getConstant(1, DL, XLenVT); 4489 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 4490 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 4491 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 4492 } 4493 4494 if (!EltVT.isInteger()) { 4495 // Floating-point extracts are handled in TableGen. 4496 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, 4497 DAG.getConstant(0, DL, XLenVT)); 4498 } 4499 4500 SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 4501 return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0); 4502 } 4503 4504 // Some RVV intrinsics may claim that they want an integer operand to be 4505 // promoted or expanded. 4506 static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG, 4507 const RISCVSubtarget &Subtarget) { 4508 assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 4509 Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) && 4510 "Unexpected opcode"); 4511 4512 if (!Subtarget.hasVInstructions()) 4513 return SDValue(); 4514 4515 bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN; 4516 unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0); 4517 SDLoc DL(Op); 4518 4519 const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II = 4520 RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo); 4521 if (!II || !II->hasScalarOperand()) 4522 return SDValue(); 4523 4524 unsigned SplatOp = II->ScalarOperand + 1 + HasChain; 4525 assert(SplatOp < Op.getNumOperands()); 4526 4527 SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end()); 4528 SDValue &ScalarOp = Operands[SplatOp]; 4529 MVT OpVT = ScalarOp.getSimpleValueType(); 4530 MVT XLenVT = Subtarget.getXLenVT(); 4531 4532 // If this isn't a scalar, or its type is XLenVT we're done. 4533 if (!OpVT.isScalarInteger() || OpVT == XLenVT) 4534 return SDValue(); 4535 4536 // Simplest case is that the operand needs to be promoted to XLenVT. 4537 if (OpVT.bitsLT(XLenVT)) { 4538 // If the operand is a constant, sign extend to increase our chances 4539 // of being able to use a .vi instruction. ANY_EXTEND would become a 4540 // a zero extend and the simm5 check in isel would fail. 4541 // FIXME: Should we ignore the upper bits in isel instead? 4542 unsigned ExtOpc = 4543 isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND; 4544 ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp); 4545 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4546 } 4547 4548 // Use the previous operand to get the vXi64 VT. The result might be a mask 4549 // VT for compares. Using the previous operand assumes that the previous 4550 // operand will never have a smaller element size than a scalar operand and 4551 // that a widening operation never uses SEW=64. 4552 // NOTE: If this fails the below assert, we can probably just find the 4553 // element count from any operand or result and use it to construct the VT. 4554 assert(II->ScalarOperand > 0 && "Unexpected splat operand!"); 4555 MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType(); 4556 4557 // The more complex case is when the scalar is larger than XLenVT. 4558 assert(XLenVT == MVT::i32 && OpVT == MVT::i64 && 4559 VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!"); 4560 4561 // If this is a sign-extended 32-bit value, we can truncate it and rely on the 4562 // instruction to sign-extend since SEW>XLEN. 4563 if (DAG.ComputeNumSignBits(ScalarOp) > 32) { 4564 ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp); 4565 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4566 } 4567 4568 switch (IntNo) { 4569 case Intrinsic::riscv_vslide1up: 4570 case Intrinsic::riscv_vslide1down: 4571 case Intrinsic::riscv_vslide1up_mask: 4572 case Intrinsic::riscv_vslide1down_mask: { 4573 // We need to special case these when the scalar is larger than XLen. 4574 unsigned NumOps = Op.getNumOperands(); 4575 bool IsMasked = NumOps == 7; 4576 4577 // Convert the vector source to the equivalent nxvXi32 vector. 4578 MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2); 4579 SDValue Vec = DAG.getBitcast(I32VT, Operands[2]); 4580 4581 SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4582 DAG.getConstant(0, DL, XLenVT)); 4583 SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp, 4584 DAG.getConstant(1, DL, XLenVT)); 4585 4586 // Double the VL since we halved SEW. 4587 SDValue AVL = getVLOperand(Op); 4588 SDValue I32VL; 4589 4590 // Optimize for constant AVL 4591 if (isa<ConstantSDNode>(AVL)) { 4592 unsigned EltSize = VT.getScalarSizeInBits(); 4593 unsigned MinSize = VT.getSizeInBits().getKnownMinValue(); 4594 4595 unsigned VectorBitsMax = Subtarget.getRealMaxVLen(); 4596 unsigned MaxVLMAX = 4597 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 4598 4599 unsigned VectorBitsMin = Subtarget.getRealMinVLen(); 4600 unsigned MinVLMAX = 4601 RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize); 4602 4603 uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue(); 4604 if (AVLInt <= MinVLMAX) { 4605 I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT); 4606 } else if (AVLInt >= 2 * MaxVLMAX) { 4607 // Just set vl to VLMAX in this situation 4608 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT); 4609 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4610 unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits()); 4611 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4612 SDValue SETVLMAX = DAG.getTargetConstant( 4613 Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32); 4614 I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW, 4615 LMUL); 4616 } else { 4617 // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl 4618 // is related to the hardware implementation. 4619 // So let the following code handle 4620 } 4621 } 4622 if (!I32VL) { 4623 RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT); 4624 SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT); 4625 unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits()); 4626 SDValue SEW = DAG.getConstant(Sew, DL, XLenVT); 4627 SDValue SETVL = 4628 DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32); 4629 // Using vsetvli instruction to get actually used length which related to 4630 // the hardware implementation 4631 SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL, 4632 SEW, LMUL); 4633 I32VL = 4634 DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT)); 4635 } 4636 4637 SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG); 4638 4639 // Shift the two scalar parts in using SEW=32 slide1up/slide1down 4640 // instructions. 4641 SDValue Passthru; 4642 if (IsMasked) 4643 Passthru = DAG.getUNDEF(I32VT); 4644 else 4645 Passthru = DAG.getBitcast(I32VT, Operands[1]); 4646 4647 if (IntNo == Intrinsic::riscv_vslide1up || 4648 IntNo == Intrinsic::riscv_vslide1up_mask) { 4649 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4650 ScalarHi, I32Mask, I32VL); 4651 Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec, 4652 ScalarLo, I32Mask, I32VL); 4653 } else { 4654 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4655 ScalarLo, I32Mask, I32VL); 4656 Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec, 4657 ScalarHi, I32Mask, I32VL); 4658 } 4659 4660 // Convert back to nxvXi64. 4661 Vec = DAG.getBitcast(VT, Vec); 4662 4663 if (!IsMasked) 4664 return Vec; 4665 // Apply mask after the operation. 4666 SDValue Mask = Operands[NumOps - 3]; 4667 SDValue MaskedOff = Operands[1]; 4668 // Assume Policy operand is the last operand. 4669 uint64_t Policy = 4670 cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue(); 4671 // We don't need to select maskedoff if it's undef. 4672 if (MaskedOff.isUndef()) 4673 return Vec; 4674 // TAMU 4675 if (Policy == RISCVII::TAIL_AGNOSTIC) 4676 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff, 4677 AVL); 4678 // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma. 4679 // It's fine because vmerge does not care mask policy. 4680 return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff, 4681 AVL); 4682 } 4683 } 4684 4685 // We need to convert the scalar to a splat vector. 4686 SDValue VL = getVLOperand(Op); 4687 assert(VL.getValueType() == XLenVT); 4688 ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG); 4689 return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands); 4690 } 4691 4692 SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, 4693 SelectionDAG &DAG) const { 4694 unsigned IntNo = Op.getConstantOperandVal(0); 4695 SDLoc DL(Op); 4696 MVT XLenVT = Subtarget.getXLenVT(); 4697 4698 switch (IntNo) { 4699 default: 4700 break; // Don't custom lower most intrinsics. 4701 case Intrinsic::thread_pointer: { 4702 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 4703 return DAG.getRegister(RISCV::X4, PtrVT); 4704 } 4705 case Intrinsic::riscv_orc_b: 4706 case Intrinsic::riscv_brev8: { 4707 // Lower to the GORCI encoding for orc.b or the GREVI encoding for brev8. 4708 unsigned Opc = 4709 IntNo == Intrinsic::riscv_brev8 ? RISCVISD::GREV : RISCVISD::GORC; 4710 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4711 DAG.getConstant(7, DL, XLenVT)); 4712 } 4713 case Intrinsic::riscv_grev: 4714 case Intrinsic::riscv_gorc: { 4715 unsigned Opc = 4716 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 4717 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4718 } 4719 case Intrinsic::riscv_zip: 4720 case Intrinsic::riscv_unzip: { 4721 // Lower to the SHFLI encoding for zip or the UNSHFLI encoding for unzip. 4722 // For i32 the immediate is 15. For i64 the immediate is 31. 4723 unsigned Opc = 4724 IntNo == Intrinsic::riscv_zip ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4725 unsigned BitWidth = Op.getValueSizeInBits(); 4726 assert(isPowerOf2_32(BitWidth) && BitWidth >= 2 && "Unexpected bit width"); 4727 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), 4728 DAG.getConstant((BitWidth / 2) - 1, DL, XLenVT)); 4729 } 4730 case Intrinsic::riscv_shfl: 4731 case Intrinsic::riscv_unshfl: { 4732 unsigned Opc = 4733 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 4734 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4735 } 4736 case Intrinsic::riscv_bcompress: 4737 case Intrinsic::riscv_bdecompress: { 4738 unsigned Opc = IntNo == Intrinsic::riscv_bcompress ? RISCVISD::BCOMPRESS 4739 : RISCVISD::BDECOMPRESS; 4740 return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1), Op.getOperand(2)); 4741 } 4742 case Intrinsic::riscv_bfp: 4743 return DAG.getNode(RISCVISD::BFP, DL, XLenVT, Op.getOperand(1), 4744 Op.getOperand(2)); 4745 case Intrinsic::riscv_fsl: 4746 return DAG.getNode(RISCVISD::FSL, DL, XLenVT, Op.getOperand(1), 4747 Op.getOperand(2), Op.getOperand(3)); 4748 case Intrinsic::riscv_fsr: 4749 return DAG.getNode(RISCVISD::FSR, DL, XLenVT, Op.getOperand(1), 4750 Op.getOperand(2), Op.getOperand(3)); 4751 case Intrinsic::riscv_vmv_x_s: 4752 assert(Op.getValueType() == XLenVT && "Unexpected VT!"); 4753 return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(), 4754 Op.getOperand(1)); 4755 case Intrinsic::riscv_vmv_v_x: 4756 return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2), 4757 Op.getOperand(3), Op.getSimpleValueType(), DL, DAG, 4758 Subtarget); 4759 case Intrinsic::riscv_vfmv_v_f: 4760 return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(), 4761 Op.getOperand(1), Op.getOperand(2), Op.getOperand(3)); 4762 case Intrinsic::riscv_vmv_s_x: { 4763 SDValue Scalar = Op.getOperand(2); 4764 4765 if (Scalar.getValueType().bitsLE(XLenVT)) { 4766 Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar); 4767 return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(), 4768 Op.getOperand(1), Scalar, Op.getOperand(3)); 4769 } 4770 4771 assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!"); 4772 4773 // This is an i64 value that lives in two scalar registers. We have to 4774 // insert this in a convoluted way. First we build vXi64 splat containing 4775 // the two values that we assemble using some bit math. Next we'll use 4776 // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask 4777 // to merge element 0 from our splat into the source vector. 4778 // FIXME: This is probably not the best way to do this, but it is 4779 // consistent with INSERT_VECTOR_ELT lowering so it is a good starting 4780 // point. 4781 // sw lo, (a0) 4782 // sw hi, 4(a0) 4783 // vlse vX, (a0) 4784 // 4785 // vid.v vVid 4786 // vmseq.vx mMask, vVid, 0 4787 // vmerge.vvm vDest, vSrc, vVal, mMask 4788 MVT VT = Op.getSimpleValueType(); 4789 SDValue Vec = Op.getOperand(1); 4790 SDValue VL = getVLOperand(Op); 4791 4792 SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG); 4793 if (Op.getOperand(1).isUndef()) 4794 return SplattedVal; 4795 SDValue SplattedIdx = 4796 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 4797 DAG.getConstant(0, DL, MVT::i32), VL); 4798 4799 MVT MaskVT = getMaskTypeFor(VT); 4800 SDValue Mask = getAllOnesMask(VT, VL, DL, DAG); 4801 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 4802 SDValue SelectCond = 4803 DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, VID, SplattedIdx, 4804 DAG.getCondCode(ISD::SETEQ), Mask, VL); 4805 return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal, 4806 Vec, VL); 4807 } 4808 } 4809 4810 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4811 } 4812 4813 SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op, 4814 SelectionDAG &DAG) const { 4815 unsigned IntNo = Op.getConstantOperandVal(1); 4816 switch (IntNo) { 4817 default: 4818 break; 4819 case Intrinsic::riscv_masked_strided_load: { 4820 SDLoc DL(Op); 4821 MVT XLenVT = Subtarget.getXLenVT(); 4822 4823 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4824 // the selection of the masked intrinsics doesn't do this for us. 4825 SDValue Mask = Op.getOperand(5); 4826 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4827 4828 MVT VT = Op->getSimpleValueType(0); 4829 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4830 4831 SDValue PassThru = Op.getOperand(2); 4832 if (!IsUnmasked) { 4833 MVT MaskVT = getMaskTypeFor(ContainerVT); 4834 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4835 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 4836 } 4837 4838 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4839 4840 SDValue IntID = DAG.getTargetConstant( 4841 IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL, 4842 XLenVT); 4843 4844 auto *Load = cast<MemIntrinsicSDNode>(Op); 4845 SmallVector<SDValue, 8> Ops{Load->getChain(), IntID}; 4846 if (IsUnmasked) 4847 Ops.push_back(DAG.getUNDEF(ContainerVT)); 4848 else 4849 Ops.push_back(PassThru); 4850 Ops.push_back(Op.getOperand(3)); // Ptr 4851 Ops.push_back(Op.getOperand(4)); // Stride 4852 if (!IsUnmasked) 4853 Ops.push_back(Mask); 4854 Ops.push_back(VL); 4855 if (!IsUnmasked) { 4856 SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT); 4857 Ops.push_back(Policy); 4858 } 4859 4860 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 4861 SDValue Result = 4862 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4863 Load->getMemoryVT(), Load->getMemOperand()); 4864 SDValue Chain = Result.getValue(1); 4865 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 4866 return DAG.getMergeValues({Result, Chain}, DL); 4867 } 4868 case Intrinsic::riscv_seg2_load: 4869 case Intrinsic::riscv_seg3_load: 4870 case Intrinsic::riscv_seg4_load: 4871 case Intrinsic::riscv_seg5_load: 4872 case Intrinsic::riscv_seg6_load: 4873 case Intrinsic::riscv_seg7_load: 4874 case Intrinsic::riscv_seg8_load: { 4875 SDLoc DL(Op); 4876 static const Intrinsic::ID VlsegInts[7] = { 4877 Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3, 4878 Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5, 4879 Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7, 4880 Intrinsic::riscv_vlseg8}; 4881 unsigned NF = Op->getNumValues() - 1; 4882 assert(NF >= 2 && NF <= 8 && "Unexpected seg number"); 4883 MVT XLenVT = Subtarget.getXLenVT(); 4884 MVT VT = Op->getSimpleValueType(0); 4885 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4886 4887 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4888 SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT); 4889 auto *Load = cast<MemIntrinsicSDNode>(Op); 4890 SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT); 4891 ContainerVTs.push_back(MVT::Other); 4892 SDVTList VTs = DAG.getVTList(ContainerVTs); 4893 SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID}; 4894 Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT)); 4895 Ops.push_back(Op.getOperand(2)); 4896 Ops.push_back(VL); 4897 SDValue Result = 4898 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 4899 Load->getMemoryVT(), Load->getMemOperand()); 4900 SmallVector<SDValue, 9> Results; 4901 for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++) 4902 Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx), 4903 DAG, Subtarget)); 4904 Results.push_back(Result.getValue(NF)); 4905 return DAG.getMergeValues(Results, DL); 4906 } 4907 } 4908 4909 return lowerVectorIntrinsicScalars(Op, DAG, Subtarget); 4910 } 4911 4912 SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op, 4913 SelectionDAG &DAG) const { 4914 unsigned IntNo = Op.getConstantOperandVal(1); 4915 switch (IntNo) { 4916 default: 4917 break; 4918 case Intrinsic::riscv_masked_strided_store: { 4919 SDLoc DL(Op); 4920 MVT XLenVT = Subtarget.getXLenVT(); 4921 4922 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 4923 // the selection of the masked intrinsics doesn't do this for us. 4924 SDValue Mask = Op.getOperand(5); 4925 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 4926 4927 SDValue Val = Op.getOperand(2); 4928 MVT VT = Val.getSimpleValueType(); 4929 MVT ContainerVT = getContainerForFixedLengthVector(VT); 4930 4931 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 4932 if (!IsUnmasked) { 4933 MVT MaskVT = getMaskTypeFor(ContainerVT); 4934 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 4935 } 4936 4937 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 4938 4939 SDValue IntID = DAG.getTargetConstant( 4940 IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL, 4941 XLenVT); 4942 4943 auto *Store = cast<MemIntrinsicSDNode>(Op); 4944 SmallVector<SDValue, 8> Ops{Store->getChain(), IntID}; 4945 Ops.push_back(Val); 4946 Ops.push_back(Op.getOperand(3)); // Ptr 4947 Ops.push_back(Op.getOperand(4)); // Stride 4948 if (!IsUnmasked) 4949 Ops.push_back(Mask); 4950 Ops.push_back(VL); 4951 4952 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(), 4953 Ops, Store->getMemoryVT(), 4954 Store->getMemOperand()); 4955 } 4956 } 4957 4958 return SDValue(); 4959 } 4960 4961 static MVT getLMUL1VT(MVT VT) { 4962 assert(VT.getVectorElementType().getSizeInBits() <= 64 && 4963 "Unexpected vector MVT"); 4964 return MVT::getScalableVectorVT( 4965 VT.getVectorElementType(), 4966 RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits()); 4967 } 4968 4969 static unsigned getRVVReductionOp(unsigned ISDOpcode) { 4970 switch (ISDOpcode) { 4971 default: 4972 llvm_unreachable("Unhandled reduction"); 4973 case ISD::VECREDUCE_ADD: 4974 return RISCVISD::VECREDUCE_ADD_VL; 4975 case ISD::VECREDUCE_UMAX: 4976 return RISCVISD::VECREDUCE_UMAX_VL; 4977 case ISD::VECREDUCE_SMAX: 4978 return RISCVISD::VECREDUCE_SMAX_VL; 4979 case ISD::VECREDUCE_UMIN: 4980 return RISCVISD::VECREDUCE_UMIN_VL; 4981 case ISD::VECREDUCE_SMIN: 4982 return RISCVISD::VECREDUCE_SMIN_VL; 4983 case ISD::VECREDUCE_AND: 4984 return RISCVISD::VECREDUCE_AND_VL; 4985 case ISD::VECREDUCE_OR: 4986 return RISCVISD::VECREDUCE_OR_VL; 4987 case ISD::VECREDUCE_XOR: 4988 return RISCVISD::VECREDUCE_XOR_VL; 4989 } 4990 } 4991 4992 SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op, 4993 SelectionDAG &DAG, 4994 bool IsVP) const { 4995 SDLoc DL(Op); 4996 SDValue Vec = Op.getOperand(IsVP ? 1 : 0); 4997 MVT VecVT = Vec.getSimpleValueType(); 4998 assert((Op.getOpcode() == ISD::VECREDUCE_AND || 4999 Op.getOpcode() == ISD::VECREDUCE_OR || 5000 Op.getOpcode() == ISD::VECREDUCE_XOR || 5001 Op.getOpcode() == ISD::VP_REDUCE_AND || 5002 Op.getOpcode() == ISD::VP_REDUCE_OR || 5003 Op.getOpcode() == ISD::VP_REDUCE_XOR) && 5004 "Unexpected reduction lowering"); 5005 5006 MVT XLenVT = Subtarget.getXLenVT(); 5007 assert(Op.getValueType() == XLenVT && 5008 "Expected reduction output to be legalized to XLenVT"); 5009 5010 MVT ContainerVT = VecVT; 5011 if (VecVT.isFixedLengthVector()) { 5012 ContainerVT = getContainerForFixedLengthVector(VecVT); 5013 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5014 } 5015 5016 SDValue Mask, VL; 5017 if (IsVP) { 5018 Mask = Op.getOperand(2); 5019 VL = Op.getOperand(3); 5020 } else { 5021 std::tie(Mask, VL) = 5022 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5023 } 5024 5025 unsigned BaseOpc; 5026 ISD::CondCode CC; 5027 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 5028 5029 switch (Op.getOpcode()) { 5030 default: 5031 llvm_unreachable("Unhandled reduction"); 5032 case ISD::VECREDUCE_AND: 5033 case ISD::VP_REDUCE_AND: { 5034 // vcpop ~x == 0 5035 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 5036 Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL); 5037 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5038 CC = ISD::SETEQ; 5039 BaseOpc = ISD::AND; 5040 break; 5041 } 5042 case ISD::VECREDUCE_OR: 5043 case ISD::VP_REDUCE_OR: 5044 // vcpop x != 0 5045 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5046 CC = ISD::SETNE; 5047 BaseOpc = ISD::OR; 5048 break; 5049 case ISD::VECREDUCE_XOR: 5050 case ISD::VP_REDUCE_XOR: { 5051 // ((vcpop x) & 1) != 0 5052 SDValue One = DAG.getConstant(1, DL, XLenVT); 5053 Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL); 5054 Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One); 5055 CC = ISD::SETNE; 5056 BaseOpc = ISD::XOR; 5057 break; 5058 } 5059 } 5060 5061 SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC); 5062 5063 if (!IsVP) 5064 return SetCC; 5065 5066 // Now include the start value in the operation. 5067 // Note that we must return the start value when no elements are operated 5068 // upon. The vcpop instructions we've emitted in each case above will return 5069 // 0 for an inactive vector, and so we've already received the neutral value: 5070 // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we 5071 // can simply include the start value. 5072 return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0)); 5073 } 5074 5075 SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op, 5076 SelectionDAG &DAG) const { 5077 SDLoc DL(Op); 5078 SDValue Vec = Op.getOperand(0); 5079 EVT VecEVT = Vec.getValueType(); 5080 5081 unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode()); 5082 5083 // Due to ordering in legalize types we may have a vector type that needs to 5084 // be split. Do that manually so we can get down to a legal type. 5085 while (getTypeAction(*DAG.getContext(), VecEVT) == 5086 TargetLowering::TypeSplitVector) { 5087 SDValue Lo, Hi; 5088 std::tie(Lo, Hi) = DAG.SplitVector(Vec, DL); 5089 VecEVT = Lo.getValueType(); 5090 Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi); 5091 } 5092 5093 // TODO: The type may need to be widened rather than split. Or widened before 5094 // it can be split. 5095 if (!isTypeLegal(VecEVT)) 5096 return SDValue(); 5097 5098 MVT VecVT = VecEVT.getSimpleVT(); 5099 MVT VecEltVT = VecVT.getVectorElementType(); 5100 unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode()); 5101 5102 MVT ContainerVT = VecVT; 5103 if (VecVT.isFixedLengthVector()) { 5104 ContainerVT = getContainerForFixedLengthVector(VecVT); 5105 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5106 } 5107 5108 MVT M1VT = getLMUL1VT(ContainerVT); 5109 MVT XLenVT = Subtarget.getXLenVT(); 5110 5111 SDValue Mask, VL; 5112 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5113 5114 SDValue NeutralElem = 5115 DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags()); 5116 SDValue IdentitySplat = 5117 lowerScalarSplat(SDValue(), NeutralElem, DAG.getConstant(1, DL, XLenVT), 5118 M1VT, DL, DAG, Subtarget); 5119 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), Vec, 5120 IdentitySplat, Mask, VL); 5121 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5122 DAG.getConstant(0, DL, XLenVT)); 5123 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5124 } 5125 5126 // Given a reduction op, this function returns the matching reduction opcode, 5127 // the vector SDValue and the scalar SDValue required to lower this to a 5128 // RISCVISD node. 5129 static std::tuple<unsigned, SDValue, SDValue> 5130 getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) { 5131 SDLoc DL(Op); 5132 auto Flags = Op->getFlags(); 5133 unsigned Opcode = Op.getOpcode(); 5134 unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode); 5135 switch (Opcode) { 5136 default: 5137 llvm_unreachable("Unhandled reduction"); 5138 case ISD::VECREDUCE_FADD: { 5139 // Use positive zero if we can. It is cheaper to materialize. 5140 SDValue Zero = 5141 DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT); 5142 return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero); 5143 } 5144 case ISD::VECREDUCE_SEQ_FADD: 5145 return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1), 5146 Op.getOperand(0)); 5147 case ISD::VECREDUCE_FMIN: 5148 return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0), 5149 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5150 case ISD::VECREDUCE_FMAX: 5151 return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0), 5152 DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags)); 5153 } 5154 } 5155 5156 SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op, 5157 SelectionDAG &DAG) const { 5158 SDLoc DL(Op); 5159 MVT VecEltVT = Op.getSimpleValueType(); 5160 5161 unsigned RVVOpcode; 5162 SDValue VectorVal, ScalarVal; 5163 std::tie(RVVOpcode, VectorVal, ScalarVal) = 5164 getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT); 5165 MVT VecVT = VectorVal.getSimpleValueType(); 5166 5167 MVT ContainerVT = VecVT; 5168 if (VecVT.isFixedLengthVector()) { 5169 ContainerVT = getContainerForFixedLengthVector(VecVT); 5170 VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget); 5171 } 5172 5173 MVT M1VT = getLMUL1VT(VectorVal.getSimpleValueType()); 5174 MVT XLenVT = Subtarget.getXLenVT(); 5175 5176 SDValue Mask, VL; 5177 std::tie(Mask, VL) = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget); 5178 5179 SDValue ScalarSplat = 5180 lowerScalarSplat(SDValue(), ScalarVal, DAG.getConstant(1, DL, XLenVT), 5181 M1VT, DL, DAG, Subtarget); 5182 SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, DAG.getUNDEF(M1VT), 5183 VectorVal, ScalarSplat, Mask, VL); 5184 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VecEltVT, Reduction, 5185 DAG.getConstant(0, DL, XLenVT)); 5186 } 5187 5188 static unsigned getRVVVPReductionOp(unsigned ISDOpcode) { 5189 switch (ISDOpcode) { 5190 default: 5191 llvm_unreachable("Unhandled reduction"); 5192 case ISD::VP_REDUCE_ADD: 5193 return RISCVISD::VECREDUCE_ADD_VL; 5194 case ISD::VP_REDUCE_UMAX: 5195 return RISCVISD::VECREDUCE_UMAX_VL; 5196 case ISD::VP_REDUCE_SMAX: 5197 return RISCVISD::VECREDUCE_SMAX_VL; 5198 case ISD::VP_REDUCE_UMIN: 5199 return RISCVISD::VECREDUCE_UMIN_VL; 5200 case ISD::VP_REDUCE_SMIN: 5201 return RISCVISD::VECREDUCE_SMIN_VL; 5202 case ISD::VP_REDUCE_AND: 5203 return RISCVISD::VECREDUCE_AND_VL; 5204 case ISD::VP_REDUCE_OR: 5205 return RISCVISD::VECREDUCE_OR_VL; 5206 case ISD::VP_REDUCE_XOR: 5207 return RISCVISD::VECREDUCE_XOR_VL; 5208 case ISD::VP_REDUCE_FADD: 5209 return RISCVISD::VECREDUCE_FADD_VL; 5210 case ISD::VP_REDUCE_SEQ_FADD: 5211 return RISCVISD::VECREDUCE_SEQ_FADD_VL; 5212 case ISD::VP_REDUCE_FMAX: 5213 return RISCVISD::VECREDUCE_FMAX_VL; 5214 case ISD::VP_REDUCE_FMIN: 5215 return RISCVISD::VECREDUCE_FMIN_VL; 5216 } 5217 } 5218 5219 SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op, 5220 SelectionDAG &DAG) const { 5221 SDLoc DL(Op); 5222 SDValue Vec = Op.getOperand(1); 5223 EVT VecEVT = Vec.getValueType(); 5224 5225 // TODO: The type may need to be widened rather than split. Or widened before 5226 // it can be split. 5227 if (!isTypeLegal(VecEVT)) 5228 return SDValue(); 5229 5230 MVT VecVT = VecEVT.getSimpleVT(); 5231 MVT VecEltVT = VecVT.getVectorElementType(); 5232 unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode()); 5233 5234 MVT ContainerVT = VecVT; 5235 if (VecVT.isFixedLengthVector()) { 5236 ContainerVT = getContainerForFixedLengthVector(VecVT); 5237 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5238 } 5239 5240 SDValue VL = Op.getOperand(3); 5241 SDValue Mask = Op.getOperand(2); 5242 5243 MVT M1VT = getLMUL1VT(ContainerVT); 5244 MVT XLenVT = Subtarget.getXLenVT(); 5245 MVT ResVT = !VecVT.isInteger() || VecEltVT.bitsGE(XLenVT) ? VecEltVT : XLenVT; 5246 5247 SDValue StartSplat = lowerScalarSplat(SDValue(), Op.getOperand(0), 5248 DAG.getConstant(1, DL, XLenVT), M1VT, 5249 DL, DAG, Subtarget); 5250 SDValue Reduction = 5251 DAG.getNode(RVVOpcode, DL, M1VT, StartSplat, Vec, StartSplat, Mask, VL); 5252 SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction, 5253 DAG.getConstant(0, DL, XLenVT)); 5254 if (!VecVT.isInteger()) 5255 return Elt0; 5256 return DAG.getSExtOrTrunc(Elt0, DL, Op.getValueType()); 5257 } 5258 5259 SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op, 5260 SelectionDAG &DAG) const { 5261 SDValue Vec = Op.getOperand(0); 5262 SDValue SubVec = Op.getOperand(1); 5263 MVT VecVT = Vec.getSimpleValueType(); 5264 MVT SubVecVT = SubVec.getSimpleValueType(); 5265 5266 SDLoc DL(Op); 5267 MVT XLenVT = Subtarget.getXLenVT(); 5268 unsigned OrigIdx = Op.getConstantOperandVal(2); 5269 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5270 5271 // We don't have the ability to slide mask vectors up indexed by their i1 5272 // elements; the smallest we can do is i8. Often we are able to bitcast to 5273 // equivalent i8 vectors. Note that when inserting a fixed-length vector 5274 // into a scalable one, we might not necessarily have enough scalable 5275 // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid. 5276 if (SubVecVT.getVectorElementType() == MVT::i1 && 5277 (OrigIdx != 0 || !Vec.isUndef())) { 5278 if (VecVT.getVectorMinNumElements() >= 8 && 5279 SubVecVT.getVectorMinNumElements() >= 8) { 5280 assert(OrigIdx % 8 == 0 && "Invalid index"); 5281 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5282 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5283 "Unexpected mask vector lowering"); 5284 OrigIdx /= 8; 5285 SubVecVT = 5286 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5287 SubVecVT.isScalableVector()); 5288 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5289 VecVT.isScalableVector()); 5290 Vec = DAG.getBitcast(VecVT, Vec); 5291 SubVec = DAG.getBitcast(SubVecVT, SubVec); 5292 } else { 5293 // We can't slide this mask vector up indexed by its i1 elements. 5294 // This poses a problem when we wish to insert a scalable vector which 5295 // can't be re-expressed as a larger type. Just choose the slow path and 5296 // extend to a larger type, then truncate back down. 5297 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5298 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5299 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5300 SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec); 5301 Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec, 5302 Op.getOperand(2)); 5303 SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT); 5304 return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE); 5305 } 5306 } 5307 5308 // If the subvector vector is a fixed-length type, we cannot use subregister 5309 // manipulation to simplify the codegen; we don't know which register of a 5310 // LMUL group contains the specific subvector as we only know the minimum 5311 // register size. Therefore we must slide the vector group up the full 5312 // amount. 5313 if (SubVecVT.isFixedLengthVector()) { 5314 if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector()) 5315 return Op; 5316 MVT ContainerVT = VecVT; 5317 if (VecVT.isFixedLengthVector()) { 5318 ContainerVT = getContainerForFixedLengthVector(VecVT); 5319 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5320 } 5321 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT, 5322 DAG.getUNDEF(ContainerVT), SubVec, 5323 DAG.getConstant(0, DL, XLenVT)); 5324 if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) { 5325 SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget); 5326 return DAG.getBitcast(Op.getValueType(), SubVec); 5327 } 5328 SDValue Mask = 5329 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5330 // Set the vector length to only the number of elements we care about. Note 5331 // that for slideup this includes the offset. 5332 SDValue VL = 5333 DAG.getConstant(OrigIdx + SubVecVT.getVectorNumElements(), DL, XLenVT); 5334 SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5335 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, ContainerVT, Vec, 5336 SubVec, SlideupAmt, Mask, VL); 5337 if (VecVT.isFixedLengthVector()) 5338 Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget); 5339 return DAG.getBitcast(Op.getValueType(), Slideup); 5340 } 5341 5342 unsigned SubRegIdx, RemIdx; 5343 std::tie(SubRegIdx, RemIdx) = 5344 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5345 VecVT, SubVecVT, OrigIdx, TRI); 5346 5347 RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT); 5348 bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 || 5349 SubVecLMUL == RISCVII::VLMUL::LMUL_F4 || 5350 SubVecLMUL == RISCVII::VLMUL::LMUL_F8; 5351 5352 // 1. If the Idx has been completely eliminated and this subvector's size is 5353 // a vector register or a multiple thereof, or the surrounding elements are 5354 // undef, then this is a subvector insert which naturally aligns to a vector 5355 // register. These can easily be handled using subregister manipulation. 5356 // 2. If the subvector is smaller than a vector register, then the insertion 5357 // must preserve the undisturbed elements of the register. We do this by 5358 // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type 5359 // (which resolves to a subregister copy), performing a VSLIDEUP to place the 5360 // subvector within the vector register, and an INSERT_SUBVECTOR of that 5361 // LMUL=1 type back into the larger vector (resolving to another subregister 5362 // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type 5363 // to avoid allocating a large register group to hold our subvector. 5364 if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef())) 5365 return Op; 5366 5367 // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements 5368 // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy 5369 // (in our case undisturbed). This means we can set up a subvector insertion 5370 // where OFFSET is the insertion offset, and the VL is the OFFSET plus the 5371 // size of the subvector. 5372 MVT InterSubVT = VecVT; 5373 SDValue AlignedExtract = Vec; 5374 unsigned AlignedIdx = OrigIdx - RemIdx; 5375 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5376 InterSubVT = getLMUL1VT(VecVT); 5377 // Extract a subvector equal to the nearest full vector register type. This 5378 // should resolve to a EXTRACT_SUBREG instruction. 5379 AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5380 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5381 } 5382 5383 SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5384 // For scalable vectors this must be further multiplied by vscale. 5385 SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt); 5386 5387 SDValue Mask, VL; 5388 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5389 5390 // Construct the vector length corresponding to RemIdx + length(SubVecVT). 5391 VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT); 5392 VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL); 5393 VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL); 5394 5395 SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT, 5396 DAG.getUNDEF(InterSubVT), SubVec, 5397 DAG.getConstant(0, DL, XLenVT)); 5398 5399 SDValue Slideup = DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, InterSubVT, 5400 AlignedExtract, SubVec, SlideupAmt, Mask, VL); 5401 5402 // If required, insert this subvector back into the correct vector register. 5403 // This should resolve to an INSERT_SUBREG instruction. 5404 if (VecVT.bitsGT(InterSubVT)) 5405 Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup, 5406 DAG.getConstant(AlignedIdx, DL, XLenVT)); 5407 5408 // We might have bitcast from a mask type: cast back to the original type if 5409 // required. 5410 return DAG.getBitcast(Op.getSimpleValueType(), Slideup); 5411 } 5412 5413 SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op, 5414 SelectionDAG &DAG) const { 5415 SDValue Vec = Op.getOperand(0); 5416 MVT SubVecVT = Op.getSimpleValueType(); 5417 MVT VecVT = Vec.getSimpleValueType(); 5418 5419 SDLoc DL(Op); 5420 MVT XLenVT = Subtarget.getXLenVT(); 5421 unsigned OrigIdx = Op.getConstantOperandVal(1); 5422 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 5423 5424 // We don't have the ability to slide mask vectors down indexed by their i1 5425 // elements; the smallest we can do is i8. Often we are able to bitcast to 5426 // equivalent i8 vectors. Note that when extracting a fixed-length vector 5427 // from a scalable one, we might not necessarily have enough scalable 5428 // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid. 5429 if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) { 5430 if (VecVT.getVectorMinNumElements() >= 8 && 5431 SubVecVT.getVectorMinNumElements() >= 8) { 5432 assert(OrigIdx % 8 == 0 && "Invalid index"); 5433 assert(VecVT.getVectorMinNumElements() % 8 == 0 && 5434 SubVecVT.getVectorMinNumElements() % 8 == 0 && 5435 "Unexpected mask vector lowering"); 5436 OrigIdx /= 8; 5437 SubVecVT = 5438 MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8, 5439 SubVecVT.isScalableVector()); 5440 VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8, 5441 VecVT.isScalableVector()); 5442 Vec = DAG.getBitcast(VecVT, Vec); 5443 } else { 5444 // We can't slide this mask vector down, indexed by its i1 elements. 5445 // This poses a problem when we wish to extract a scalable vector which 5446 // can't be re-expressed as a larger type. Just choose the slow path and 5447 // extend to a larger type, then truncate back down. 5448 // TODO: We could probably improve this when extracting certain fixed 5449 // from fixed, where we can extract as i8 and shift the correct element 5450 // right to reach the desired subvector? 5451 MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8); 5452 MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8); 5453 Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec); 5454 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec, 5455 Op.getOperand(1)); 5456 SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT); 5457 return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE); 5458 } 5459 } 5460 5461 // If the subvector vector is a fixed-length type, we cannot use subregister 5462 // manipulation to simplify the codegen; we don't know which register of a 5463 // LMUL group contains the specific subvector as we only know the minimum 5464 // register size. Therefore we must slide the vector group down the full 5465 // amount. 5466 if (SubVecVT.isFixedLengthVector()) { 5467 // With an index of 0 this is a cast-like subvector, which can be performed 5468 // with subregister operations. 5469 if (OrigIdx == 0) 5470 return Op; 5471 MVT ContainerVT = VecVT; 5472 if (VecVT.isFixedLengthVector()) { 5473 ContainerVT = getContainerForFixedLengthVector(VecVT); 5474 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 5475 } 5476 SDValue Mask = 5477 getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first; 5478 // Set the vector length to only the number of elements we care about. This 5479 // avoids sliding down elements we're going to discard straight away. 5480 SDValue VL = DAG.getConstant(SubVecVT.getVectorNumElements(), DL, XLenVT); 5481 SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT); 5482 SDValue Slidedown = 5483 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 5484 DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL); 5485 // Now we can use a cast-like subvector extract to get the result. 5486 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5487 DAG.getConstant(0, DL, XLenVT)); 5488 return DAG.getBitcast(Op.getValueType(), Slidedown); 5489 } 5490 5491 unsigned SubRegIdx, RemIdx; 5492 std::tie(SubRegIdx, RemIdx) = 5493 RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs( 5494 VecVT, SubVecVT, OrigIdx, TRI); 5495 5496 // If the Idx has been completely eliminated then this is a subvector extract 5497 // which naturally aligns to a vector register. These can easily be handled 5498 // using subregister manipulation. 5499 if (RemIdx == 0) 5500 return Op; 5501 5502 // Else we must shift our vector register directly to extract the subvector. 5503 // Do this using VSLIDEDOWN. 5504 5505 // If the vector type is an LMUL-group type, extract a subvector equal to the 5506 // nearest full vector register type. This should resolve to a EXTRACT_SUBREG 5507 // instruction. 5508 MVT InterSubVT = VecVT; 5509 if (VecVT.bitsGT(getLMUL1VT(VecVT))) { 5510 InterSubVT = getLMUL1VT(VecVT); 5511 Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec, 5512 DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT)); 5513 } 5514 5515 // Slide this vector register down by the desired number of elements in order 5516 // to place the desired subvector starting at element 0. 5517 SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT); 5518 // For scalable vectors this must be further multiplied by vscale. 5519 SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt); 5520 5521 SDValue Mask, VL; 5522 std::tie(Mask, VL) = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget); 5523 SDValue Slidedown = 5524 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, InterSubVT, 5525 DAG.getUNDEF(InterSubVT), Vec, SlidedownAmt, Mask, VL); 5526 5527 // Now the vector is in the right position, extract our final subvector. This 5528 // should resolve to a COPY. 5529 Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown, 5530 DAG.getConstant(0, DL, XLenVT)); 5531 5532 // We might have bitcast from a mask type: cast back to the original type if 5533 // required. 5534 return DAG.getBitcast(Op.getSimpleValueType(), Slidedown); 5535 } 5536 5537 // Lower step_vector to the vid instruction. Any non-identity step value must 5538 // be accounted for my manual expansion. 5539 SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op, 5540 SelectionDAG &DAG) const { 5541 SDLoc DL(Op); 5542 MVT VT = Op.getSimpleValueType(); 5543 MVT XLenVT = Subtarget.getXLenVT(); 5544 SDValue Mask, VL; 5545 std::tie(Mask, VL) = getDefaultScalableVLOps(VT, DL, DAG, Subtarget); 5546 SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL); 5547 uint64_t StepValImm = Op.getConstantOperandVal(0); 5548 if (StepValImm != 1) { 5549 if (isPowerOf2_64(StepValImm)) { 5550 SDValue StepVal = 5551 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 5552 DAG.getConstant(Log2_64(StepValImm), DL, XLenVT)); 5553 StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal); 5554 } else { 5555 SDValue StepVal = lowerScalarSplat( 5556 SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()), 5557 VL, VT, DL, DAG, Subtarget); 5558 StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal); 5559 } 5560 } 5561 return StepVec; 5562 } 5563 5564 // Implement vector_reverse using vrgather.vv with indices determined by 5565 // subtracting the id of each element from (VLMAX-1). This will convert 5566 // the indices like so: 5567 // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0). 5568 // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16. 5569 SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op, 5570 SelectionDAG &DAG) const { 5571 SDLoc DL(Op); 5572 MVT VecVT = Op.getSimpleValueType(); 5573 unsigned EltSize = VecVT.getScalarSizeInBits(); 5574 unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue(); 5575 5576 unsigned MaxVLMAX = 0; 5577 unsigned VectorBitsMax = Subtarget.getMaxRVVVectorSizeInBits(); 5578 if (VectorBitsMax != 0) 5579 MaxVLMAX = 5580 RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize); 5581 5582 unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL; 5583 MVT IntVT = VecVT.changeVectorElementTypeToInteger(); 5584 5585 // If this is SEW=8 and VLMAX is unknown or more than 256, we need 5586 // to use vrgatherei16.vv. 5587 // TODO: It's also possible to use vrgatherei16.vv for other types to 5588 // decrease register width for the index calculation. 5589 if ((MaxVLMAX == 0 || MaxVLMAX > 256) && EltSize == 8) { 5590 // If this is LMUL=8, we have to split before can use vrgatherei16.vv. 5591 // Reverse each half, then reassemble them in reverse order. 5592 // NOTE: It's also possible that after splitting that VLMAX no longer 5593 // requires vrgatherei16.vv. 5594 if (MinSize == (8 * RISCV::RVVBitsPerBlock)) { 5595 SDValue Lo, Hi; 5596 std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0); 5597 EVT LoVT, HiVT; 5598 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VecVT); 5599 Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo); 5600 Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi); 5601 // Reassemble the low and high pieces reversed. 5602 // FIXME: This is a CONCAT_VECTORS. 5603 SDValue Res = 5604 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi, 5605 DAG.getIntPtrConstant(0, DL)); 5606 return DAG.getNode( 5607 ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo, 5608 DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL)); 5609 } 5610 5611 // Just promote the int type to i16 which will double the LMUL. 5612 IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount()); 5613 GatherOpc = RISCVISD::VRGATHEREI16_VV_VL; 5614 } 5615 5616 MVT XLenVT = Subtarget.getXLenVT(); 5617 SDValue Mask, VL; 5618 std::tie(Mask, VL) = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget); 5619 5620 // Calculate VLMAX-1 for the desired SEW. 5621 unsigned MinElts = VecVT.getVectorMinNumElements(); 5622 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5623 DAG.getConstant(MinElts, DL, XLenVT)); 5624 SDValue VLMinus1 = 5625 DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT)); 5626 5627 // Splat VLMAX-1 taking care to handle SEW==64 on RV32. 5628 bool IsRV32E64 = 5629 !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64; 5630 SDValue SplatVL; 5631 if (!IsRV32E64) 5632 SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1); 5633 else 5634 SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT), 5635 VLMinus1, DAG.getRegister(RISCV::X0, XLenVT)); 5636 5637 SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL); 5638 SDValue Indices = 5639 DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID, Mask, VL); 5640 5641 return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices, Mask, VL); 5642 } 5643 5644 SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op, 5645 SelectionDAG &DAG) const { 5646 SDLoc DL(Op); 5647 SDValue V1 = Op.getOperand(0); 5648 SDValue V2 = Op.getOperand(1); 5649 MVT XLenVT = Subtarget.getXLenVT(); 5650 MVT VecVT = Op.getSimpleValueType(); 5651 5652 unsigned MinElts = VecVT.getVectorMinNumElements(); 5653 SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT, 5654 DAG.getConstant(MinElts, DL, XLenVT)); 5655 5656 int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue(); 5657 SDValue DownOffset, UpOffset; 5658 if (ImmValue >= 0) { 5659 // The operand is a TargetConstant, we need to rebuild it as a regular 5660 // constant. 5661 DownOffset = DAG.getConstant(ImmValue, DL, XLenVT); 5662 UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset); 5663 } else { 5664 // The operand is a TargetConstant, we need to rebuild it as a regular 5665 // constant rather than negating the original operand. 5666 UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT); 5667 DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset); 5668 } 5669 5670 SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG); 5671 5672 SDValue SlideDown = 5673 DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VecVT, DAG.getUNDEF(VecVT), V1, 5674 DownOffset, TrueMask, UpOffset); 5675 return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VecVT, SlideDown, V2, UpOffset, 5676 TrueMask, 5677 DAG.getTargetConstant(RISCV::VLMaxSentinel, DL, XLenVT)); 5678 } 5679 5680 SDValue 5681 RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op, 5682 SelectionDAG &DAG) const { 5683 SDLoc DL(Op); 5684 auto *Load = cast<LoadSDNode>(Op); 5685 5686 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5687 Load->getMemoryVT(), 5688 *Load->getMemOperand()) && 5689 "Expecting a correctly-aligned load"); 5690 5691 MVT VT = Op.getSimpleValueType(); 5692 MVT XLenVT = Subtarget.getXLenVT(); 5693 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5694 5695 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5696 5697 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5698 SDValue IntID = DAG.getTargetConstant( 5699 IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT); 5700 SmallVector<SDValue, 4> Ops{Load->getChain(), IntID}; 5701 if (!IsMaskOp) 5702 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5703 Ops.push_back(Load->getBasePtr()); 5704 Ops.push_back(VL); 5705 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5706 SDValue NewLoad = 5707 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, 5708 Load->getMemoryVT(), Load->getMemOperand()); 5709 5710 SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget); 5711 return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL); 5712 } 5713 5714 SDValue 5715 RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op, 5716 SelectionDAG &DAG) const { 5717 SDLoc DL(Op); 5718 auto *Store = cast<StoreSDNode>(Op); 5719 5720 assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(), 5721 Store->getMemoryVT(), 5722 *Store->getMemOperand()) && 5723 "Expecting a correctly-aligned store"); 5724 5725 SDValue StoreVal = Store->getValue(); 5726 MVT VT = StoreVal.getSimpleValueType(); 5727 MVT XLenVT = Subtarget.getXLenVT(); 5728 5729 // If the size less than a byte, we need to pad with zeros to make a byte. 5730 if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) { 5731 VT = MVT::v8i1; 5732 StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, 5733 DAG.getConstant(0, DL, VT), StoreVal, 5734 DAG.getIntPtrConstant(0, DL)); 5735 } 5736 5737 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5738 5739 SDValue VL = DAG.getConstant(VT.getVectorNumElements(), DL, XLenVT); 5740 5741 SDValue NewValue = 5742 convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget); 5743 5744 bool IsMaskOp = VT.getVectorElementType() == MVT::i1; 5745 SDValue IntID = DAG.getTargetConstant( 5746 IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT); 5747 return DAG.getMemIntrinsicNode( 5748 ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other), 5749 {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL}, 5750 Store->getMemoryVT(), Store->getMemOperand()); 5751 } 5752 5753 SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op, 5754 SelectionDAG &DAG) const { 5755 SDLoc DL(Op); 5756 MVT VT = Op.getSimpleValueType(); 5757 5758 const auto *MemSD = cast<MemSDNode>(Op); 5759 EVT MemVT = MemSD->getMemoryVT(); 5760 MachineMemOperand *MMO = MemSD->getMemOperand(); 5761 SDValue Chain = MemSD->getChain(); 5762 SDValue BasePtr = MemSD->getBasePtr(); 5763 5764 SDValue Mask, PassThru, VL; 5765 if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) { 5766 Mask = VPLoad->getMask(); 5767 PassThru = DAG.getUNDEF(VT); 5768 VL = VPLoad->getVectorLength(); 5769 } else { 5770 const auto *MLoad = cast<MaskedLoadSDNode>(Op); 5771 Mask = MLoad->getMask(); 5772 PassThru = MLoad->getPassThru(); 5773 } 5774 5775 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5776 5777 MVT XLenVT = Subtarget.getXLenVT(); 5778 5779 MVT ContainerVT = VT; 5780 if (VT.isFixedLengthVector()) { 5781 ContainerVT = getContainerForFixedLengthVector(VT); 5782 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 5783 if (!IsUnmasked) { 5784 MVT MaskVT = getMaskTypeFor(ContainerVT); 5785 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5786 } 5787 } 5788 5789 if (!VL) 5790 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5791 5792 unsigned IntID = 5793 IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask; 5794 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5795 if (IsUnmasked) 5796 Ops.push_back(DAG.getUNDEF(ContainerVT)); 5797 else 5798 Ops.push_back(PassThru); 5799 Ops.push_back(BasePtr); 5800 if (!IsUnmasked) 5801 Ops.push_back(Mask); 5802 Ops.push_back(VL); 5803 if (!IsUnmasked) 5804 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 5805 5806 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 5807 5808 SDValue Result = 5809 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 5810 Chain = Result.getValue(1); 5811 5812 if (VT.isFixedLengthVector()) 5813 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 5814 5815 return DAG.getMergeValues({Result, Chain}, DL); 5816 } 5817 5818 SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op, 5819 SelectionDAG &DAG) const { 5820 SDLoc DL(Op); 5821 5822 const auto *MemSD = cast<MemSDNode>(Op); 5823 EVT MemVT = MemSD->getMemoryVT(); 5824 MachineMemOperand *MMO = MemSD->getMemOperand(); 5825 SDValue Chain = MemSD->getChain(); 5826 SDValue BasePtr = MemSD->getBasePtr(); 5827 SDValue Val, Mask, VL; 5828 5829 if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) { 5830 Val = VPStore->getValue(); 5831 Mask = VPStore->getMask(); 5832 VL = VPStore->getVectorLength(); 5833 } else { 5834 const auto *MStore = cast<MaskedStoreSDNode>(Op); 5835 Val = MStore->getValue(); 5836 Mask = MStore->getMask(); 5837 } 5838 5839 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 5840 5841 MVT VT = Val.getSimpleValueType(); 5842 MVT XLenVT = Subtarget.getXLenVT(); 5843 5844 MVT ContainerVT = VT; 5845 if (VT.isFixedLengthVector()) { 5846 ContainerVT = getContainerForFixedLengthVector(VT); 5847 5848 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 5849 if (!IsUnmasked) { 5850 MVT MaskVT = getMaskTypeFor(ContainerVT); 5851 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 5852 } 5853 } 5854 5855 if (!VL) 5856 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 5857 5858 unsigned IntID = 5859 IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask; 5860 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 5861 Ops.push_back(Val); 5862 Ops.push_back(BasePtr); 5863 if (!IsUnmasked) 5864 Ops.push_back(Mask); 5865 Ops.push_back(VL); 5866 5867 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 5868 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 5869 } 5870 5871 SDValue 5872 RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op, 5873 SelectionDAG &DAG) const { 5874 MVT InVT = Op.getOperand(0).getSimpleValueType(); 5875 MVT ContainerVT = getContainerForFixedLengthVector(InVT); 5876 5877 MVT VT = Op.getSimpleValueType(); 5878 5879 SDValue Op1 = 5880 convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget); 5881 SDValue Op2 = 5882 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5883 5884 SDLoc DL(Op); 5885 SDValue VL = 5886 DAG.getConstant(VT.getVectorNumElements(), DL, Subtarget.getXLenVT()); 5887 5888 MVT MaskVT = getMaskTypeFor(ContainerVT); 5889 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 5890 5891 SDValue Cmp = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT, Op1, Op2, 5892 Op.getOperand(2), Mask, VL); 5893 5894 return convertFromScalableVector(VT, Cmp, DAG, Subtarget); 5895 } 5896 5897 SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV( 5898 SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const { 5899 MVT VT = Op.getSimpleValueType(); 5900 5901 if (VT.getVectorElementType() == MVT::i1) 5902 return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMask*/ false); 5903 5904 return lowerToScalableOp(Op, DAG, VecOpc, /*HasMask*/ true); 5905 } 5906 5907 SDValue 5908 RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op, 5909 SelectionDAG &DAG) const { 5910 unsigned Opc; 5911 switch (Op.getOpcode()) { 5912 default: llvm_unreachable("Unexpected opcode!"); 5913 case ISD::SHL: Opc = RISCVISD::SHL_VL; break; 5914 case ISD::SRA: Opc = RISCVISD::SRA_VL; break; 5915 case ISD::SRL: Opc = RISCVISD::SRL_VL; break; 5916 } 5917 5918 return lowerToScalableOp(Op, DAG, Opc); 5919 } 5920 5921 // Lower vector ABS to smax(X, sub(0, X)). 5922 SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const { 5923 SDLoc DL(Op); 5924 MVT VT = Op.getSimpleValueType(); 5925 SDValue X = Op.getOperand(0); 5926 5927 assert(VT.isFixedLengthVector() && "Unexpected type"); 5928 5929 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5930 X = convertToScalableVector(ContainerVT, X, DAG, Subtarget); 5931 5932 SDValue Mask, VL; 5933 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5934 5935 SDValue SplatZero = DAG.getNode( 5936 RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT), 5937 DAG.getConstant(0, DL, Subtarget.getXLenVT())); 5938 SDValue NegX = 5939 DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X, Mask, VL); 5940 SDValue Max = 5941 DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX, Mask, VL); 5942 5943 return convertFromScalableVector(VT, Max, DAG, Subtarget); 5944 } 5945 5946 SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV( 5947 SDValue Op, SelectionDAG &DAG) const { 5948 SDLoc DL(Op); 5949 MVT VT = Op.getSimpleValueType(); 5950 SDValue Mag = Op.getOperand(0); 5951 SDValue Sign = Op.getOperand(1); 5952 assert(Mag.getValueType() == Sign.getValueType() && 5953 "Can only handle COPYSIGN with matching types."); 5954 5955 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5956 Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget); 5957 Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget); 5958 5959 SDValue Mask, VL; 5960 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5961 5962 SDValue CopySign = 5963 DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag, Sign, Mask, VL); 5964 5965 return convertFromScalableVector(VT, CopySign, DAG, Subtarget); 5966 } 5967 5968 SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV( 5969 SDValue Op, SelectionDAG &DAG) const { 5970 MVT VT = Op.getSimpleValueType(); 5971 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5972 5973 MVT I1ContainerVT = 5974 MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 5975 5976 SDValue CC = 5977 convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget); 5978 SDValue Op1 = 5979 convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget); 5980 SDValue Op2 = 5981 convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget); 5982 5983 SDLoc DL(Op); 5984 SDValue Mask, VL; 5985 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 5986 5987 SDValue Select = 5988 DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL); 5989 5990 return convertFromScalableVector(VT, Select, DAG, Subtarget); 5991 } 5992 5993 SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG, 5994 unsigned NewOpc, 5995 bool HasMask) const { 5996 MVT VT = Op.getSimpleValueType(); 5997 MVT ContainerVT = getContainerForFixedLengthVector(VT); 5998 5999 // Create list of operands by converting existing ones to scalable types. 6000 SmallVector<SDValue, 6> Ops; 6001 for (const SDValue &V : Op->op_values()) { 6002 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6003 6004 // Pass through non-vector operands. 6005 if (!V.getValueType().isVector()) { 6006 Ops.push_back(V); 6007 continue; 6008 } 6009 6010 // "cast" fixed length vector to a scalable vector. 6011 assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) && 6012 "Only fixed length vectors are supported!"); 6013 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6014 } 6015 6016 SDLoc DL(Op); 6017 SDValue Mask, VL; 6018 std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget); 6019 if (HasMask) 6020 Ops.push_back(Mask); 6021 Ops.push_back(VL); 6022 6023 SDValue ScalableRes = DAG.getNode(NewOpc, DL, ContainerVT, Ops); 6024 return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget); 6025 } 6026 6027 // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node: 6028 // * Operands of each node are assumed to be in the same order. 6029 // * The EVL operand is promoted from i32 to i64 on RV64. 6030 // * Fixed-length vectors are converted to their scalable-vector container 6031 // types. 6032 SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG, 6033 unsigned RISCVISDOpc) const { 6034 SDLoc DL(Op); 6035 MVT VT = Op.getSimpleValueType(); 6036 SmallVector<SDValue, 4> Ops; 6037 6038 for (const auto &OpIdx : enumerate(Op->ops())) { 6039 SDValue V = OpIdx.value(); 6040 assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!"); 6041 // Pass through operands which aren't fixed-length vectors. 6042 if (!V.getValueType().isFixedLengthVector()) { 6043 Ops.push_back(V); 6044 continue; 6045 } 6046 // "cast" fixed length vector to a scalable vector. 6047 MVT OpVT = V.getSimpleValueType(); 6048 MVT ContainerVT = getContainerForFixedLengthVector(OpVT); 6049 assert(useRVVForFixedLengthVectorVT(OpVT) && 6050 "Only fixed length vectors are supported!"); 6051 Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget)); 6052 } 6053 6054 if (!VT.isFixedLengthVector()) 6055 return DAG.getNode(RISCVISDOpc, DL, VT, Ops, Op->getFlags()); 6056 6057 MVT ContainerVT = getContainerForFixedLengthVector(VT); 6058 6059 SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops, Op->getFlags()); 6060 6061 return convertFromScalableVector(VT, VPOp, DAG, Subtarget); 6062 } 6063 6064 SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op, 6065 SelectionDAG &DAG) const { 6066 SDLoc DL(Op); 6067 MVT VT = Op.getSimpleValueType(); 6068 6069 SDValue Src = Op.getOperand(0); 6070 // NOTE: Mask is dropped. 6071 SDValue VL = Op.getOperand(2); 6072 6073 MVT ContainerVT = VT; 6074 if (VT.isFixedLengthVector()) { 6075 ContainerVT = getContainerForFixedLengthVector(VT); 6076 MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount()); 6077 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6078 } 6079 6080 MVT XLenVT = Subtarget.getXLenVT(); 6081 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6082 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6083 DAG.getUNDEF(ContainerVT), Zero, VL); 6084 6085 SDValue SplatValue = DAG.getConstant( 6086 Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT); 6087 SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 6088 DAG.getUNDEF(ContainerVT), SplatValue, VL); 6089 6090 SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src, 6091 Splat, ZeroSplat, VL); 6092 if (!VT.isFixedLengthVector()) 6093 return Result; 6094 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6095 } 6096 6097 SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op, 6098 SelectionDAG &DAG) const { 6099 SDLoc DL(Op); 6100 MVT VT = Op.getSimpleValueType(); 6101 6102 SDValue Op1 = Op.getOperand(0); 6103 SDValue Op2 = Op.getOperand(1); 6104 ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get(); 6105 // NOTE: Mask is dropped. 6106 SDValue VL = Op.getOperand(4); 6107 6108 MVT ContainerVT = VT; 6109 if (VT.isFixedLengthVector()) { 6110 ContainerVT = getContainerForFixedLengthVector(VT); 6111 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6112 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6113 } 6114 6115 SDValue Result; 6116 SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL); 6117 6118 switch (Condition) { 6119 default: 6120 break; 6121 // X != Y --> (X^Y) 6122 case ISD::SETNE: 6123 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6124 break; 6125 // X == Y --> ~(X^Y) 6126 case ISD::SETEQ: { 6127 SDValue Temp = 6128 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL); 6129 Result = 6130 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL); 6131 break; 6132 } 6133 // X >s Y --> X == 0 & Y == 1 --> ~X & Y 6134 // X <u Y --> X == 0 & Y == 1 --> ~X & Y 6135 case ISD::SETGT: 6136 case ISD::SETULT: { 6137 SDValue Temp = 6138 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6139 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL); 6140 break; 6141 } 6142 // X <s Y --> X == 1 & Y == 0 --> ~Y & X 6143 // X >u Y --> X == 1 & Y == 0 --> ~Y & X 6144 case ISD::SETLT: 6145 case ISD::SETUGT: { 6146 SDValue Temp = 6147 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6148 Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL); 6149 break; 6150 } 6151 // X >=s Y --> X == 0 | Y == 1 --> ~X | Y 6152 // X <=u Y --> X == 0 | Y == 1 --> ~X | Y 6153 case ISD::SETGE: 6154 case ISD::SETULE: { 6155 SDValue Temp = 6156 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL); 6157 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL); 6158 break; 6159 } 6160 // X <=s Y --> X == 1 | Y == 0 --> ~Y | X 6161 // X >=u Y --> X == 1 | Y == 0 --> ~Y | X 6162 case ISD::SETLE: 6163 case ISD::SETUGE: { 6164 SDValue Temp = 6165 DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL); 6166 Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL); 6167 break; 6168 } 6169 } 6170 6171 if (!VT.isFixedLengthVector()) 6172 return Result; 6173 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6174 } 6175 6176 // Lower Floating-Point/Integer Type-Convert VP SDNodes 6177 SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG, 6178 unsigned RISCVISDOpc) const { 6179 SDLoc DL(Op); 6180 6181 SDValue Src = Op.getOperand(0); 6182 SDValue Mask = Op.getOperand(1); 6183 SDValue VL = Op.getOperand(2); 6184 6185 MVT DstVT = Op.getSimpleValueType(); 6186 MVT SrcVT = Src.getSimpleValueType(); 6187 if (DstVT.isFixedLengthVector()) { 6188 DstVT = getContainerForFixedLengthVector(DstVT); 6189 SrcVT = getContainerForFixedLengthVector(SrcVT); 6190 Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget); 6191 MVT MaskVT = getMaskTypeFor(DstVT); 6192 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6193 } 6194 6195 unsigned RISCVISDExtOpc = (RISCVISDOpc == RISCVISD::SINT_TO_FP_VL || 6196 RISCVISDOpc == RISCVISD::FP_TO_SINT_VL) 6197 ? RISCVISD::VSEXT_VL 6198 : RISCVISD::VZEXT_VL; 6199 6200 unsigned DstEltSize = DstVT.getScalarSizeInBits(); 6201 unsigned SrcEltSize = SrcVT.getScalarSizeInBits(); 6202 6203 SDValue Result; 6204 if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion. 6205 if (SrcVT.isInteger()) { 6206 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6207 6208 // Do we need to do any pre-widening before converting? 6209 if (SrcEltSize == 1) { 6210 MVT IntVT = DstVT.changeVectorElementTypeToInteger(); 6211 MVT XLenVT = Subtarget.getXLenVT(); 6212 SDValue Zero = DAG.getConstant(0, DL, XLenVT); 6213 SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6214 DAG.getUNDEF(IntVT), Zero, VL); 6215 SDValue One = DAG.getConstant( 6216 RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT); 6217 SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, 6218 DAG.getUNDEF(IntVT), One, VL); 6219 Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat, 6220 ZeroSplat, VL); 6221 } else if (DstEltSize > (2 * SrcEltSize)) { 6222 // Widen before converting. 6223 MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2), 6224 DstVT.getVectorElementCount()); 6225 Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL); 6226 } 6227 6228 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6229 } else { 6230 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6231 "Wrong input/output vector types"); 6232 6233 // Convert f16 to f32 then convert f32 to i64. 6234 if (DstEltSize > (2 * SrcEltSize)) { 6235 assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6236 MVT InterimFVT = 6237 MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6238 Src = 6239 DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL); 6240 } 6241 6242 Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL); 6243 } 6244 } else { // Narrowing + Conversion 6245 if (SrcVT.isInteger()) { 6246 assert(DstVT.isFloatingPoint() && "Wrong input/output vector types"); 6247 // First do a narrowing convert to an FP type half the size, then round 6248 // the FP type to a small FP type if needed. 6249 6250 MVT InterimFVT = DstVT; 6251 if (SrcEltSize > (2 * DstEltSize)) { 6252 assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!"); 6253 assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!"); 6254 InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount()); 6255 } 6256 6257 Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL); 6258 6259 if (InterimFVT != DstVT) { 6260 Src = Result; 6261 Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL); 6262 } 6263 } else { 6264 assert(SrcVT.isFloatingPoint() && DstVT.isInteger() && 6265 "Wrong input/output vector types"); 6266 // First do a narrowing conversion to an integer half the size, then 6267 // truncate if needed. 6268 6269 if (DstEltSize == 1) { 6270 // First convert to the same size integer, then convert to mask using 6271 // setcc. 6272 assert(SrcEltSize >= 16 && "Unexpected FP type!"); 6273 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize), 6274 DstVT.getVectorElementCount()); 6275 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6276 6277 // Compare the integer result to 0. The integer should be 0 or 1/-1, 6278 // otherwise the conversion was undefined. 6279 MVT XLenVT = Subtarget.getXLenVT(); 6280 SDValue SplatZero = DAG.getConstant(0, DL, XLenVT); 6281 SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT, 6282 DAG.getUNDEF(InterimIVT), SplatZero); 6283 Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT, Result, SplatZero, 6284 DAG.getCondCode(ISD::SETNE), Mask, VL); 6285 } else { 6286 MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6287 DstVT.getVectorElementCount()); 6288 6289 Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL); 6290 6291 while (InterimIVT != DstVT) { 6292 SrcEltSize /= 2; 6293 Src = Result; 6294 InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2), 6295 DstVT.getVectorElementCount()); 6296 Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT, 6297 Src, Mask, VL); 6298 } 6299 } 6300 } 6301 } 6302 6303 MVT VT = Op.getSimpleValueType(); 6304 if (!VT.isFixedLengthVector()) 6305 return Result; 6306 return convertFromScalableVector(VT, Result, DAG, Subtarget); 6307 } 6308 6309 SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG, 6310 unsigned MaskOpc, 6311 unsigned VecOpc) const { 6312 MVT VT = Op.getSimpleValueType(); 6313 if (VT.getVectorElementType() != MVT::i1) 6314 return lowerVPOp(Op, DAG, VecOpc); 6315 6316 // It is safe to drop mask parameter as masked-off elements are undef. 6317 SDValue Op1 = Op->getOperand(0); 6318 SDValue Op2 = Op->getOperand(1); 6319 SDValue VL = Op->getOperand(3); 6320 6321 MVT ContainerVT = VT; 6322 const bool IsFixed = VT.isFixedLengthVector(); 6323 if (IsFixed) { 6324 ContainerVT = getContainerForFixedLengthVector(VT); 6325 Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget); 6326 Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget); 6327 } 6328 6329 SDLoc DL(Op); 6330 SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL); 6331 if (!IsFixed) 6332 return Val; 6333 return convertFromScalableVector(VT, Val, DAG, Subtarget); 6334 } 6335 6336 // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be 6337 // matched to a RVV indexed load. The RVV indexed load instructions only 6338 // support the "unsigned unscaled" addressing mode; indices are implicitly 6339 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6340 // signed or scaled indexing is extended to the XLEN value type and scaled 6341 // accordingly. 6342 SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op, 6343 SelectionDAG &DAG) const { 6344 SDLoc DL(Op); 6345 MVT VT = Op.getSimpleValueType(); 6346 6347 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6348 EVT MemVT = MemSD->getMemoryVT(); 6349 MachineMemOperand *MMO = MemSD->getMemOperand(); 6350 SDValue Chain = MemSD->getChain(); 6351 SDValue BasePtr = MemSD->getBasePtr(); 6352 6353 ISD::LoadExtType LoadExtType; 6354 SDValue Index, Mask, PassThru, VL; 6355 6356 if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) { 6357 Index = VPGN->getIndex(); 6358 Mask = VPGN->getMask(); 6359 PassThru = DAG.getUNDEF(VT); 6360 VL = VPGN->getVectorLength(); 6361 // VP doesn't support extending loads. 6362 LoadExtType = ISD::NON_EXTLOAD; 6363 } else { 6364 // Else it must be a MGATHER. 6365 auto *MGN = cast<MaskedGatherSDNode>(Op.getNode()); 6366 Index = MGN->getIndex(); 6367 Mask = MGN->getMask(); 6368 PassThru = MGN->getPassThru(); 6369 LoadExtType = MGN->getExtensionType(); 6370 } 6371 6372 MVT IndexVT = Index.getSimpleValueType(); 6373 MVT XLenVT = Subtarget.getXLenVT(); 6374 6375 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6376 "Unexpected VTs!"); 6377 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6378 // Targets have to explicitly opt-in for extending vector loads. 6379 assert(LoadExtType == ISD::NON_EXTLOAD && 6380 "Unexpected extending MGATHER/VP_GATHER"); 6381 (void)LoadExtType; 6382 6383 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6384 // the selection of the masked intrinsics doesn't do this for us. 6385 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6386 6387 MVT ContainerVT = VT; 6388 if (VT.isFixedLengthVector()) { 6389 ContainerVT = getContainerForFixedLengthVector(VT); 6390 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6391 ContainerVT.getVectorElementCount()); 6392 6393 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6394 6395 if (!IsUnmasked) { 6396 MVT MaskVT = getMaskTypeFor(ContainerVT); 6397 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6398 PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget); 6399 } 6400 } 6401 6402 if (!VL) 6403 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6404 6405 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6406 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6407 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6408 VL); 6409 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6410 TrueMask, VL); 6411 } 6412 6413 unsigned IntID = 6414 IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask; 6415 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6416 if (IsUnmasked) 6417 Ops.push_back(DAG.getUNDEF(ContainerVT)); 6418 else 6419 Ops.push_back(PassThru); 6420 Ops.push_back(BasePtr); 6421 Ops.push_back(Index); 6422 if (!IsUnmasked) 6423 Ops.push_back(Mask); 6424 Ops.push_back(VL); 6425 if (!IsUnmasked) 6426 Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT)); 6427 6428 SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other}); 6429 SDValue Result = 6430 DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO); 6431 Chain = Result.getValue(1); 6432 6433 if (VT.isFixedLengthVector()) 6434 Result = convertFromScalableVector(VT, Result, DAG, Subtarget); 6435 6436 return DAG.getMergeValues({Result, Chain}, DL); 6437 } 6438 6439 // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be 6440 // matched to a RVV indexed store. The RVV indexed store instructions only 6441 // support the "unsigned unscaled" addressing mode; indices are implicitly 6442 // zero-extended or truncated to XLEN and are treated as byte offsets. Any 6443 // signed or scaled indexing is extended to the XLEN value type and scaled 6444 // accordingly. 6445 SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op, 6446 SelectionDAG &DAG) const { 6447 SDLoc DL(Op); 6448 const auto *MemSD = cast<MemSDNode>(Op.getNode()); 6449 EVT MemVT = MemSD->getMemoryVT(); 6450 MachineMemOperand *MMO = MemSD->getMemOperand(); 6451 SDValue Chain = MemSD->getChain(); 6452 SDValue BasePtr = MemSD->getBasePtr(); 6453 6454 bool IsTruncatingStore = false; 6455 SDValue Index, Mask, Val, VL; 6456 6457 if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) { 6458 Index = VPSN->getIndex(); 6459 Mask = VPSN->getMask(); 6460 Val = VPSN->getValue(); 6461 VL = VPSN->getVectorLength(); 6462 // VP doesn't support truncating stores. 6463 IsTruncatingStore = false; 6464 } else { 6465 // Else it must be a MSCATTER. 6466 auto *MSN = cast<MaskedScatterSDNode>(Op.getNode()); 6467 Index = MSN->getIndex(); 6468 Mask = MSN->getMask(); 6469 Val = MSN->getValue(); 6470 IsTruncatingStore = MSN->isTruncatingStore(); 6471 } 6472 6473 MVT VT = Val.getSimpleValueType(); 6474 MVT IndexVT = Index.getSimpleValueType(); 6475 MVT XLenVT = Subtarget.getXLenVT(); 6476 6477 assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() && 6478 "Unexpected VTs!"); 6479 assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type"); 6480 // Targets have to explicitly opt-in for extending vector loads and 6481 // truncating vector stores. 6482 assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER"); 6483 (void)IsTruncatingStore; 6484 6485 // If the mask is known to be all ones, optimize to an unmasked intrinsic; 6486 // the selection of the masked intrinsics doesn't do this for us. 6487 bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode()); 6488 6489 MVT ContainerVT = VT; 6490 if (VT.isFixedLengthVector()) { 6491 ContainerVT = getContainerForFixedLengthVector(VT); 6492 IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(), 6493 ContainerVT.getVectorElementCount()); 6494 6495 Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget); 6496 Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget); 6497 6498 if (!IsUnmasked) { 6499 MVT MaskVT = getMaskTypeFor(ContainerVT); 6500 Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget); 6501 } 6502 } 6503 6504 if (!VL) 6505 VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second; 6506 6507 if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) { 6508 IndexVT = IndexVT.changeVectorElementType(XLenVT); 6509 SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(), 6510 VL); 6511 Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index, 6512 TrueMask, VL); 6513 } 6514 6515 unsigned IntID = 6516 IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask; 6517 SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)}; 6518 Ops.push_back(Val); 6519 Ops.push_back(BasePtr); 6520 Ops.push_back(Index); 6521 if (!IsUnmasked) 6522 Ops.push_back(Mask); 6523 Ops.push_back(VL); 6524 6525 return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, 6526 DAG.getVTList(MVT::Other), Ops, MemVT, MMO); 6527 } 6528 6529 SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op, 6530 SelectionDAG &DAG) const { 6531 const MVT XLenVT = Subtarget.getXLenVT(); 6532 SDLoc DL(Op); 6533 SDValue Chain = Op->getOperand(0); 6534 SDValue SysRegNo = DAG.getTargetConstant( 6535 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6536 SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other); 6537 SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo); 6538 6539 // Encoding used for rounding mode in RISCV differs from that used in 6540 // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a 6541 // table, which consists of a sequence of 4-bit fields, each representing 6542 // corresponding FLT_ROUNDS mode. 6543 static const int Table = 6544 (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) | 6545 (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) | 6546 (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) | 6547 (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) | 6548 (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM); 6549 6550 SDValue Shift = 6551 DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT)); 6552 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6553 DAG.getConstant(Table, DL, XLenVT), Shift); 6554 SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6555 DAG.getConstant(7, DL, XLenVT)); 6556 6557 return DAG.getMergeValues({Masked, Chain}, DL); 6558 } 6559 6560 SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op, 6561 SelectionDAG &DAG) const { 6562 const MVT XLenVT = Subtarget.getXLenVT(); 6563 SDLoc DL(Op); 6564 SDValue Chain = Op->getOperand(0); 6565 SDValue RMValue = Op->getOperand(1); 6566 SDValue SysRegNo = DAG.getTargetConstant( 6567 RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT); 6568 6569 // Encoding used for rounding mode in RISCV differs from that used in 6570 // FLT_ROUNDS. To convert it the C rounding mode is used as an index in 6571 // a table, which consists of a sequence of 4-bit fields, each representing 6572 // corresponding RISCV mode. 6573 static const unsigned Table = 6574 (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) | 6575 (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) | 6576 (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) | 6577 (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) | 6578 (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway)); 6579 6580 SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue, 6581 DAG.getConstant(2, DL, XLenVT)); 6582 SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT, 6583 DAG.getConstant(Table, DL, XLenVT), Shift); 6584 RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted, 6585 DAG.getConstant(0x7, DL, XLenVT)); 6586 return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo, 6587 RMValue); 6588 } 6589 6590 static RISCVISD::NodeType getRISCVWOpcodeByIntr(unsigned IntNo) { 6591 switch (IntNo) { 6592 default: 6593 llvm_unreachable("Unexpected Intrinsic"); 6594 case Intrinsic::riscv_bcompress: 6595 return RISCVISD::BCOMPRESSW; 6596 case Intrinsic::riscv_bdecompress: 6597 return RISCVISD::BDECOMPRESSW; 6598 case Intrinsic::riscv_bfp: 6599 return RISCVISD::BFPW; 6600 case Intrinsic::riscv_fsl: 6601 return RISCVISD::FSLW; 6602 case Intrinsic::riscv_fsr: 6603 return RISCVISD::FSRW; 6604 } 6605 } 6606 6607 // Converts the given intrinsic to a i64 operation with any extension. 6608 static SDValue customLegalizeToWOpByIntr(SDNode *N, SelectionDAG &DAG, 6609 unsigned IntNo) { 6610 SDLoc DL(N); 6611 RISCVISD::NodeType WOpcode = getRISCVWOpcodeByIntr(IntNo); 6612 // Deal with the Instruction Operands 6613 SmallVector<SDValue, 3> NewOps; 6614 for (SDValue Op : drop_begin(N->ops())) 6615 // Promote the operand to i64 type 6616 NewOps.push_back(DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op)); 6617 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOps); 6618 // ReplaceNodeResults requires we maintain the same type for the return value. 6619 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6620 } 6621 6622 // Returns the opcode of the target-specific SDNode that implements the 32-bit 6623 // form of the given Opcode. 6624 static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) { 6625 switch (Opcode) { 6626 default: 6627 llvm_unreachable("Unexpected opcode"); 6628 case ISD::SHL: 6629 return RISCVISD::SLLW; 6630 case ISD::SRA: 6631 return RISCVISD::SRAW; 6632 case ISD::SRL: 6633 return RISCVISD::SRLW; 6634 case ISD::SDIV: 6635 return RISCVISD::DIVW; 6636 case ISD::UDIV: 6637 return RISCVISD::DIVUW; 6638 case ISD::UREM: 6639 return RISCVISD::REMUW; 6640 case ISD::ROTL: 6641 return RISCVISD::ROLW; 6642 case ISD::ROTR: 6643 return RISCVISD::RORW; 6644 } 6645 } 6646 6647 // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG 6648 // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would 6649 // otherwise be promoted to i64, making it difficult to select the 6650 // SLLW/DIVUW/.../*W later one because the fact the operation was originally of 6651 // type i8/i16/i32 is lost. 6652 static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG, 6653 unsigned ExtOpc = ISD::ANY_EXTEND) { 6654 SDLoc DL(N); 6655 RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode()); 6656 SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0)); 6657 SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1)); 6658 SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1); 6659 // ReplaceNodeResults requires we maintain the same type for the return value. 6660 return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes); 6661 } 6662 6663 // Converts the given 32-bit operation to a i64 operation with signed extension 6664 // semantic to reduce the signed extension instructions. 6665 static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) { 6666 SDLoc DL(N); 6667 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6668 SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6669 SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1); 6670 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6671 DAG.getValueType(MVT::i32)); 6672 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes); 6673 } 6674 6675 void RISCVTargetLowering::ReplaceNodeResults(SDNode *N, 6676 SmallVectorImpl<SDValue> &Results, 6677 SelectionDAG &DAG) const { 6678 SDLoc DL(N); 6679 switch (N->getOpcode()) { 6680 default: 6681 llvm_unreachable("Don't know how to custom type legalize this operation!"); 6682 case ISD::STRICT_FP_TO_SINT: 6683 case ISD::STRICT_FP_TO_UINT: 6684 case ISD::FP_TO_SINT: 6685 case ISD::FP_TO_UINT: { 6686 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6687 "Unexpected custom legalisation"); 6688 bool IsStrict = N->isStrictFPOpcode(); 6689 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT || 6690 N->getOpcode() == ISD::STRICT_FP_TO_SINT; 6691 SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0); 6692 if (getTypeAction(*DAG.getContext(), Op0.getValueType()) != 6693 TargetLowering::TypeSoftenFloat) { 6694 if (!isTypeLegal(Op0.getValueType())) 6695 return; 6696 if (IsStrict) { 6697 unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64 6698 : RISCVISD::STRICT_FCVT_WU_RV64; 6699 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 6700 SDValue Res = DAG.getNode( 6701 Opc, DL, VTs, N->getOperand(0), Op0, 6702 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6703 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6704 Results.push_back(Res.getValue(1)); 6705 return; 6706 } 6707 unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 6708 SDValue Res = 6709 DAG.getNode(Opc, DL, MVT::i64, Op0, 6710 DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64)); 6711 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6712 return; 6713 } 6714 // If the FP type needs to be softened, emit a library call using the 'si' 6715 // version. If we left it to default legalization we'd end up with 'di'. If 6716 // the FP type doesn't need to be softened just let generic type 6717 // legalization promote the result type. 6718 RTLIB::Libcall LC; 6719 if (IsSigned) 6720 LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0)); 6721 else 6722 LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0)); 6723 MakeLibCallOptions CallOptions; 6724 EVT OpVT = Op0.getValueType(); 6725 CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true); 6726 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue(); 6727 SDValue Result; 6728 std::tie(Result, Chain) = 6729 makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain); 6730 Results.push_back(Result); 6731 if (IsStrict) 6732 Results.push_back(Chain); 6733 break; 6734 } 6735 case ISD::READCYCLECOUNTER: { 6736 assert(!Subtarget.is64Bit() && 6737 "READCYCLECOUNTER only has custom type legalization on riscv32"); 6738 6739 SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other); 6740 SDValue RCW = 6741 DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0)); 6742 6743 Results.push_back( 6744 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1))); 6745 Results.push_back(RCW.getValue(2)); 6746 break; 6747 } 6748 case ISD::MUL: { 6749 unsigned Size = N->getSimpleValueType(0).getSizeInBits(); 6750 unsigned XLen = Subtarget.getXLen(); 6751 // This multiply needs to be expanded, try to use MULHSU+MUL if possible. 6752 if (Size > XLen) { 6753 assert(Size == (XLen * 2) && "Unexpected custom legalisation"); 6754 SDValue LHS = N->getOperand(0); 6755 SDValue RHS = N->getOperand(1); 6756 APInt HighMask = APInt::getHighBitsSet(Size, XLen); 6757 6758 bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask); 6759 bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask); 6760 // We need exactly one side to be unsigned. 6761 if (LHSIsU == RHSIsU) 6762 return; 6763 6764 auto MakeMULPair = [&](SDValue S, SDValue U) { 6765 MVT XLenVT = Subtarget.getXLenVT(); 6766 S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S); 6767 U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U); 6768 SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U); 6769 SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U); 6770 return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi); 6771 }; 6772 6773 bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen; 6774 bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen; 6775 6776 // The other operand should be signed, but still prefer MULH when 6777 // possible. 6778 if (RHSIsU && LHSIsS && !RHSIsS) 6779 Results.push_back(MakeMULPair(LHS, RHS)); 6780 else if (LHSIsU && RHSIsS && !LHSIsS) 6781 Results.push_back(MakeMULPair(RHS, LHS)); 6782 6783 return; 6784 } 6785 LLVM_FALLTHROUGH; 6786 } 6787 case ISD::ADD: 6788 case ISD::SUB: 6789 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6790 "Unexpected custom legalisation"); 6791 Results.push_back(customLegalizeToWOpWithSExt(N, DAG)); 6792 break; 6793 case ISD::SHL: 6794 case ISD::SRA: 6795 case ISD::SRL: 6796 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6797 "Unexpected custom legalisation"); 6798 if (N->getOperand(1).getOpcode() != ISD::Constant) { 6799 // If we can use a BSET instruction, allow default promotion to apply. 6800 if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() && 6801 isOneConstant(N->getOperand(0))) 6802 break; 6803 Results.push_back(customLegalizeToWOp(N, DAG)); 6804 break; 6805 } 6806 6807 // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is 6808 // similar to customLegalizeToWOpWithSExt, but we must zero_extend the 6809 // shift amount. 6810 if (N->getOpcode() == ISD::SHL) { 6811 SDLoc DL(N); 6812 SDValue NewOp0 = 6813 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6814 SDValue NewOp1 = 6815 DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1)); 6816 SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1); 6817 SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp, 6818 DAG.getValueType(MVT::i32)); 6819 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6820 } 6821 6822 break; 6823 case ISD::ROTL: 6824 case ISD::ROTR: 6825 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6826 "Unexpected custom legalisation"); 6827 Results.push_back(customLegalizeToWOp(N, DAG)); 6828 break; 6829 case ISD::CTTZ: 6830 case ISD::CTTZ_ZERO_UNDEF: 6831 case ISD::CTLZ: 6832 case ISD::CTLZ_ZERO_UNDEF: { 6833 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6834 "Unexpected custom legalisation"); 6835 6836 SDValue NewOp0 = 6837 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6838 bool IsCTZ = 6839 N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF; 6840 unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW; 6841 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0); 6842 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6843 return; 6844 } 6845 case ISD::SDIV: 6846 case ISD::UDIV: 6847 case ISD::UREM: { 6848 MVT VT = N->getSimpleValueType(0); 6849 assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) && 6850 Subtarget.is64Bit() && Subtarget.hasStdExtM() && 6851 "Unexpected custom legalisation"); 6852 // Don't promote division/remainder by constant since we should expand those 6853 // to multiply by magic constant. 6854 // FIXME: What if the expansion is disabled for minsize. 6855 if (N->getOperand(1).getOpcode() == ISD::Constant) 6856 return; 6857 6858 // If the input is i32, use ANY_EXTEND since the W instructions don't read 6859 // the upper 32 bits. For other types we need to sign or zero extend 6860 // based on the opcode. 6861 unsigned ExtOpc = ISD::ANY_EXTEND; 6862 if (VT != MVT::i32) 6863 ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND 6864 : ISD::ZERO_EXTEND; 6865 6866 Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc)); 6867 break; 6868 } 6869 case ISD::UADDO: 6870 case ISD::USUBO: { 6871 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6872 "Unexpected custom legalisation"); 6873 bool IsAdd = N->getOpcode() == ISD::UADDO; 6874 // Create an ADDW or SUBW. 6875 SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6876 SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 6877 SDValue Res = 6878 DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS); 6879 Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res, 6880 DAG.getValueType(MVT::i32)); 6881 6882 SDValue Overflow; 6883 if (IsAdd && isOneConstant(RHS)) { 6884 // Special case uaddo X, 1 overflowed if the addition result is 0. 6885 // The general case (X + C) < C is not necessarily beneficial. Although we 6886 // reduce the live range of X, we may introduce the materialization of 6887 // constant C, especially when the setcc result is used by branch. We have 6888 // no compare with constant and branch instructions. 6889 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, 6890 DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ); 6891 } else { 6892 // Sign extend the LHS and perform an unsigned compare with the ADDW 6893 // result. Since the inputs are sign extended from i32, this is equivalent 6894 // to comparing the lower 32 bits. 6895 LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6896 Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS, 6897 IsAdd ? ISD::SETULT : ISD::SETUGT); 6898 } 6899 6900 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6901 Results.push_back(Overflow); 6902 return; 6903 } 6904 case ISD::UADDSAT: 6905 case ISD::USUBSAT: { 6906 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6907 "Unexpected custom legalisation"); 6908 if (Subtarget.hasStdExtZbb()) { 6909 // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using 6910 // sign extend allows overflow of the lower 32 bits to be detected on 6911 // the promoted size. 6912 SDValue LHS = 6913 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6914 SDValue RHS = 6915 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1)); 6916 SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS); 6917 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 6918 return; 6919 } 6920 6921 // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom 6922 // promotion for UADDO/USUBO. 6923 Results.push_back(expandAddSubSat(N, DAG)); 6924 return; 6925 } 6926 case ISD::ABS: { 6927 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 6928 "Unexpected custom legalisation"); 6929 DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0)); 6930 6931 // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y) 6932 6933 SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 6934 6935 // Freeze the source so we can increase it's use count. 6936 Src = DAG.getFreeze(Src); 6937 6938 // Copy sign bit to all bits using the sraiw pattern. 6939 SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src, 6940 DAG.getValueType(MVT::i32)); 6941 SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill, 6942 DAG.getConstant(31, DL, MVT::i64)); 6943 6944 SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill); 6945 NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill); 6946 6947 // NOTE: The result is only required to be anyextended, but sext is 6948 // consistent with type legalization of sub. 6949 NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes, 6950 DAG.getValueType(MVT::i32)); 6951 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes)); 6952 return; 6953 } 6954 case ISD::BITCAST: { 6955 EVT VT = N->getValueType(0); 6956 assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!"); 6957 SDValue Op0 = N->getOperand(0); 6958 EVT Op0VT = Op0.getValueType(); 6959 MVT XLenVT = Subtarget.getXLenVT(); 6960 if (VT == MVT::i16 && Op0VT == MVT::f16 && Subtarget.hasStdExtZfh()) { 6961 SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0); 6962 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv)); 6963 } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() && 6964 Subtarget.hasStdExtF()) { 6965 SDValue FPConv = 6966 DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0); 6967 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv)); 6968 } else if (!VT.isVector() && Op0VT.isFixedLengthVector() && 6969 isTypeLegal(Op0VT)) { 6970 // Custom-legalize bitcasts from fixed-length vector types to illegal 6971 // scalar types in order to improve codegen. Bitcast the vector to a 6972 // one-element vector type whose element type is the same as the result 6973 // type, and extract the first element. 6974 EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1); 6975 if (isTypeLegal(BVT)) { 6976 SDValue BVec = DAG.getBitcast(BVT, Op0); 6977 Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec, 6978 DAG.getConstant(0, DL, XLenVT))); 6979 } 6980 } 6981 break; 6982 } 6983 case RISCVISD::GREV: 6984 case RISCVISD::GORC: 6985 case RISCVISD::SHFL: { 6986 MVT VT = N->getSimpleValueType(0); 6987 MVT XLenVT = Subtarget.getXLenVT(); 6988 assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) && 6989 "Unexpected custom legalisation"); 6990 assert(isa<ConstantSDNode>(N->getOperand(1)) && "Expected constant"); 6991 assert((Subtarget.hasStdExtZbp() || 6992 (Subtarget.hasStdExtZbkb() && N->getOpcode() == RISCVISD::GREV && 6993 N->getConstantOperandVal(1) == 7)) && 6994 "Unexpected extension"); 6995 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 6996 SDValue NewOp1 = 6997 DAG.getNode(ISD::ZERO_EXTEND, DL, XLenVT, N->getOperand(1)); 6998 SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp0, NewOp1); 6999 // ReplaceNodeResults requires we maintain the same type for the return 7000 // value. 7001 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes)); 7002 break; 7003 } 7004 case ISD::BSWAP: 7005 case ISD::BITREVERSE: { 7006 MVT VT = N->getSimpleValueType(0); 7007 MVT XLenVT = Subtarget.getXLenVT(); 7008 assert((VT == MVT::i8 || VT == MVT::i16 || 7009 (VT == MVT::i32 && Subtarget.is64Bit())) && 7010 Subtarget.hasStdExtZbp() && "Unexpected custom legalisation"); 7011 SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0)); 7012 unsigned Imm = VT.getSizeInBits() - 1; 7013 // If this is BSWAP rather than BITREVERSE, clear the lower 3 bits. 7014 if (N->getOpcode() == ISD::BSWAP) 7015 Imm &= ~0x7U; 7016 SDValue GREVI = DAG.getNode(RISCVISD::GREV, DL, XLenVT, NewOp0, 7017 DAG.getConstant(Imm, DL, XLenVT)); 7018 // ReplaceNodeResults requires we maintain the same type for the return 7019 // value. 7020 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, GREVI)); 7021 break; 7022 } 7023 case ISD::FSHL: 7024 case ISD::FSHR: { 7025 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7026 Subtarget.hasStdExtZbt() && "Unexpected custom legalisation"); 7027 SDValue NewOp0 = 7028 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0)); 7029 SDValue NewOp1 = 7030 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7031 SDValue NewShAmt = 7032 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7033 // FSLW/FSRW take a 6 bit shift amount but i32 FSHL/FSHR only use 5 bits. 7034 // Mask the shift amount to 5 bits to prevent accidentally setting bit 5. 7035 NewShAmt = DAG.getNode(ISD::AND, DL, MVT::i64, NewShAmt, 7036 DAG.getConstant(0x1f, DL, MVT::i64)); 7037 // fshl and fshr concatenate their operands in the same order. fsrw and fslw 7038 // instruction use different orders. fshl will return its first operand for 7039 // shift of zero, fshr will return its second operand. fsl and fsr both 7040 // return rs1 so the ISD nodes need to have different operand orders. 7041 // Shift amount is in rs2. 7042 unsigned Opc = RISCVISD::FSLW; 7043 if (N->getOpcode() == ISD::FSHR) { 7044 std::swap(NewOp0, NewOp1); 7045 Opc = RISCVISD::FSRW; 7046 } 7047 SDValue NewOp = DAG.getNode(Opc, DL, MVT::i64, NewOp0, NewOp1, NewShAmt); 7048 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewOp)); 7049 break; 7050 } 7051 case ISD::EXTRACT_VECTOR_ELT: { 7052 // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element 7053 // type is illegal (currently only vXi64 RV32). 7054 // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are 7055 // transferred to the destination register. We issue two of these from the 7056 // upper- and lower- halves of the SEW-bit vector element, slid down to the 7057 // first element. 7058 SDValue Vec = N->getOperand(0); 7059 SDValue Idx = N->getOperand(1); 7060 7061 // The vector type hasn't been legalized yet so we can't issue target 7062 // specific nodes if it needs legalization. 7063 // FIXME: We would manually legalize if it's important. 7064 if (!isTypeLegal(Vec.getValueType())) 7065 return; 7066 7067 MVT VecVT = Vec.getSimpleValueType(); 7068 7069 assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 && 7070 VecVT.getVectorElementType() == MVT::i64 && 7071 "Unexpected EXTRACT_VECTOR_ELT legalization"); 7072 7073 // If this is a fixed vector, we need to convert it to a scalable vector. 7074 MVT ContainerVT = VecVT; 7075 if (VecVT.isFixedLengthVector()) { 7076 ContainerVT = getContainerForFixedLengthVector(VecVT); 7077 Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget); 7078 } 7079 7080 MVT XLenVT = Subtarget.getXLenVT(); 7081 7082 // Use a VL of 1 to avoid processing more elements than we need. 7083 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7084 SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG); 7085 7086 // Unless the index is known to be 0, we must slide the vector down to get 7087 // the desired element into index 0. 7088 if (!isNullConstant(Idx)) { 7089 Vec = DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, ContainerVT, 7090 DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL); 7091 } 7092 7093 // Extract the lower XLEN bits of the correct vector element. 7094 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7095 7096 // To extract the upper XLEN bits of the vector element, shift the first 7097 // element right by 32 bits and re-extract the lower XLEN bits. 7098 SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT, 7099 DAG.getUNDEF(ContainerVT), 7100 DAG.getConstant(32, DL, XLenVT), VL); 7101 SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, 7102 ThirtyTwoV, Mask, VL); 7103 7104 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7105 7106 Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7107 break; 7108 } 7109 case ISD::INTRINSIC_WO_CHAIN: { 7110 unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue(); 7111 switch (IntNo) { 7112 default: 7113 llvm_unreachable( 7114 "Don't know how to custom type legalize this intrinsic!"); 7115 case Intrinsic::riscv_grev: 7116 case Intrinsic::riscv_gorc: { 7117 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7118 "Unexpected custom legalisation"); 7119 SDValue NewOp1 = 7120 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7121 SDValue NewOp2 = 7122 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7123 unsigned Opc = 7124 IntNo == Intrinsic::riscv_grev ? RISCVISD::GREVW : RISCVISD::GORCW; 7125 // If the control is a constant, promote the node by clearing any extra 7126 // bits bits in the control. isel will form greviw/gorciw if the result is 7127 // sign extended. 7128 if (isa<ConstantSDNode>(NewOp2)) { 7129 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7130 DAG.getConstant(0x1f, DL, MVT::i64)); 7131 Opc = IntNo == Intrinsic::riscv_grev ? RISCVISD::GREV : RISCVISD::GORC; 7132 } 7133 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7134 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7135 break; 7136 } 7137 case Intrinsic::riscv_bcompress: 7138 case Intrinsic::riscv_bdecompress: 7139 case Intrinsic::riscv_bfp: 7140 case Intrinsic::riscv_fsl: 7141 case Intrinsic::riscv_fsr: { 7142 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7143 "Unexpected custom legalisation"); 7144 Results.push_back(customLegalizeToWOpByIntr(N, DAG, IntNo)); 7145 break; 7146 } 7147 case Intrinsic::riscv_orc_b: { 7148 // Lower to the GORCI encoding for orc.b with the operand extended. 7149 SDValue NewOp = 7150 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7151 SDValue Res = DAG.getNode(RISCVISD::GORC, DL, MVT::i64, NewOp, 7152 DAG.getConstant(7, DL, MVT::i64)); 7153 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7154 return; 7155 } 7156 case Intrinsic::riscv_shfl: 7157 case Intrinsic::riscv_unshfl: { 7158 assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() && 7159 "Unexpected custom legalisation"); 7160 SDValue NewOp1 = 7161 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1)); 7162 SDValue NewOp2 = 7163 DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(2)); 7164 unsigned Opc = 7165 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFLW : RISCVISD::UNSHFLW; 7166 // There is no (UN)SHFLIW. If the control word is a constant, we can use 7167 // (UN)SHFLI with bit 4 of the control word cleared. The upper 32 bit half 7168 // will be shuffled the same way as the lower 32 bit half, but the two 7169 // halves won't cross. 7170 if (isa<ConstantSDNode>(NewOp2)) { 7171 NewOp2 = DAG.getNode(ISD::AND, DL, MVT::i64, NewOp2, 7172 DAG.getConstant(0xf, DL, MVT::i64)); 7173 Opc = 7174 IntNo == Intrinsic::riscv_shfl ? RISCVISD::SHFL : RISCVISD::UNSHFL; 7175 } 7176 SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp1, NewOp2); 7177 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res)); 7178 break; 7179 } 7180 case Intrinsic::riscv_vmv_x_s: { 7181 EVT VT = N->getValueType(0); 7182 MVT XLenVT = Subtarget.getXLenVT(); 7183 if (VT.bitsLT(XLenVT)) { 7184 // Simple case just extract using vmv.x.s and truncate. 7185 SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL, 7186 Subtarget.getXLenVT(), N->getOperand(1)); 7187 Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract)); 7188 return; 7189 } 7190 7191 assert(VT == MVT::i64 && !Subtarget.is64Bit() && 7192 "Unexpected custom legalization"); 7193 7194 // We need to do the move in two steps. 7195 SDValue Vec = N->getOperand(1); 7196 MVT VecVT = Vec.getSimpleValueType(); 7197 7198 // First extract the lower XLEN bits of the element. 7199 SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec); 7200 7201 // To extract the upper XLEN bits of the vector element, shift the first 7202 // element right by 32 bits and re-extract the lower XLEN bits. 7203 SDValue VL = DAG.getConstant(1, DL, XLenVT); 7204 SDValue Mask = getAllOnesMask(VecVT, VL, DL, DAG); 7205 7206 SDValue ThirtyTwoV = 7207 DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), 7208 DAG.getConstant(32, DL, XLenVT), VL); 7209 SDValue LShr32 = 7210 DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV, Mask, VL); 7211 SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32); 7212 7213 Results.push_back( 7214 DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi)); 7215 break; 7216 } 7217 } 7218 break; 7219 } 7220 case ISD::VECREDUCE_ADD: 7221 case ISD::VECREDUCE_AND: 7222 case ISD::VECREDUCE_OR: 7223 case ISD::VECREDUCE_XOR: 7224 case ISD::VECREDUCE_SMAX: 7225 case ISD::VECREDUCE_UMAX: 7226 case ISD::VECREDUCE_SMIN: 7227 case ISD::VECREDUCE_UMIN: 7228 if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG)) 7229 Results.push_back(V); 7230 break; 7231 case ISD::VP_REDUCE_ADD: 7232 case ISD::VP_REDUCE_AND: 7233 case ISD::VP_REDUCE_OR: 7234 case ISD::VP_REDUCE_XOR: 7235 case ISD::VP_REDUCE_SMAX: 7236 case ISD::VP_REDUCE_UMAX: 7237 case ISD::VP_REDUCE_SMIN: 7238 case ISD::VP_REDUCE_UMIN: 7239 if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG)) 7240 Results.push_back(V); 7241 break; 7242 case ISD::FLT_ROUNDS_: { 7243 SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other); 7244 SDValue Res = DAG.getNode(ISD::FLT_ROUNDS_, DL, VTs, N->getOperand(0)); 7245 Results.push_back(Res.getValue(0)); 7246 Results.push_back(Res.getValue(1)); 7247 break; 7248 } 7249 } 7250 } 7251 7252 // A structure to hold one of the bit-manipulation patterns below. Together, a 7253 // SHL and non-SHL pattern may form a bit-manipulation pair on a single source: 7254 // (or (and (shl x, 1), 0xAAAAAAAA), 7255 // (and (srl x, 1), 0x55555555)) 7256 struct RISCVBitmanipPat { 7257 SDValue Op; 7258 unsigned ShAmt; 7259 bool IsSHL; 7260 7261 bool formsPairWith(const RISCVBitmanipPat &Other) const { 7262 return Op == Other.Op && ShAmt == Other.ShAmt && IsSHL != Other.IsSHL; 7263 } 7264 }; 7265 7266 // Matches patterns of the form 7267 // (and (shl x, C2), (C1 << C2)) 7268 // (and (srl x, C2), C1) 7269 // (shl (and x, C1), C2) 7270 // (srl (and x, (C1 << C2)), C2) 7271 // Where C2 is a power of 2 and C1 has at least that many leading zeroes. 7272 // The expected masks for each shift amount are specified in BitmanipMasks where 7273 // BitmanipMasks[log2(C2)] specifies the expected C1 value. 7274 // The max allowed shift amount is either XLen/2 or XLen/4 determined by whether 7275 // BitmanipMasks contains 6 or 5 entries assuming that the maximum possible 7276 // XLen is 64. 7277 static Optional<RISCVBitmanipPat> 7278 matchRISCVBitmanipPat(SDValue Op, ArrayRef<uint64_t> BitmanipMasks) { 7279 assert((BitmanipMasks.size() == 5 || BitmanipMasks.size() == 6) && 7280 "Unexpected number of masks"); 7281 Optional<uint64_t> Mask; 7282 // Optionally consume a mask around the shift operation. 7283 if (Op.getOpcode() == ISD::AND && isa<ConstantSDNode>(Op.getOperand(1))) { 7284 Mask = Op.getConstantOperandVal(1); 7285 Op = Op.getOperand(0); 7286 } 7287 if (Op.getOpcode() != ISD::SHL && Op.getOpcode() != ISD::SRL) 7288 return None; 7289 bool IsSHL = Op.getOpcode() == ISD::SHL; 7290 7291 if (!isa<ConstantSDNode>(Op.getOperand(1))) 7292 return None; 7293 uint64_t ShAmt = Op.getConstantOperandVal(1); 7294 7295 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7296 if (ShAmt >= Width || !isPowerOf2_64(ShAmt)) 7297 return None; 7298 // If we don't have enough masks for 64 bit, then we must be trying to 7299 // match SHFL so we're only allowed to shift 1/4 of the width. 7300 if (BitmanipMasks.size() == 5 && ShAmt >= (Width / 2)) 7301 return None; 7302 7303 SDValue Src = Op.getOperand(0); 7304 7305 // The expected mask is shifted left when the AND is found around SHL 7306 // patterns. 7307 // ((x >> 1) & 0x55555555) 7308 // ((x << 1) & 0xAAAAAAAA) 7309 bool SHLExpMask = IsSHL; 7310 7311 if (!Mask) { 7312 // Sometimes LLVM keeps the mask as an operand of the shift, typically when 7313 // the mask is all ones: consume that now. 7314 if (Src.getOpcode() == ISD::AND && isa<ConstantSDNode>(Src.getOperand(1))) { 7315 Mask = Src.getConstantOperandVal(1); 7316 Src = Src.getOperand(0); 7317 // The expected mask is now in fact shifted left for SRL, so reverse the 7318 // decision. 7319 // ((x & 0xAAAAAAAA) >> 1) 7320 // ((x & 0x55555555) << 1) 7321 SHLExpMask = !SHLExpMask; 7322 } else { 7323 // Use a default shifted mask of all-ones if there's no AND, truncated 7324 // down to the expected width. This simplifies the logic later on. 7325 Mask = maskTrailingOnes<uint64_t>(Width); 7326 *Mask &= (IsSHL ? *Mask << ShAmt : *Mask >> ShAmt); 7327 } 7328 } 7329 7330 unsigned MaskIdx = Log2_32(ShAmt); 7331 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7332 7333 if (SHLExpMask) 7334 ExpMask <<= ShAmt; 7335 7336 if (Mask != ExpMask) 7337 return None; 7338 7339 return RISCVBitmanipPat{Src, (unsigned)ShAmt, IsSHL}; 7340 } 7341 7342 // Matches any of the following bit-manipulation patterns: 7343 // (and (shl x, 1), (0x55555555 << 1)) 7344 // (and (srl x, 1), 0x55555555) 7345 // (shl (and x, 0x55555555), 1) 7346 // (srl (and x, (0x55555555 << 1)), 1) 7347 // where the shift amount and mask may vary thus: 7348 // [1] = 0x55555555 / 0xAAAAAAAA 7349 // [2] = 0x33333333 / 0xCCCCCCCC 7350 // [4] = 0x0F0F0F0F / 0xF0F0F0F0 7351 // [8] = 0x00FF00FF / 0xFF00FF00 7352 // [16] = 0x0000FFFF / 0xFFFFFFFF 7353 // [32] = 0x00000000FFFFFFFF / 0xFFFFFFFF00000000 (for RV64) 7354 static Optional<RISCVBitmanipPat> matchGREVIPat(SDValue Op) { 7355 // These are the unshifted masks which we use to match bit-manipulation 7356 // patterns. They may be shifted left in certain circumstances. 7357 static const uint64_t BitmanipMasks[] = { 7358 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 7359 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 7360 7361 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7362 } 7363 7364 // Try to fold (<bop> x, (reduction.<bop> vec, start)) 7365 static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG) { 7366 auto BinOpToRVVReduce = [](unsigned Opc) { 7367 switch (Opc) { 7368 default: 7369 llvm_unreachable("Unhandled binary to transfrom reduction"); 7370 case ISD::ADD: 7371 return RISCVISD::VECREDUCE_ADD_VL; 7372 case ISD::UMAX: 7373 return RISCVISD::VECREDUCE_UMAX_VL; 7374 case ISD::SMAX: 7375 return RISCVISD::VECREDUCE_SMAX_VL; 7376 case ISD::UMIN: 7377 return RISCVISD::VECREDUCE_UMIN_VL; 7378 case ISD::SMIN: 7379 return RISCVISD::VECREDUCE_SMIN_VL; 7380 case ISD::AND: 7381 return RISCVISD::VECREDUCE_AND_VL; 7382 case ISD::OR: 7383 return RISCVISD::VECREDUCE_OR_VL; 7384 case ISD::XOR: 7385 return RISCVISD::VECREDUCE_XOR_VL; 7386 case ISD::FADD: 7387 return RISCVISD::VECREDUCE_FADD_VL; 7388 case ISD::FMAXNUM: 7389 return RISCVISD::VECREDUCE_FMAX_VL; 7390 case ISD::FMINNUM: 7391 return RISCVISD::VECREDUCE_FMIN_VL; 7392 } 7393 }; 7394 7395 auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) { 7396 return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT && 7397 isNullConstant(V.getOperand(1)) && 7398 V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc); 7399 }; 7400 7401 unsigned Opc = N->getOpcode(); 7402 unsigned ReduceIdx; 7403 if (IsReduction(N->getOperand(0), Opc)) 7404 ReduceIdx = 0; 7405 else if (IsReduction(N->getOperand(1), Opc)) 7406 ReduceIdx = 1; 7407 else 7408 return SDValue(); 7409 7410 // Skip if FADD disallows reassociation but the combiner needs. 7411 if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation()) 7412 return SDValue(); 7413 7414 SDValue Extract = N->getOperand(ReduceIdx); 7415 SDValue Reduce = Extract.getOperand(0); 7416 if (!Reduce.hasOneUse()) 7417 return SDValue(); 7418 7419 SDValue ScalarV = Reduce.getOperand(2); 7420 7421 // Make sure that ScalarV is a splat with VL=1. 7422 if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL && 7423 ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL && 7424 ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL) 7425 return SDValue(); 7426 7427 if (!isOneConstant(ScalarV.getOperand(2))) 7428 return SDValue(); 7429 7430 // TODO: Deal with value other than neutral element. 7431 auto IsRVVNeutralElement = [Opc, &DAG](SDNode *N, SDValue V) { 7432 if (Opc == ISD::FADD && N->getFlags().hasNoSignedZeros() && 7433 isNullFPConstant(V)) 7434 return true; 7435 return DAG.getNeutralElement(Opc, SDLoc(V), V.getSimpleValueType(), 7436 N->getFlags()) == V; 7437 }; 7438 7439 // Check the scalar of ScalarV is neutral element 7440 if (!IsRVVNeutralElement(N, ScalarV.getOperand(1))) 7441 return SDValue(); 7442 7443 if (!ScalarV.hasOneUse()) 7444 return SDValue(); 7445 7446 EVT SplatVT = ScalarV.getValueType(); 7447 SDValue NewStart = N->getOperand(1 - ReduceIdx); 7448 unsigned SplatOpc = RISCVISD::VFMV_S_F_VL; 7449 if (SplatVT.isInteger()) { 7450 auto *C = dyn_cast<ConstantSDNode>(NewStart.getNode()); 7451 if (!C || C->isZero() || !isInt<5>(C->getSExtValue())) 7452 SplatOpc = RISCVISD::VMV_S_X_VL; 7453 else 7454 SplatOpc = RISCVISD::VMV_V_X_VL; 7455 } 7456 7457 SDValue NewScalarV = 7458 DAG.getNode(SplatOpc, SDLoc(N), SplatVT, ScalarV.getOperand(0), NewStart, 7459 ScalarV.getOperand(2)); 7460 SDValue NewReduce = 7461 DAG.getNode(Reduce.getOpcode(), SDLoc(Reduce), Reduce.getValueType(), 7462 Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV, 7463 Reduce.getOperand(3), Reduce.getOperand(4)); 7464 return DAG.getNode(Extract.getOpcode(), SDLoc(Extract), 7465 Extract.getValueType(), NewReduce, Extract.getOperand(1)); 7466 } 7467 7468 // Match the following pattern as a GREVI(W) operation 7469 // (or (BITMANIP_SHL x), (BITMANIP_SRL x)) 7470 static SDValue combineORToGREV(SDValue Op, SelectionDAG &DAG, 7471 const RISCVSubtarget &Subtarget) { 7472 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7473 EVT VT = Op.getValueType(); 7474 7475 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7476 auto LHS = matchGREVIPat(Op.getOperand(0)); 7477 auto RHS = matchGREVIPat(Op.getOperand(1)); 7478 if (LHS && RHS && LHS->formsPairWith(*RHS)) { 7479 SDLoc DL(Op); 7480 return DAG.getNode(RISCVISD::GREV, DL, VT, LHS->Op, 7481 DAG.getConstant(LHS->ShAmt, DL, VT)); 7482 } 7483 } 7484 return SDValue(); 7485 } 7486 7487 // Matches any the following pattern as a GORCI(W) operation 7488 // 1. (or (GREVI x, shamt), x) if shamt is a power of 2 7489 // 2. (or x, (GREVI x, shamt)) if shamt is a power of 2 7490 // 3. (or (or (BITMANIP_SHL x), x), (BITMANIP_SRL x)) 7491 // Note that with the variant of 3., 7492 // (or (or (BITMANIP_SHL x), (BITMANIP_SRL x)), x) 7493 // the inner pattern will first be matched as GREVI and then the outer 7494 // pattern will be matched to GORC via the first rule above. 7495 // 4. (or (rotl/rotr x, bitwidth/2), x) 7496 static SDValue combineORToGORC(SDValue Op, SelectionDAG &DAG, 7497 const RISCVSubtarget &Subtarget) { 7498 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7499 EVT VT = Op.getValueType(); 7500 7501 if (VT == Subtarget.getXLenVT() || (Subtarget.is64Bit() && VT == MVT::i32)) { 7502 SDLoc DL(Op); 7503 SDValue Op0 = Op.getOperand(0); 7504 SDValue Op1 = Op.getOperand(1); 7505 7506 auto MatchOROfReverse = [&](SDValue Reverse, SDValue X) { 7507 if (Reverse.getOpcode() == RISCVISD::GREV && Reverse.getOperand(0) == X && 7508 isa<ConstantSDNode>(Reverse.getOperand(1)) && 7509 isPowerOf2_32(Reverse.getConstantOperandVal(1))) 7510 return DAG.getNode(RISCVISD::GORC, DL, VT, X, Reverse.getOperand(1)); 7511 // We can also form GORCI from ROTL/ROTR by half the bitwidth. 7512 if ((Reverse.getOpcode() == ISD::ROTL || 7513 Reverse.getOpcode() == ISD::ROTR) && 7514 Reverse.getOperand(0) == X && 7515 isa<ConstantSDNode>(Reverse.getOperand(1))) { 7516 uint64_t RotAmt = Reverse.getConstantOperandVal(1); 7517 if (RotAmt == (VT.getSizeInBits() / 2)) 7518 return DAG.getNode(RISCVISD::GORC, DL, VT, X, 7519 DAG.getConstant(RotAmt, DL, VT)); 7520 } 7521 return SDValue(); 7522 }; 7523 7524 // Check for either commutable permutation of (or (GREVI x, shamt), x) 7525 if (SDValue V = MatchOROfReverse(Op0, Op1)) 7526 return V; 7527 if (SDValue V = MatchOROfReverse(Op1, Op0)) 7528 return V; 7529 7530 // OR is commutable so canonicalize its OR operand to the left 7531 if (Op0.getOpcode() != ISD::OR && Op1.getOpcode() == ISD::OR) 7532 std::swap(Op0, Op1); 7533 if (Op0.getOpcode() != ISD::OR) 7534 return SDValue(); 7535 SDValue OrOp0 = Op0.getOperand(0); 7536 SDValue OrOp1 = Op0.getOperand(1); 7537 auto LHS = matchGREVIPat(OrOp0); 7538 // OR is commutable so swap the operands and try again: x might have been 7539 // on the left 7540 if (!LHS) { 7541 std::swap(OrOp0, OrOp1); 7542 LHS = matchGREVIPat(OrOp0); 7543 } 7544 auto RHS = matchGREVIPat(Op1); 7545 if (LHS && RHS && LHS->formsPairWith(*RHS) && LHS->Op == OrOp1) { 7546 return DAG.getNode(RISCVISD::GORC, DL, VT, LHS->Op, 7547 DAG.getConstant(LHS->ShAmt, DL, VT)); 7548 } 7549 } 7550 return SDValue(); 7551 } 7552 7553 // Matches any of the following bit-manipulation patterns: 7554 // (and (shl x, 1), (0x22222222 << 1)) 7555 // (and (srl x, 1), 0x22222222) 7556 // (shl (and x, 0x22222222), 1) 7557 // (srl (and x, (0x22222222 << 1)), 1) 7558 // where the shift amount and mask may vary thus: 7559 // [1] = 0x22222222 / 0x44444444 7560 // [2] = 0x0C0C0C0C / 0x3C3C3C3C 7561 // [4] = 0x00F000F0 / 0x0F000F00 7562 // [8] = 0x0000FF00 / 0x00FF0000 7563 // [16] = 0x00000000FFFF0000 / 0x0000FFFF00000000 (for RV64) 7564 static Optional<RISCVBitmanipPat> matchSHFLPat(SDValue Op) { 7565 // These are the unshifted masks which we use to match bit-manipulation 7566 // patterns. They may be shifted left in certain circumstances. 7567 static const uint64_t BitmanipMasks[] = { 7568 0x2222222222222222ULL, 0x0C0C0C0C0C0C0C0CULL, 0x00F000F000F000F0ULL, 7569 0x0000FF000000FF00ULL, 0x00000000FFFF0000ULL}; 7570 7571 return matchRISCVBitmanipPat(Op, BitmanipMasks); 7572 } 7573 7574 // Match (or (or (SHFL_SHL x), (SHFL_SHR x)), (SHFL_AND x) 7575 static SDValue combineORToSHFL(SDValue Op, SelectionDAG &DAG, 7576 const RISCVSubtarget &Subtarget) { 7577 assert(Subtarget.hasStdExtZbp() && "Expected Zbp extenson"); 7578 EVT VT = Op.getValueType(); 7579 7580 if (VT != MVT::i32 && VT != Subtarget.getXLenVT()) 7581 return SDValue(); 7582 7583 SDValue Op0 = Op.getOperand(0); 7584 SDValue Op1 = Op.getOperand(1); 7585 7586 // Or is commutable so canonicalize the second OR to the LHS. 7587 if (Op0.getOpcode() != ISD::OR) 7588 std::swap(Op0, Op1); 7589 if (Op0.getOpcode() != ISD::OR) 7590 return SDValue(); 7591 7592 // We found an inner OR, so our operands are the operands of the inner OR 7593 // and the other operand of the outer OR. 7594 SDValue A = Op0.getOperand(0); 7595 SDValue B = Op0.getOperand(1); 7596 SDValue C = Op1; 7597 7598 auto Match1 = matchSHFLPat(A); 7599 auto Match2 = matchSHFLPat(B); 7600 7601 // If neither matched, we failed. 7602 if (!Match1 && !Match2) 7603 return SDValue(); 7604 7605 // We had at least one match. if one failed, try the remaining C operand. 7606 if (!Match1) { 7607 std::swap(A, C); 7608 Match1 = matchSHFLPat(A); 7609 if (!Match1) 7610 return SDValue(); 7611 } else if (!Match2) { 7612 std::swap(B, C); 7613 Match2 = matchSHFLPat(B); 7614 if (!Match2) 7615 return SDValue(); 7616 } 7617 assert(Match1 && Match2); 7618 7619 // Make sure our matches pair up. 7620 if (!Match1->formsPairWith(*Match2)) 7621 return SDValue(); 7622 7623 // All the remains is to make sure C is an AND with the same input, that masks 7624 // out the bits that are being shuffled. 7625 if (C.getOpcode() != ISD::AND || !isa<ConstantSDNode>(C.getOperand(1)) || 7626 C.getOperand(0) != Match1->Op) 7627 return SDValue(); 7628 7629 uint64_t Mask = C.getConstantOperandVal(1); 7630 7631 static const uint64_t BitmanipMasks[] = { 7632 0x9999999999999999ULL, 0xC3C3C3C3C3C3C3C3ULL, 0xF00FF00FF00FF00FULL, 7633 0xFF0000FFFF0000FFULL, 0xFFFF00000000FFFFULL, 7634 }; 7635 7636 unsigned Width = Op.getValueType() == MVT::i64 ? 64 : 32; 7637 unsigned MaskIdx = Log2_32(Match1->ShAmt); 7638 uint64_t ExpMask = BitmanipMasks[MaskIdx] & maskTrailingOnes<uint64_t>(Width); 7639 7640 if (Mask != ExpMask) 7641 return SDValue(); 7642 7643 SDLoc DL(Op); 7644 return DAG.getNode(RISCVISD::SHFL, DL, VT, Match1->Op, 7645 DAG.getConstant(Match1->ShAmt, DL, VT)); 7646 } 7647 7648 // Optimize (add (shl x, c0), (shl y, c1)) -> 7649 // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3]. 7650 static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG, 7651 const RISCVSubtarget &Subtarget) { 7652 // Perform this optimization only in the zba extension. 7653 if (!Subtarget.hasStdExtZba()) 7654 return SDValue(); 7655 7656 // Skip for vector types and larger types. 7657 EVT VT = N->getValueType(0); 7658 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7659 return SDValue(); 7660 7661 // The two operand nodes must be SHL and have no other use. 7662 SDValue N0 = N->getOperand(0); 7663 SDValue N1 = N->getOperand(1); 7664 if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL || 7665 !N0->hasOneUse() || !N1->hasOneUse()) 7666 return SDValue(); 7667 7668 // Check c0 and c1. 7669 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7670 auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1)); 7671 if (!N0C || !N1C) 7672 return SDValue(); 7673 int64_t C0 = N0C->getSExtValue(); 7674 int64_t C1 = N1C->getSExtValue(); 7675 if (C0 <= 0 || C1 <= 0) 7676 return SDValue(); 7677 7678 // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable. 7679 int64_t Bits = std::min(C0, C1); 7680 int64_t Diff = std::abs(C0 - C1); 7681 if (Diff != 1 && Diff != 2 && Diff != 3) 7682 return SDValue(); 7683 7684 // Build nodes. 7685 SDLoc DL(N); 7686 SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0); 7687 SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0); 7688 SDValue NA0 = 7689 DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT)); 7690 SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS); 7691 return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT)); 7692 } 7693 7694 // Combine 7695 // ROTR ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7696 // ROTL ((GREVI x, 24), 16) -> (GREVI x, 8) for RV32 7697 // ROTR ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7698 // ROTL ((GREVI x, 56), 32) -> (GREVI x, 24) for RV64 7699 // RORW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7700 // ROLW ((GREVI x, 24), 16) -> (GREVIW x, 8) for RV64 7701 // The grev patterns represents BSWAP. 7702 // FIXME: This can be generalized to any GREV. We just need to toggle the MSB 7703 // off the grev. 7704 static SDValue combineROTR_ROTL_RORW_ROLW(SDNode *N, SelectionDAG &DAG, 7705 const RISCVSubtarget &Subtarget) { 7706 bool IsWInstruction = 7707 N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW; 7708 assert((N->getOpcode() == ISD::ROTR || N->getOpcode() == ISD::ROTL || 7709 IsWInstruction) && 7710 "Unexpected opcode!"); 7711 SDValue Src = N->getOperand(0); 7712 EVT VT = N->getValueType(0); 7713 SDLoc DL(N); 7714 7715 if (!Subtarget.hasStdExtZbp() || Src.getOpcode() != RISCVISD::GREV) 7716 return SDValue(); 7717 7718 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7719 !isa<ConstantSDNode>(Src.getOperand(1))) 7720 return SDValue(); 7721 7722 unsigned BitWidth = IsWInstruction ? 32 : VT.getSizeInBits(); 7723 assert(isPowerOf2_32(BitWidth) && "Expected a power of 2"); 7724 7725 // Needs to be a rotate by half the bitwidth for ROTR/ROTL or by 16 for 7726 // RORW/ROLW. And the grev should be the encoding for bswap for this width. 7727 unsigned ShAmt1 = N->getConstantOperandVal(1); 7728 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7729 if (BitWidth < 32 || ShAmt1 != (BitWidth / 2) || ShAmt2 != (BitWidth - 8)) 7730 return SDValue(); 7731 7732 Src = Src.getOperand(0); 7733 7734 // Toggle bit the MSB of the shift. 7735 unsigned CombinedShAmt = ShAmt1 ^ ShAmt2; 7736 if (CombinedShAmt == 0) 7737 return Src; 7738 7739 SDValue Res = DAG.getNode( 7740 RISCVISD::GREV, DL, VT, Src, 7741 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7742 if (!IsWInstruction) 7743 return Res; 7744 7745 // Sign extend the result to match the behavior of the rotate. This will be 7746 // selected to GREVIW in isel. 7747 return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Res, 7748 DAG.getValueType(MVT::i32)); 7749 } 7750 7751 // Combine (GREVI (GREVI x, C2), C1) -> (GREVI x, C1^C2) when C1^C2 is 7752 // non-zero, and to x when it is. Any repeated GREVI stage undoes itself. 7753 // Combine (GORCI (GORCI x, C2), C1) -> (GORCI x, C1|C2). Repeated stage does 7754 // not undo itself, but they are redundant. 7755 static SDValue combineGREVI_GORCI(SDNode *N, SelectionDAG &DAG) { 7756 bool IsGORC = N->getOpcode() == RISCVISD::GORC; 7757 assert((IsGORC || N->getOpcode() == RISCVISD::GREV) && "Unexpected opcode"); 7758 SDValue Src = N->getOperand(0); 7759 7760 if (Src.getOpcode() != N->getOpcode()) 7761 return SDValue(); 7762 7763 if (!isa<ConstantSDNode>(N->getOperand(1)) || 7764 !isa<ConstantSDNode>(Src.getOperand(1))) 7765 return SDValue(); 7766 7767 unsigned ShAmt1 = N->getConstantOperandVal(1); 7768 unsigned ShAmt2 = Src.getConstantOperandVal(1); 7769 Src = Src.getOperand(0); 7770 7771 unsigned CombinedShAmt; 7772 if (IsGORC) 7773 CombinedShAmt = ShAmt1 | ShAmt2; 7774 else 7775 CombinedShAmt = ShAmt1 ^ ShAmt2; 7776 7777 if (CombinedShAmt == 0) 7778 return Src; 7779 7780 SDLoc DL(N); 7781 return DAG.getNode( 7782 N->getOpcode(), DL, N->getValueType(0), Src, 7783 DAG.getConstant(CombinedShAmt, DL, N->getOperand(1).getValueType())); 7784 } 7785 7786 // Combine a constant select operand into its use: 7787 // 7788 // (and (select cond, -1, c), x) 7789 // -> (select cond, x, (and x, c)) [AllOnes=1] 7790 // (or (select cond, 0, c), x) 7791 // -> (select cond, x, (or x, c)) [AllOnes=0] 7792 // (xor (select cond, 0, c), x) 7793 // -> (select cond, x, (xor x, c)) [AllOnes=0] 7794 // (add (select cond, 0, c), x) 7795 // -> (select cond, x, (add x, c)) [AllOnes=0] 7796 // (sub x, (select cond, 0, c)) 7797 // -> (select cond, x, (sub x, c)) [AllOnes=0] 7798 static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp, 7799 SelectionDAG &DAG, bool AllOnes) { 7800 EVT VT = N->getValueType(0); 7801 7802 // Skip vectors. 7803 if (VT.isVector()) 7804 return SDValue(); 7805 7806 if ((Slct.getOpcode() != ISD::SELECT && 7807 Slct.getOpcode() != RISCVISD::SELECT_CC) || 7808 !Slct.hasOneUse()) 7809 return SDValue(); 7810 7811 auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) { 7812 return AllOnes ? isAllOnesConstant(N) : isNullConstant(N); 7813 }; 7814 7815 bool SwapSelectOps; 7816 unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0; 7817 SDValue TrueVal = Slct.getOperand(1 + OpOffset); 7818 SDValue FalseVal = Slct.getOperand(2 + OpOffset); 7819 SDValue NonConstantVal; 7820 if (isZeroOrAllOnes(TrueVal, AllOnes)) { 7821 SwapSelectOps = false; 7822 NonConstantVal = FalseVal; 7823 } else if (isZeroOrAllOnes(FalseVal, AllOnes)) { 7824 SwapSelectOps = true; 7825 NonConstantVal = TrueVal; 7826 } else 7827 return SDValue(); 7828 7829 // Slct is now know to be the desired identity constant when CC is true. 7830 TrueVal = OtherOp; 7831 FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal); 7832 // Unless SwapSelectOps says the condition should be false. 7833 if (SwapSelectOps) 7834 std::swap(TrueVal, FalseVal); 7835 7836 if (Slct.getOpcode() == RISCVISD::SELECT_CC) 7837 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT, 7838 {Slct.getOperand(0), Slct.getOperand(1), 7839 Slct.getOperand(2), TrueVal, FalseVal}); 7840 7841 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, 7842 {Slct.getOperand(0), TrueVal, FalseVal}); 7843 } 7844 7845 // Attempt combineSelectAndUse on each operand of a commutative operator N. 7846 static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG, 7847 bool AllOnes) { 7848 SDValue N0 = N->getOperand(0); 7849 SDValue N1 = N->getOperand(1); 7850 if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes)) 7851 return Result; 7852 if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes)) 7853 return Result; 7854 return SDValue(); 7855 } 7856 7857 // Transform (add (mul x, c0), c1) -> 7858 // (add (mul (add x, c1/c0), c0), c1%c0). 7859 // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case 7860 // that should be excluded is when c0*(c1/c0) is simm12, which will lead 7861 // to an infinite loop in DAGCombine if transformed. 7862 // Or transform (add (mul x, c0), c1) -> 7863 // (add (mul (add x, c1/c0+1), c0), c1%c0-c0), 7864 // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner 7865 // case that should be excluded is when c0*(c1/c0+1) is simm12, which will 7866 // lead to an infinite loop in DAGCombine if transformed. 7867 // Or transform (add (mul x, c0), c1) -> 7868 // (add (mul (add x, c1/c0-1), c0), c1%c0+c0), 7869 // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner 7870 // case that should be excluded is when c0*(c1/c0-1) is simm12, which will 7871 // lead to an infinite loop in DAGCombine if transformed. 7872 // Or transform (add (mul x, c0), c1) -> 7873 // (mul (add x, c1/c0), c0). 7874 // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not. 7875 static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG, 7876 const RISCVSubtarget &Subtarget) { 7877 // Skip for vector types and larger types. 7878 EVT VT = N->getValueType(0); 7879 if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen()) 7880 return SDValue(); 7881 // The first operand node must be a MUL and has no other use. 7882 SDValue N0 = N->getOperand(0); 7883 if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL) 7884 return SDValue(); 7885 // Check if c0 and c1 match above conditions. 7886 auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 7887 auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 7888 if (!N0C || !N1C) 7889 return SDValue(); 7890 // If N0C has multiple uses it's possible one of the cases in 7891 // DAGCombiner::isMulAddWithConstProfitable will be true, which would result 7892 // in an infinite loop. 7893 if (!N0C->hasOneUse()) 7894 return SDValue(); 7895 int64_t C0 = N0C->getSExtValue(); 7896 int64_t C1 = N1C->getSExtValue(); 7897 int64_t CA, CB; 7898 if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1)) 7899 return SDValue(); 7900 // Search for proper CA (non-zero) and CB that both are simm12. 7901 if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) && 7902 !isInt<12>(C0 * (C1 / C0))) { 7903 CA = C1 / C0; 7904 CB = C1 % C0; 7905 } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) && 7906 isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) { 7907 CA = C1 / C0 + 1; 7908 CB = C1 % C0 - C0; 7909 } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) && 7910 isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) { 7911 CA = C1 / C0 - 1; 7912 CB = C1 % C0 + C0; 7913 } else 7914 return SDValue(); 7915 // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0). 7916 SDLoc DL(N); 7917 SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0), 7918 DAG.getConstant(CA, DL, VT)); 7919 SDValue New1 = 7920 DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT)); 7921 return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT)); 7922 } 7923 7924 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG, 7925 const RISCVSubtarget &Subtarget) { 7926 if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget)) 7927 return V; 7928 if (SDValue V = transformAddShlImm(N, DAG, Subtarget)) 7929 return V; 7930 if (SDValue V = combineBinOpToReduce(N, DAG)) 7931 return V; 7932 // fold (add (select lhs, rhs, cc, 0, y), x) -> 7933 // (select lhs, rhs, cc, x, (add x, y)) 7934 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7935 } 7936 7937 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG) { 7938 // fold (sub x, (select lhs, rhs, cc, 0, y)) -> 7939 // (select lhs, rhs, cc, x, (sub x, y)) 7940 SDValue N0 = N->getOperand(0); 7941 SDValue N1 = N->getOperand(1); 7942 return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false); 7943 } 7944 7945 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG, 7946 const RISCVSubtarget &Subtarget) { 7947 SDValue N0 = N->getOperand(0); 7948 // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero 7949 // extending X. This is safe since we only need the LSB after the shift and 7950 // shift amounts larger than 31 would produce poison. If we wait until 7951 // type legalization, we'll create RISCVISD::SRLW and we can't recover it 7952 // to use a BEXT instruction. 7953 if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() && 7954 N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) && 7955 N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) && 7956 N0.hasOneUse()) { 7957 SDLoc DL(N); 7958 SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0)); 7959 SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1)); 7960 SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1); 7961 SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl, 7962 DAG.getConstant(1, DL, MVT::i64)); 7963 return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And); 7964 } 7965 7966 if (SDValue V = combineBinOpToReduce(N, DAG)) 7967 return V; 7968 7969 // fold (and (select lhs, rhs, cc, -1, y), x) -> 7970 // (select lhs, rhs, cc, x, (and x, y)) 7971 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true); 7972 } 7973 7974 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG, 7975 const RISCVSubtarget &Subtarget) { 7976 if (Subtarget.hasStdExtZbp()) { 7977 if (auto GREV = combineORToGREV(SDValue(N, 0), DAG, Subtarget)) 7978 return GREV; 7979 if (auto GORC = combineORToGORC(SDValue(N, 0), DAG, Subtarget)) 7980 return GORC; 7981 if (auto SHFL = combineORToSHFL(SDValue(N, 0), DAG, Subtarget)) 7982 return SHFL; 7983 } 7984 7985 if (SDValue V = combineBinOpToReduce(N, DAG)) 7986 return V; 7987 // fold (or (select cond, 0, y), x) -> 7988 // (select cond, x, (or x, y)) 7989 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 7990 } 7991 7992 static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG) { 7993 SDValue N0 = N->getOperand(0); 7994 SDValue N1 = N->getOperand(1); 7995 7996 // fold (xor (sllw 1, x), -1) -> (rolw ~1, x) 7997 // NOTE: Assumes ROL being legal means ROLW is legal. 7998 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 7999 if (N0.getOpcode() == RISCVISD::SLLW && 8000 isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) && 8001 TLI.isOperationLegal(ISD::ROTL, MVT::i64)) { 8002 SDLoc DL(N); 8003 return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64, 8004 DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1)); 8005 } 8006 8007 if (SDValue V = combineBinOpToReduce(N, DAG)) 8008 return V; 8009 // fold (xor (select cond, 0, y), x) -> 8010 // (select cond, x, (xor x, y)) 8011 return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false); 8012 } 8013 8014 static SDValue 8015 performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG, 8016 const RISCVSubtarget &Subtarget) { 8017 SDValue Src = N->getOperand(0); 8018 EVT VT = N->getValueType(0); 8019 8020 // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X) 8021 if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8022 cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16)) 8023 return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT, 8024 Src.getOperand(0)); 8025 8026 // Fold (i64 (sext_inreg (abs X), i32)) -> 8027 // (i64 (smax (sext_inreg (neg X), i32), X)) if X has more than 32 sign bits. 8028 // The (sext_inreg (neg X), i32) will be selected to negw by isel. This 8029 // pattern occurs after type legalization of (i32 (abs X)) on RV64 if the user 8030 // of the (i32 (abs X)) is a sext or setcc or something else that causes type 8031 // legalization to add a sext_inreg after the abs. The (i32 (abs X)) will have 8032 // been type legalized to (i64 (abs (sext_inreg X, i32))), but the sext_inreg 8033 // may get combined into an earlier operation so we need to use 8034 // ComputeNumSignBits. 8035 // NOTE: (i64 (sext_inreg (abs X), i32)) can also be created for 8036 // (i64 (ashr (shl (abs X), 32), 32)) without any type legalization so 8037 // we can't assume that X has 33 sign bits. We must check. 8038 if (Subtarget.hasStdExtZbb() && Subtarget.is64Bit() && 8039 Src.getOpcode() == ISD::ABS && Src.hasOneUse() && VT == MVT::i64 && 8040 cast<VTSDNode>(N->getOperand(1))->getVT() == MVT::i32 && 8041 DAG.ComputeNumSignBits(Src.getOperand(0)) > 32) { 8042 SDLoc DL(N); 8043 SDValue Freeze = DAG.getFreeze(Src.getOperand(0)); 8044 SDValue Neg = 8045 DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, MVT::i64), Freeze); 8046 Neg = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Neg, 8047 DAG.getValueType(MVT::i32)); 8048 return DAG.getNode(ISD::SMAX, DL, MVT::i64, Freeze, Neg); 8049 } 8050 8051 return SDValue(); 8052 } 8053 8054 // Try to form vwadd(u).wv/wx or vwsub(u).wv/wx. It might later be optimized to 8055 // vwadd(u).vv/vx or vwsub(u).vv/vx. 8056 static SDValue combineADDSUB_VLToVWADDSUB_VL(SDNode *N, SelectionDAG &DAG, 8057 bool Commute = false) { 8058 assert((N->getOpcode() == RISCVISD::ADD_VL || 8059 N->getOpcode() == RISCVISD::SUB_VL) && 8060 "Unexpected opcode"); 8061 bool IsAdd = N->getOpcode() == RISCVISD::ADD_VL; 8062 SDValue Op0 = N->getOperand(0); 8063 SDValue Op1 = N->getOperand(1); 8064 if (Commute) 8065 std::swap(Op0, Op1); 8066 8067 MVT VT = N->getSimpleValueType(0); 8068 8069 // Determine the narrow size for a widening add/sub. 8070 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8071 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8072 VT.getVectorElementCount()); 8073 8074 SDValue Mask = N->getOperand(2); 8075 SDValue VL = N->getOperand(3); 8076 8077 SDLoc DL(N); 8078 8079 // If the RHS is a sext or zext, we can form a widening op. 8080 if ((Op1.getOpcode() == RISCVISD::VZEXT_VL || 8081 Op1.getOpcode() == RISCVISD::VSEXT_VL) && 8082 Op1.hasOneUse() && Op1.getOperand(1) == Mask && Op1.getOperand(2) == VL) { 8083 unsigned ExtOpc = Op1.getOpcode(); 8084 Op1 = Op1.getOperand(0); 8085 // Re-introduce narrower extends if needed. 8086 if (Op1.getValueType() != NarrowVT) 8087 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8088 8089 unsigned WOpc; 8090 if (ExtOpc == RISCVISD::VSEXT_VL) 8091 WOpc = IsAdd ? RISCVISD::VWADD_W_VL : RISCVISD::VWSUB_W_VL; 8092 else 8093 WOpc = IsAdd ? RISCVISD::VWADDU_W_VL : RISCVISD::VWSUBU_W_VL; 8094 8095 return DAG.getNode(WOpc, DL, VT, Op0, Op1, Mask, VL); 8096 } 8097 8098 // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar 8099 // sext/zext? 8100 8101 return SDValue(); 8102 } 8103 8104 // Try to convert vwadd(u).wv/wx or vwsub(u).wv/wx to vwadd(u).vv/vx or 8105 // vwsub(u).vv/vx. 8106 static SDValue combineVWADD_W_VL_VWSUB_W_VL(SDNode *N, SelectionDAG &DAG) { 8107 SDValue Op0 = N->getOperand(0); 8108 SDValue Op1 = N->getOperand(1); 8109 SDValue Mask = N->getOperand(2); 8110 SDValue VL = N->getOperand(3); 8111 8112 MVT VT = N->getSimpleValueType(0); 8113 MVT NarrowVT = Op1.getSimpleValueType(); 8114 unsigned NarrowSize = NarrowVT.getScalarSizeInBits(); 8115 8116 unsigned VOpc; 8117 switch (N->getOpcode()) { 8118 default: llvm_unreachable("Unexpected opcode"); 8119 case RISCVISD::VWADD_W_VL: VOpc = RISCVISD::VWADD_VL; break; 8120 case RISCVISD::VWSUB_W_VL: VOpc = RISCVISD::VWSUB_VL; break; 8121 case RISCVISD::VWADDU_W_VL: VOpc = RISCVISD::VWADDU_VL; break; 8122 case RISCVISD::VWSUBU_W_VL: VOpc = RISCVISD::VWSUBU_VL; break; 8123 } 8124 8125 bool IsSigned = N->getOpcode() == RISCVISD::VWADD_W_VL || 8126 N->getOpcode() == RISCVISD::VWSUB_W_VL; 8127 8128 SDLoc DL(N); 8129 8130 // If the LHS is a sext or zext, we can narrow this op to the same size as 8131 // the RHS. 8132 if (((Op0.getOpcode() == RISCVISD::VZEXT_VL && !IsSigned) || 8133 (Op0.getOpcode() == RISCVISD::VSEXT_VL && IsSigned)) && 8134 Op0.hasOneUse() && Op0.getOperand(1) == Mask && Op0.getOperand(2) == VL) { 8135 unsigned ExtOpc = Op0.getOpcode(); 8136 Op0 = Op0.getOperand(0); 8137 // Re-introduce narrower extends if needed. 8138 if (Op0.getValueType() != NarrowVT) 8139 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8140 return DAG.getNode(VOpc, DL, VT, Op0, Op1, Mask, VL); 8141 } 8142 8143 bool IsAdd = N->getOpcode() == RISCVISD::VWADD_W_VL || 8144 N->getOpcode() == RISCVISD::VWADDU_W_VL; 8145 8146 // Look for splats on the left hand side of a vwadd(u).wv. We might be able 8147 // to commute and use a vwadd(u).vx instead. 8148 if (IsAdd && Op0.getOpcode() == RISCVISD::VMV_V_X_VL && 8149 Op0.getOperand(0).isUndef() && Op0.getOperand(2) == VL) { 8150 Op0 = Op0.getOperand(1); 8151 8152 // See if have enough sign bits or zero bits in the scalar to use a 8153 // widening add/sub by splatting to smaller element size. 8154 unsigned EltBits = VT.getScalarSizeInBits(); 8155 unsigned ScalarBits = Op0.getValueSizeInBits(); 8156 // Make sure we're getting all element bits from the scalar register. 8157 // FIXME: Support implicit sign extension of vmv.v.x? 8158 if (ScalarBits < EltBits) 8159 return SDValue(); 8160 8161 if (IsSigned) { 8162 if (DAG.ComputeNumSignBits(Op0) <= (ScalarBits - NarrowSize)) 8163 return SDValue(); 8164 } else { 8165 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8166 if (!DAG.MaskedValueIsZero(Op0, Mask)) 8167 return SDValue(); 8168 } 8169 8170 Op0 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8171 DAG.getUNDEF(NarrowVT), Op0, VL); 8172 return DAG.getNode(VOpc, DL, VT, Op1, Op0, Mask, VL); 8173 } 8174 8175 return SDValue(); 8176 } 8177 8178 // Try to form VWMUL, VWMULU or VWMULSU. 8179 // TODO: Support VWMULSU.vx with a sign extend Op and a splat of scalar Op. 8180 static SDValue combineMUL_VLToVWMUL_VL(SDNode *N, SelectionDAG &DAG, 8181 bool Commute) { 8182 assert(N->getOpcode() == RISCVISD::MUL_VL && "Unexpected opcode"); 8183 SDValue Op0 = N->getOperand(0); 8184 SDValue Op1 = N->getOperand(1); 8185 if (Commute) 8186 std::swap(Op0, Op1); 8187 8188 bool IsSignExt = Op0.getOpcode() == RISCVISD::VSEXT_VL; 8189 bool IsZeroExt = Op0.getOpcode() == RISCVISD::VZEXT_VL; 8190 bool IsVWMULSU = IsSignExt && Op1.getOpcode() == RISCVISD::VZEXT_VL; 8191 if ((!IsSignExt && !IsZeroExt) || !Op0.hasOneUse()) 8192 return SDValue(); 8193 8194 SDValue Mask = N->getOperand(2); 8195 SDValue VL = N->getOperand(3); 8196 8197 // Make sure the mask and VL match. 8198 if (Op0.getOperand(1) != Mask || Op0.getOperand(2) != VL) 8199 return SDValue(); 8200 8201 MVT VT = N->getSimpleValueType(0); 8202 8203 // Determine the narrow size for a widening multiply. 8204 unsigned NarrowSize = VT.getScalarSizeInBits() / 2; 8205 MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize), 8206 VT.getVectorElementCount()); 8207 8208 SDLoc DL(N); 8209 8210 // See if the other operand is the same opcode. 8211 if (IsVWMULSU || Op0.getOpcode() == Op1.getOpcode()) { 8212 if (!Op1.hasOneUse()) 8213 return SDValue(); 8214 8215 // Make sure the mask and VL match. 8216 if (Op1.getOperand(1) != Mask || Op1.getOperand(2) != VL) 8217 return SDValue(); 8218 8219 Op1 = Op1.getOperand(0); 8220 } else if (Op1.getOpcode() == RISCVISD::VMV_V_X_VL) { 8221 // The operand is a splat of a scalar. 8222 8223 // The pasthru must be undef for tail agnostic 8224 if (!Op1.getOperand(0).isUndef()) 8225 return SDValue(); 8226 // The VL must be the same. 8227 if (Op1.getOperand(2) != VL) 8228 return SDValue(); 8229 8230 // Get the scalar value. 8231 Op1 = Op1.getOperand(1); 8232 8233 // See if have enough sign bits or zero bits in the scalar to use a 8234 // widening multiply by splatting to smaller element size. 8235 unsigned EltBits = VT.getScalarSizeInBits(); 8236 unsigned ScalarBits = Op1.getValueSizeInBits(); 8237 // Make sure we're getting all element bits from the scalar register. 8238 // FIXME: Support implicit sign extension of vmv.v.x? 8239 if (ScalarBits < EltBits) 8240 return SDValue(); 8241 8242 // If the LHS is a sign extend, try to use vwmul. 8243 if (IsSignExt && DAG.ComputeNumSignBits(Op1) > (ScalarBits - NarrowSize)) { 8244 // Can use vwmul. 8245 } else { 8246 // Otherwise try to use vwmulu or vwmulsu. 8247 APInt Mask = APInt::getBitsSetFrom(ScalarBits, NarrowSize); 8248 if (DAG.MaskedValueIsZero(Op1, Mask)) 8249 IsVWMULSU = IsSignExt; 8250 else 8251 return SDValue(); 8252 } 8253 8254 Op1 = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT, 8255 DAG.getUNDEF(NarrowVT), Op1, VL); 8256 } else 8257 return SDValue(); 8258 8259 Op0 = Op0.getOperand(0); 8260 8261 // Re-introduce narrower extends if needed. 8262 unsigned ExtOpc = IsSignExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL; 8263 if (Op0.getValueType() != NarrowVT) 8264 Op0 = DAG.getNode(ExtOpc, DL, NarrowVT, Op0, Mask, VL); 8265 // vwmulsu requires second operand to be zero extended. 8266 ExtOpc = IsVWMULSU ? RISCVISD::VZEXT_VL : ExtOpc; 8267 if (Op1.getValueType() != NarrowVT) 8268 Op1 = DAG.getNode(ExtOpc, DL, NarrowVT, Op1, Mask, VL); 8269 8270 unsigned WMulOpc = RISCVISD::VWMULSU_VL; 8271 if (!IsVWMULSU) 8272 WMulOpc = IsSignExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL; 8273 return DAG.getNode(WMulOpc, DL, VT, Op0, Op1, Mask, VL); 8274 } 8275 8276 static RISCVFPRndMode::RoundingMode matchRoundingOp(SDValue Op) { 8277 switch (Op.getOpcode()) { 8278 case ISD::FROUNDEVEN: return RISCVFPRndMode::RNE; 8279 case ISD::FTRUNC: return RISCVFPRndMode::RTZ; 8280 case ISD::FFLOOR: return RISCVFPRndMode::RDN; 8281 case ISD::FCEIL: return RISCVFPRndMode::RUP; 8282 case ISD::FROUND: return RISCVFPRndMode::RMM; 8283 } 8284 8285 return RISCVFPRndMode::Invalid; 8286 } 8287 8288 // Fold 8289 // (fp_to_int (froundeven X)) -> fcvt X, rne 8290 // (fp_to_int (ftrunc X)) -> fcvt X, rtz 8291 // (fp_to_int (ffloor X)) -> fcvt X, rdn 8292 // (fp_to_int (fceil X)) -> fcvt X, rup 8293 // (fp_to_int (fround X)) -> fcvt X, rmm 8294 static SDValue performFP_TO_INTCombine(SDNode *N, 8295 TargetLowering::DAGCombinerInfo &DCI, 8296 const RISCVSubtarget &Subtarget) { 8297 SelectionDAG &DAG = DCI.DAG; 8298 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8299 MVT XLenVT = Subtarget.getXLenVT(); 8300 8301 // Only handle XLen or i32 types. Other types narrower than XLen will 8302 // eventually be legalized to XLenVT. 8303 EVT VT = N->getValueType(0); 8304 if (VT != MVT::i32 && VT != XLenVT) 8305 return SDValue(); 8306 8307 SDValue Src = N->getOperand(0); 8308 8309 // Ensure the FP type is also legal. 8310 if (!TLI.isTypeLegal(Src.getValueType())) 8311 return SDValue(); 8312 8313 // Don't do this for f16 with Zfhmin and not Zfh. 8314 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8315 return SDValue(); 8316 8317 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8318 if (FRM == RISCVFPRndMode::Invalid) 8319 return SDValue(); 8320 8321 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT; 8322 8323 unsigned Opc; 8324 if (VT == XLenVT) 8325 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8326 else 8327 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8328 8329 SDLoc DL(N); 8330 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0), 8331 DAG.getTargetConstant(FRM, DL, XLenVT)); 8332 return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt); 8333 } 8334 8335 // Fold 8336 // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne)) 8337 // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz)) 8338 // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn)) 8339 // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup)) 8340 // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm)) 8341 static SDValue performFP_TO_INT_SATCombine(SDNode *N, 8342 TargetLowering::DAGCombinerInfo &DCI, 8343 const RISCVSubtarget &Subtarget) { 8344 SelectionDAG &DAG = DCI.DAG; 8345 const TargetLowering &TLI = DAG.getTargetLoweringInfo(); 8346 MVT XLenVT = Subtarget.getXLenVT(); 8347 8348 // Only handle XLen types. Other types narrower than XLen will eventually be 8349 // legalized to XLenVT. 8350 EVT DstVT = N->getValueType(0); 8351 if (DstVT != XLenVT) 8352 return SDValue(); 8353 8354 SDValue Src = N->getOperand(0); 8355 8356 // Ensure the FP type is also legal. 8357 if (!TLI.isTypeLegal(Src.getValueType())) 8358 return SDValue(); 8359 8360 // Don't do this for f16 with Zfhmin and not Zfh. 8361 if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) 8362 return SDValue(); 8363 8364 EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT(); 8365 8366 RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src); 8367 if (FRM == RISCVFPRndMode::Invalid) 8368 return SDValue(); 8369 8370 bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT; 8371 8372 unsigned Opc; 8373 if (SatVT == DstVT) 8374 Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU; 8375 else if (DstVT == MVT::i64 && SatVT == MVT::i32) 8376 Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64; 8377 else 8378 return SDValue(); 8379 // FIXME: Support other SatVTs by clamping before or after the conversion. 8380 8381 Src = Src.getOperand(0); 8382 8383 SDLoc DL(N); 8384 SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src, 8385 DAG.getTargetConstant(FRM, DL, XLenVT)); 8386 8387 // RISCV FP-to-int conversions saturate to the destination register size, but 8388 // don't produce 0 for nan. 8389 SDValue ZeroInt = DAG.getConstant(0, DL, DstVT); 8390 return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO); 8391 } 8392 8393 // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is 8394 // smaller than XLenVT. 8395 static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG, 8396 const RISCVSubtarget &Subtarget) { 8397 assert(Subtarget.hasStdExtZbkb() && "Unexpected extension"); 8398 8399 SDValue Src = N->getOperand(0); 8400 if (Src.getOpcode() != ISD::BSWAP) 8401 return SDValue(); 8402 8403 EVT VT = N->getValueType(0); 8404 if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() || 8405 !isPowerOf2_32(VT.getSizeInBits())) 8406 return SDValue(); 8407 8408 SDLoc DL(N); 8409 return DAG.getNode(RISCVISD::GREV, DL, VT, Src.getOperand(0), 8410 DAG.getConstant(7, DL, VT)); 8411 } 8412 8413 SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N, 8414 DAGCombinerInfo &DCI) const { 8415 SelectionDAG &DAG = DCI.DAG; 8416 8417 // Helper to call SimplifyDemandedBits on an operand of N where only some low 8418 // bits are demanded. N will be added to the Worklist if it was not deleted. 8419 // Caller should return SDValue(N, 0) if this returns true. 8420 auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) { 8421 SDValue Op = N->getOperand(OpNo); 8422 APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits); 8423 if (!SimplifyDemandedBits(Op, Mask, DCI)) 8424 return false; 8425 8426 if (N->getOpcode() != ISD::DELETED_NODE) 8427 DCI.AddToWorklist(N); 8428 return true; 8429 }; 8430 8431 switch (N->getOpcode()) { 8432 default: 8433 break; 8434 case RISCVISD::SplitF64: { 8435 SDValue Op0 = N->getOperand(0); 8436 // If the input to SplitF64 is just BuildPairF64 then the operation is 8437 // redundant. Instead, use BuildPairF64's operands directly. 8438 if (Op0->getOpcode() == RISCVISD::BuildPairF64) 8439 return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1)); 8440 8441 if (Op0->isUndef()) { 8442 SDValue Lo = DAG.getUNDEF(MVT::i32); 8443 SDValue Hi = DAG.getUNDEF(MVT::i32); 8444 return DCI.CombineTo(N, Lo, Hi); 8445 } 8446 8447 SDLoc DL(N); 8448 8449 // It's cheaper to materialise two 32-bit integers than to load a double 8450 // from the constant pool and transfer it to integer registers through the 8451 // stack. 8452 if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) { 8453 APInt V = C->getValueAPF().bitcastToAPInt(); 8454 SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32); 8455 SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32); 8456 return DCI.CombineTo(N, Lo, Hi); 8457 } 8458 8459 // This is a target-specific version of a DAGCombine performed in 8460 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8461 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8462 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8463 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8464 !Op0.getNode()->hasOneUse()) 8465 break; 8466 SDValue NewSplitF64 = 8467 DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), 8468 Op0.getOperand(0)); 8469 SDValue Lo = NewSplitF64.getValue(0); 8470 SDValue Hi = NewSplitF64.getValue(1); 8471 APInt SignBit = APInt::getSignMask(32); 8472 if (Op0.getOpcode() == ISD::FNEG) { 8473 SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi, 8474 DAG.getConstant(SignBit, DL, MVT::i32)); 8475 return DCI.CombineTo(N, Lo, NewHi); 8476 } 8477 assert(Op0.getOpcode() == ISD::FABS); 8478 SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi, 8479 DAG.getConstant(~SignBit, DL, MVT::i32)); 8480 return DCI.CombineTo(N, Lo, NewHi); 8481 } 8482 case RISCVISD::SLLW: 8483 case RISCVISD::SRAW: 8484 case RISCVISD::SRLW: { 8485 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8486 if (SimplifyDemandedLowBitsHelper(0, 32) || 8487 SimplifyDemandedLowBitsHelper(1, 5)) 8488 return SDValue(N, 0); 8489 8490 break; 8491 } 8492 case ISD::ROTR: 8493 case ISD::ROTL: 8494 case RISCVISD::RORW: 8495 case RISCVISD::ROLW: { 8496 if (N->getOpcode() == RISCVISD::RORW || N->getOpcode() == RISCVISD::ROLW) { 8497 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8498 if (SimplifyDemandedLowBitsHelper(0, 32) || 8499 SimplifyDemandedLowBitsHelper(1, 5)) 8500 return SDValue(N, 0); 8501 } 8502 8503 return combineROTR_ROTL_RORW_ROLW(N, DAG, Subtarget); 8504 } 8505 case RISCVISD::CLZW: 8506 case RISCVISD::CTZW: { 8507 // Only the lower 32 bits of the first operand are read 8508 if (SimplifyDemandedLowBitsHelper(0, 32)) 8509 return SDValue(N, 0); 8510 break; 8511 } 8512 case RISCVISD::GREV: 8513 case RISCVISD::GORC: { 8514 // Only the lower log2(Bitwidth) bits of the the shift amount are read. 8515 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8516 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8517 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth))) 8518 return SDValue(N, 0); 8519 8520 return combineGREVI_GORCI(N, DAG); 8521 } 8522 case RISCVISD::GREVW: 8523 case RISCVISD::GORCW: { 8524 // Only the lower 32 bits of LHS and lower 5 bits of RHS are read. 8525 if (SimplifyDemandedLowBitsHelper(0, 32) || 8526 SimplifyDemandedLowBitsHelper(1, 5)) 8527 return SDValue(N, 0); 8528 8529 break; 8530 } 8531 case RISCVISD::SHFL: 8532 case RISCVISD::UNSHFL: { 8533 // Only the lower log2(Bitwidth)-1 bits of the the shift amount are read. 8534 unsigned BitWidth = N->getOperand(1).getValueSizeInBits(); 8535 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8536 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) - 1)) 8537 return SDValue(N, 0); 8538 8539 break; 8540 } 8541 case RISCVISD::SHFLW: 8542 case RISCVISD::UNSHFLW: { 8543 // Only the lower 32 bits of LHS and lower 4 bits of RHS are read. 8544 if (SimplifyDemandedLowBitsHelper(0, 32) || 8545 SimplifyDemandedLowBitsHelper(1, 4)) 8546 return SDValue(N, 0); 8547 8548 break; 8549 } 8550 case RISCVISD::BCOMPRESSW: 8551 case RISCVISD::BDECOMPRESSW: { 8552 // Only the lower 32 bits of LHS and RHS are read. 8553 if (SimplifyDemandedLowBitsHelper(0, 32) || 8554 SimplifyDemandedLowBitsHelper(1, 32)) 8555 return SDValue(N, 0); 8556 8557 break; 8558 } 8559 case RISCVISD::FSR: 8560 case RISCVISD::FSL: 8561 case RISCVISD::FSRW: 8562 case RISCVISD::FSLW: { 8563 bool IsWInstruction = 8564 N->getOpcode() == RISCVISD::FSRW || N->getOpcode() == RISCVISD::FSLW; 8565 unsigned BitWidth = 8566 IsWInstruction ? 32 : N->getSimpleValueType(0).getSizeInBits(); 8567 assert(isPowerOf2_32(BitWidth) && "Unexpected bit width"); 8568 // Only the lower log2(Bitwidth)+1 bits of the the shift amount are read. 8569 if (SimplifyDemandedLowBitsHelper(1, Log2_32(BitWidth) + 1)) 8570 return SDValue(N, 0); 8571 8572 break; 8573 } 8574 case RISCVISD::FMV_X_ANYEXTH: 8575 case RISCVISD::FMV_X_ANYEXTW_RV64: { 8576 SDLoc DL(N); 8577 SDValue Op0 = N->getOperand(0); 8578 MVT VT = N->getSimpleValueType(0); 8579 // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the 8580 // conversion is unnecessary and can be replaced with the FMV_W_X_RV64 8581 // operand. Similar for FMV_X_ANYEXTH and FMV_H_X. 8582 if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 && 8583 Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) || 8584 (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH && 8585 Op0->getOpcode() == RISCVISD::FMV_H_X)) { 8586 assert(Op0.getOperand(0).getValueType() == VT && 8587 "Unexpected value type!"); 8588 return Op0.getOperand(0); 8589 } 8590 8591 // This is a target-specific version of a DAGCombine performed in 8592 // DAGCombiner::visitBITCAST. It performs the equivalent of: 8593 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit) 8594 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit)) 8595 if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) || 8596 !Op0.getNode()->hasOneUse()) 8597 break; 8598 SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0)); 8599 unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16; 8600 APInt SignBit = APInt::getSignMask(FPBits).sext(VT.getSizeInBits()); 8601 if (Op0.getOpcode() == ISD::FNEG) 8602 return DAG.getNode(ISD::XOR, DL, VT, NewFMV, 8603 DAG.getConstant(SignBit, DL, VT)); 8604 8605 assert(Op0.getOpcode() == ISD::FABS); 8606 return DAG.getNode(ISD::AND, DL, VT, NewFMV, 8607 DAG.getConstant(~SignBit, DL, VT)); 8608 } 8609 case ISD::ADD: 8610 return performADDCombine(N, DAG, Subtarget); 8611 case ISD::SUB: 8612 return performSUBCombine(N, DAG); 8613 case ISD::AND: 8614 return performANDCombine(N, DAG, Subtarget); 8615 case ISD::OR: 8616 return performORCombine(N, DAG, Subtarget); 8617 case ISD::XOR: 8618 return performXORCombine(N, DAG); 8619 case ISD::FADD: 8620 case ISD::UMAX: 8621 case ISD::UMIN: 8622 case ISD::SMAX: 8623 case ISD::SMIN: 8624 case ISD::FMAXNUM: 8625 case ISD::FMINNUM: 8626 return combineBinOpToReduce(N, DAG); 8627 case ISD::SIGN_EXTEND_INREG: 8628 return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget); 8629 case ISD::ZERO_EXTEND: 8630 // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during 8631 // type legalization. This is safe because fp_to_uint produces poison if 8632 // it overflows. 8633 if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) { 8634 SDValue Src = N->getOperand(0); 8635 if (Src.getOpcode() == ISD::FP_TO_UINT && 8636 isTypeLegal(Src.getOperand(0).getValueType())) 8637 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64, 8638 Src.getOperand(0)); 8639 if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() && 8640 isTypeLegal(Src.getOperand(1).getValueType())) { 8641 SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other); 8642 SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs, 8643 Src.getOperand(0), Src.getOperand(1)); 8644 DCI.CombineTo(N, Res); 8645 DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1)); 8646 DCI.recursivelyDeleteUnusedNodes(Src.getNode()); 8647 return SDValue(N, 0); // Return N so it doesn't get rechecked. 8648 } 8649 } 8650 return SDValue(); 8651 case RISCVISD::SELECT_CC: { 8652 // Transform 8653 SDValue LHS = N->getOperand(0); 8654 SDValue RHS = N->getOperand(1); 8655 SDValue TrueV = N->getOperand(3); 8656 SDValue FalseV = N->getOperand(4); 8657 8658 // If the True and False values are the same, we don't need a select_cc. 8659 if (TrueV == FalseV) 8660 return TrueV; 8661 8662 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(2))->get(); 8663 if (!ISD::isIntEqualitySetCC(CCVal)) 8664 break; 8665 8666 // Fold (select_cc (setlt X, Y), 0, ne, trueV, falseV) -> 8667 // (select_cc X, Y, lt, trueV, falseV) 8668 // Sometimes the setcc is introduced after select_cc has been formed. 8669 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8670 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8671 // If we're looking for eq 0 instead of ne 0, we need to invert the 8672 // condition. 8673 bool Invert = CCVal == ISD::SETEQ; 8674 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8675 if (Invert) 8676 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8677 8678 SDLoc DL(N); 8679 RHS = LHS.getOperand(1); 8680 LHS = LHS.getOperand(0); 8681 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8682 8683 SDValue TargetCC = DAG.getCondCode(CCVal); 8684 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8685 {LHS, RHS, TargetCC, TrueV, FalseV}); 8686 } 8687 8688 // Fold (select_cc (xor X, Y), 0, eq/ne, trueV, falseV) -> 8689 // (select_cc X, Y, eq/ne, trueV, falseV) 8690 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8691 return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), N->getValueType(0), 8692 {LHS.getOperand(0), LHS.getOperand(1), 8693 N->getOperand(2), TrueV, FalseV}); 8694 // (select_cc X, 1, setne, trueV, falseV) -> 8695 // (select_cc X, 0, seteq, trueV, falseV) if we can prove X is 0/1. 8696 // This can occur when legalizing some floating point comparisons. 8697 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8698 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8699 SDLoc DL(N); 8700 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8701 SDValue TargetCC = DAG.getCondCode(CCVal); 8702 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8703 return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0), 8704 {LHS, RHS, TargetCC, TrueV, FalseV}); 8705 } 8706 8707 break; 8708 } 8709 case RISCVISD::BR_CC: { 8710 SDValue LHS = N->getOperand(1); 8711 SDValue RHS = N->getOperand(2); 8712 ISD::CondCode CCVal = cast<CondCodeSDNode>(N->getOperand(3))->get(); 8713 if (!ISD::isIntEqualitySetCC(CCVal)) 8714 break; 8715 8716 // Fold (br_cc (setlt X, Y), 0, ne, dest) -> 8717 // (br_cc X, Y, lt, dest) 8718 // Sometimes the setcc is introduced after br_cc has been formed. 8719 if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) && 8720 LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) { 8721 // If we're looking for eq 0 instead of ne 0, we need to invert the 8722 // condition. 8723 bool Invert = CCVal == ISD::SETEQ; 8724 CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get(); 8725 if (Invert) 8726 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8727 8728 SDLoc DL(N); 8729 RHS = LHS.getOperand(1); 8730 LHS = LHS.getOperand(0); 8731 translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG); 8732 8733 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8734 N->getOperand(0), LHS, RHS, DAG.getCondCode(CCVal), 8735 N->getOperand(4)); 8736 } 8737 8738 // Fold (br_cc (xor X, Y), 0, eq/ne, dest) -> 8739 // (br_cc X, Y, eq/ne, trueV, falseV) 8740 if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) 8741 return DAG.getNode(RISCVISD::BR_CC, SDLoc(N), N->getValueType(0), 8742 N->getOperand(0), LHS.getOperand(0), LHS.getOperand(1), 8743 N->getOperand(3), N->getOperand(4)); 8744 8745 // (br_cc X, 1, setne, br_cc) -> 8746 // (br_cc X, 0, seteq, br_cc) if we can prove X is 0/1. 8747 // This can occur when legalizing some floating point comparisons. 8748 APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1); 8749 if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) { 8750 SDLoc DL(N); 8751 CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType()); 8752 SDValue TargetCC = DAG.getCondCode(CCVal); 8753 RHS = DAG.getConstant(0, DL, LHS.getValueType()); 8754 return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0), 8755 N->getOperand(0), LHS, RHS, TargetCC, 8756 N->getOperand(4)); 8757 } 8758 break; 8759 } 8760 case ISD::BITREVERSE: 8761 return performBITREVERSECombine(N, DAG, Subtarget); 8762 case ISD::FP_TO_SINT: 8763 case ISD::FP_TO_UINT: 8764 return performFP_TO_INTCombine(N, DCI, Subtarget); 8765 case ISD::FP_TO_SINT_SAT: 8766 case ISD::FP_TO_UINT_SAT: 8767 return performFP_TO_INT_SATCombine(N, DCI, Subtarget); 8768 case ISD::FCOPYSIGN: { 8769 EVT VT = N->getValueType(0); 8770 if (!VT.isVector()) 8771 break; 8772 // There is a form of VFSGNJ which injects the negated sign of its second 8773 // operand. Try and bubble any FNEG up after the extend/round to produce 8774 // this optimized pattern. Avoid modifying cases where FP_ROUND and 8775 // TRUNC=1. 8776 SDValue In2 = N->getOperand(1); 8777 // Avoid cases where the extend/round has multiple uses, as duplicating 8778 // those is typically more expensive than removing a fneg. 8779 if (!In2.hasOneUse()) 8780 break; 8781 if (In2.getOpcode() != ISD::FP_EXTEND && 8782 (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0)) 8783 break; 8784 In2 = In2.getOperand(0); 8785 if (In2.getOpcode() != ISD::FNEG) 8786 break; 8787 SDLoc DL(N); 8788 SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT); 8789 return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0), 8790 DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound)); 8791 } 8792 case ISD::MGATHER: 8793 case ISD::MSCATTER: 8794 case ISD::VP_GATHER: 8795 case ISD::VP_SCATTER: { 8796 if (!DCI.isBeforeLegalize()) 8797 break; 8798 SDValue Index, ScaleOp; 8799 bool IsIndexScaled = false; 8800 bool IsIndexSigned = false; 8801 if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) { 8802 Index = VPGSN->getIndex(); 8803 ScaleOp = VPGSN->getScale(); 8804 IsIndexScaled = VPGSN->isIndexScaled(); 8805 IsIndexSigned = VPGSN->isIndexSigned(); 8806 } else { 8807 const auto *MGSN = cast<MaskedGatherScatterSDNode>(N); 8808 Index = MGSN->getIndex(); 8809 ScaleOp = MGSN->getScale(); 8810 IsIndexScaled = MGSN->isIndexScaled(); 8811 IsIndexSigned = MGSN->isIndexSigned(); 8812 } 8813 EVT IndexVT = Index.getValueType(); 8814 MVT XLenVT = Subtarget.getXLenVT(); 8815 // RISCV indexed loads only support the "unsigned unscaled" addressing 8816 // mode, so anything else must be manually legalized. 8817 bool NeedsIdxLegalization = 8818 IsIndexScaled || 8819 (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT)); 8820 if (!NeedsIdxLegalization) 8821 break; 8822 8823 SDLoc DL(N); 8824 8825 // Any index legalization should first promote to XLenVT, so we don't lose 8826 // bits when scaling. This may create an illegal index type so we let 8827 // LLVM's legalization take care of the splitting. 8828 // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet. 8829 if (IndexVT.getVectorElementType().bitsLT(XLenVT)) { 8830 IndexVT = IndexVT.changeVectorElementType(XLenVT); 8831 Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, 8832 DL, IndexVT, Index); 8833 } 8834 8835 if (IsIndexScaled) { 8836 // Manually scale the indices. 8837 // TODO: Sanitize the scale operand here? 8838 // TODO: For VP nodes, should we use VP_SHL here? 8839 unsigned Scale = cast<ConstantSDNode>(ScaleOp)->getZExtValue(); 8840 assert(isPowerOf2_32(Scale) && "Expecting power-of-two types"); 8841 SDValue SplatScale = DAG.getConstant(Log2_32(Scale), DL, IndexVT); 8842 Index = DAG.getNode(ISD::SHL, DL, IndexVT, Index, SplatScale); 8843 ScaleOp = DAG.getTargetConstant(1, DL, ScaleOp.getValueType()); 8844 } 8845 8846 ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_SCALED; 8847 if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N)) 8848 return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL, 8849 {VPGN->getChain(), VPGN->getBasePtr(), Index, 8850 ScaleOp, VPGN->getMask(), 8851 VPGN->getVectorLength()}, 8852 VPGN->getMemOperand(), NewIndexTy); 8853 if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N)) 8854 return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL, 8855 {VPSN->getChain(), VPSN->getValue(), 8856 VPSN->getBasePtr(), Index, ScaleOp, 8857 VPSN->getMask(), VPSN->getVectorLength()}, 8858 VPSN->getMemOperand(), NewIndexTy); 8859 if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N)) 8860 return DAG.getMaskedGather( 8861 N->getVTList(), MGN->getMemoryVT(), DL, 8862 {MGN->getChain(), MGN->getPassThru(), MGN->getMask(), 8863 MGN->getBasePtr(), Index, ScaleOp}, 8864 MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType()); 8865 const auto *MSN = cast<MaskedScatterSDNode>(N); 8866 return DAG.getMaskedScatter( 8867 N->getVTList(), MSN->getMemoryVT(), DL, 8868 {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(), 8869 Index, ScaleOp}, 8870 MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore()); 8871 } 8872 case RISCVISD::SRA_VL: 8873 case RISCVISD::SRL_VL: 8874 case RISCVISD::SHL_VL: { 8875 SDValue ShAmt = N->getOperand(1); 8876 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8877 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8878 SDLoc DL(N); 8879 SDValue VL = N->getOperand(3); 8880 EVT VT = N->getValueType(0); 8881 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8882 ShAmt.getOperand(1), VL); 8883 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt, 8884 N->getOperand(2), N->getOperand(3)); 8885 } 8886 break; 8887 } 8888 case ISD::SRA: 8889 case ISD::SRL: 8890 case ISD::SHL: { 8891 SDValue ShAmt = N->getOperand(1); 8892 if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) { 8893 // We don't need the upper 32 bits of a 64-bit element for a shift amount. 8894 SDLoc DL(N); 8895 EVT VT = N->getValueType(0); 8896 ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT), 8897 ShAmt.getOperand(1), 8898 DAG.getRegister(RISCV::X0, Subtarget.getXLenVT())); 8899 return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt); 8900 } 8901 break; 8902 } 8903 case RISCVISD::ADD_VL: 8904 if (SDValue V = combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ false)) 8905 return V; 8906 return combineADDSUB_VLToVWADDSUB_VL(N, DAG, /*Commute*/ true); 8907 case RISCVISD::SUB_VL: 8908 return combineADDSUB_VLToVWADDSUB_VL(N, DAG); 8909 case RISCVISD::VWADD_W_VL: 8910 case RISCVISD::VWADDU_W_VL: 8911 case RISCVISD::VWSUB_W_VL: 8912 case RISCVISD::VWSUBU_W_VL: 8913 return combineVWADD_W_VL_VWSUB_W_VL(N, DAG); 8914 case RISCVISD::MUL_VL: 8915 if (SDValue V = combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ false)) 8916 return V; 8917 // Mul is commutative. 8918 return combineMUL_VLToVWMUL_VL(N, DAG, /*Commute*/ true); 8919 case ISD::STORE: { 8920 auto *Store = cast<StoreSDNode>(N); 8921 SDValue Val = Store->getValue(); 8922 // Combine store of vmv.x.s to vse with VL of 1. 8923 // FIXME: Support FP. 8924 if (Val.getOpcode() == RISCVISD::VMV_X_S) { 8925 SDValue Src = Val.getOperand(0); 8926 EVT VecVT = Src.getValueType(); 8927 EVT MemVT = Store->getMemoryVT(); 8928 // The memory VT and the element type must match. 8929 if (VecVT.getVectorElementType() == MemVT) { 8930 SDLoc DL(N); 8931 MVT MaskVT = getMaskTypeFor(VecVT); 8932 return DAG.getStoreVP( 8933 Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(), 8934 DAG.getConstant(1, DL, MaskVT), 8935 DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT, 8936 Store->getMemOperand(), Store->getAddressingMode(), 8937 Store->isTruncatingStore(), /*IsCompress*/ false); 8938 } 8939 } 8940 8941 break; 8942 } 8943 case ISD::SPLAT_VECTOR: { 8944 EVT VT = N->getValueType(0); 8945 // Only perform this combine on legal MVT types. 8946 if (!isTypeLegal(VT)) 8947 break; 8948 if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N, 8949 DAG, Subtarget)) 8950 return Gather; 8951 break; 8952 } 8953 case RISCVISD::VMV_V_X_VL: { 8954 // Tail agnostic VMV.V.X only demands the vector element bitwidth from the 8955 // scalar input. 8956 unsigned ScalarSize = N->getOperand(1).getValueSizeInBits(); 8957 unsigned EltWidth = N->getValueType(0).getScalarSizeInBits(); 8958 if (ScalarSize > EltWidth && N->getOperand(0).isUndef()) 8959 if (SimplifyDemandedLowBitsHelper(1, EltWidth)) 8960 return SDValue(N, 0); 8961 8962 break; 8963 } 8964 case ISD::INTRINSIC_WO_CHAIN: { 8965 unsigned IntNo = N->getConstantOperandVal(0); 8966 switch (IntNo) { 8967 // By default we do not combine any intrinsic. 8968 default: 8969 return SDValue(); 8970 case Intrinsic::riscv_vcpop: 8971 case Intrinsic::riscv_vcpop_mask: 8972 case Intrinsic::riscv_vfirst: 8973 case Intrinsic::riscv_vfirst_mask: { 8974 SDValue VL = N->getOperand(2); 8975 if (IntNo == Intrinsic::riscv_vcpop_mask || 8976 IntNo == Intrinsic::riscv_vfirst_mask) 8977 VL = N->getOperand(3); 8978 if (!isNullConstant(VL)) 8979 return SDValue(); 8980 // If VL is 0, vcpop -> li 0, vfirst -> li -1. 8981 SDLoc DL(N); 8982 EVT VT = N->getValueType(0); 8983 if (IntNo == Intrinsic::riscv_vfirst || 8984 IntNo == Intrinsic::riscv_vfirst_mask) 8985 return DAG.getConstant(-1, DL, VT); 8986 return DAG.getConstant(0, DL, VT); 8987 } 8988 } 8989 } 8990 } 8991 8992 return SDValue(); 8993 } 8994 8995 bool RISCVTargetLowering::isDesirableToCommuteWithShift( 8996 const SDNode *N, CombineLevel Level) const { 8997 // The following folds are only desirable if `(OP _, c1 << c2)` can be 8998 // materialised in fewer instructions than `(OP _, c1)`: 8999 // 9000 // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2) 9001 // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2) 9002 SDValue N0 = N->getOperand(0); 9003 EVT Ty = N0.getValueType(); 9004 if (Ty.isScalarInteger() && 9005 (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) { 9006 auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1)); 9007 auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)); 9008 if (C1 && C2) { 9009 const APInt &C1Int = C1->getAPIntValue(); 9010 APInt ShiftedC1Int = C1Int << C2->getAPIntValue(); 9011 9012 // We can materialise `c1 << c2` into an add immediate, so it's "free", 9013 // and the combine should happen, to potentially allow further combines 9014 // later. 9015 if (ShiftedC1Int.getMinSignedBits() <= 64 && 9016 isLegalAddImmediate(ShiftedC1Int.getSExtValue())) 9017 return true; 9018 9019 // We can materialise `c1` in an add immediate, so it's "free", and the 9020 // combine should be prevented. 9021 if (C1Int.getMinSignedBits() <= 64 && 9022 isLegalAddImmediate(C1Int.getSExtValue())) 9023 return false; 9024 9025 // Neither constant will fit into an immediate, so find materialisation 9026 // costs. 9027 int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(), 9028 Subtarget.getFeatureBits(), 9029 /*CompressionCost*/true); 9030 int ShiftedC1Cost = RISCVMatInt::getIntMatCost( 9031 ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(), 9032 /*CompressionCost*/true); 9033 9034 // Materialising `c1` is cheaper than materialising `c1 << c2`, so the 9035 // combine should be prevented. 9036 if (C1Cost < ShiftedC1Cost) 9037 return false; 9038 } 9039 } 9040 return true; 9041 } 9042 9043 bool RISCVTargetLowering::targetShrinkDemandedConstant( 9044 SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts, 9045 TargetLoweringOpt &TLO) const { 9046 // Delay this optimization as late as possible. 9047 if (!TLO.LegalOps) 9048 return false; 9049 9050 EVT VT = Op.getValueType(); 9051 if (VT.isVector()) 9052 return false; 9053 9054 // Only handle AND for now. 9055 if (Op.getOpcode() != ISD::AND) 9056 return false; 9057 9058 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1)); 9059 if (!C) 9060 return false; 9061 9062 const APInt &Mask = C->getAPIntValue(); 9063 9064 // Clear all non-demanded bits initially. 9065 APInt ShrunkMask = Mask & DemandedBits; 9066 9067 // Try to make a smaller immediate by setting undemanded bits. 9068 9069 APInt ExpandedMask = Mask | ~DemandedBits; 9070 9071 auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool { 9072 return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask); 9073 }; 9074 auto UseMask = [Mask, Op, VT, &TLO](const APInt &NewMask) -> bool { 9075 if (NewMask == Mask) 9076 return true; 9077 SDLoc DL(Op); 9078 SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT); 9079 SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC); 9080 return TLO.CombineTo(Op, NewOp); 9081 }; 9082 9083 // If the shrunk mask fits in sign extended 12 bits, let the target 9084 // independent code apply it. 9085 if (ShrunkMask.isSignedIntN(12)) 9086 return false; 9087 9088 // Preserve (and X, 0xffff) when zext.h is supported. 9089 if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbp()) { 9090 APInt NewMask = APInt(Mask.getBitWidth(), 0xffff); 9091 if (IsLegalMask(NewMask)) 9092 return UseMask(NewMask); 9093 } 9094 9095 // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern. 9096 if (VT == MVT::i64) { 9097 APInt NewMask = APInt(64, 0xffffffff); 9098 if (IsLegalMask(NewMask)) 9099 return UseMask(NewMask); 9100 } 9101 9102 // For the remaining optimizations, we need to be able to make a negative 9103 // number through a combination of mask and undemanded bits. 9104 if (!ExpandedMask.isNegative()) 9105 return false; 9106 9107 // What is the fewest number of bits we need to represent the negative number. 9108 unsigned MinSignedBits = ExpandedMask.getMinSignedBits(); 9109 9110 // Try to make a 12 bit negative immediate. If that fails try to make a 32 9111 // bit negative immediate unless the shrunk immediate already fits in 32 bits. 9112 APInt NewMask = ShrunkMask; 9113 if (MinSignedBits <= 12) 9114 NewMask.setBitsFrom(11); 9115 else if (MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32)) 9116 NewMask.setBitsFrom(31); 9117 else 9118 return false; 9119 9120 // Check that our new mask is a subset of the demanded mask. 9121 assert(IsLegalMask(NewMask)); 9122 return UseMask(NewMask); 9123 } 9124 9125 static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) { 9126 static const uint64_t GREVMasks[] = { 9127 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL, 9128 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL}; 9129 9130 for (unsigned Stage = 0; Stage != 6; ++Stage) { 9131 unsigned Shift = 1 << Stage; 9132 if (ShAmt & Shift) { 9133 uint64_t Mask = GREVMasks[Stage]; 9134 uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask); 9135 if (IsGORC) 9136 Res |= x; 9137 x = Res; 9138 } 9139 } 9140 9141 return x; 9142 } 9143 9144 void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op, 9145 KnownBits &Known, 9146 const APInt &DemandedElts, 9147 const SelectionDAG &DAG, 9148 unsigned Depth) const { 9149 unsigned BitWidth = Known.getBitWidth(); 9150 unsigned Opc = Op.getOpcode(); 9151 assert((Opc >= ISD::BUILTIN_OP_END || 9152 Opc == ISD::INTRINSIC_WO_CHAIN || 9153 Opc == ISD::INTRINSIC_W_CHAIN || 9154 Opc == ISD::INTRINSIC_VOID) && 9155 "Should use MaskedValueIsZero if you don't know whether Op" 9156 " is a target node!"); 9157 9158 Known.resetAll(); 9159 switch (Opc) { 9160 default: break; 9161 case RISCVISD::SELECT_CC: { 9162 Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1); 9163 // If we don't know any bits, early out. 9164 if (Known.isUnknown()) 9165 break; 9166 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1); 9167 9168 // Only known if known in both the LHS and RHS. 9169 Known = KnownBits::commonBits(Known, Known2); 9170 break; 9171 } 9172 case RISCVISD::REMUW: { 9173 KnownBits Known2; 9174 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9175 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9176 // We only care about the lower 32 bits. 9177 Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32)); 9178 // Restore the original width by sign extending. 9179 Known = Known.sext(BitWidth); 9180 break; 9181 } 9182 case RISCVISD::DIVUW: { 9183 KnownBits Known2; 9184 Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1); 9185 Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1); 9186 // We only care about the lower 32 bits. 9187 Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32)); 9188 // Restore the original width by sign extending. 9189 Known = Known.sext(BitWidth); 9190 break; 9191 } 9192 case RISCVISD::CTZW: { 9193 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9194 unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros(); 9195 unsigned LowBits = Log2_32(PossibleTZ) + 1; 9196 Known.Zero.setBitsFrom(LowBits); 9197 break; 9198 } 9199 case RISCVISD::CLZW: { 9200 KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9201 unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros(); 9202 unsigned LowBits = Log2_32(PossibleLZ) + 1; 9203 Known.Zero.setBitsFrom(LowBits); 9204 break; 9205 } 9206 case RISCVISD::GREV: 9207 case RISCVISD::GORC: { 9208 if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) { 9209 Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1); 9210 unsigned ShAmt = C->getZExtValue() & (Known.getBitWidth() - 1); 9211 bool IsGORC = Op.getOpcode() == RISCVISD::GORC; 9212 // To compute zeros, we need to invert the value and invert it back after. 9213 Known.Zero = 9214 ~computeGREVOrGORC(~Known.Zero.getZExtValue(), ShAmt, IsGORC); 9215 Known.One = computeGREVOrGORC(Known.One.getZExtValue(), ShAmt, IsGORC); 9216 } 9217 break; 9218 } 9219 case RISCVISD::READ_VLENB: { 9220 // If we know the minimum VLen from Zvl extensions, we can use that to 9221 // determine the trailing zeros of VLENB. 9222 // FIXME: Limit to 128 bit vectors until we have more testing. 9223 unsigned MinVLenB = std::min(128U, Subtarget.getMinVLen()) / 8; 9224 if (MinVLenB > 0) 9225 Known.Zero.setLowBits(Log2_32(MinVLenB)); 9226 // We assume VLENB is no more than 65536 / 8 bytes. 9227 Known.Zero.setBitsFrom(14); 9228 break; 9229 } 9230 case ISD::INTRINSIC_W_CHAIN: 9231 case ISD::INTRINSIC_WO_CHAIN: { 9232 unsigned IntNo = 9233 Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1); 9234 switch (IntNo) { 9235 default: 9236 // We can't do anything for most intrinsics. 9237 break; 9238 case Intrinsic::riscv_vsetvli: 9239 case Intrinsic::riscv_vsetvlimax: 9240 case Intrinsic::riscv_vsetvli_opt: 9241 case Intrinsic::riscv_vsetvlimax_opt: 9242 // Assume that VL output is positive and would fit in an int32_t. 9243 // TODO: VLEN might be capped at 16 bits in a future V spec update. 9244 if (BitWidth >= 32) 9245 Known.Zero.setBitsFrom(31); 9246 break; 9247 } 9248 break; 9249 } 9250 } 9251 } 9252 9253 unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode( 9254 SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG, 9255 unsigned Depth) const { 9256 switch (Op.getOpcode()) { 9257 default: 9258 break; 9259 case RISCVISD::SELECT_CC: { 9260 unsigned Tmp = 9261 DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1); 9262 if (Tmp == 1) return 1; // Early out. 9263 unsigned Tmp2 = 9264 DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1); 9265 return std::min(Tmp, Tmp2); 9266 } 9267 case RISCVISD::SLLW: 9268 case RISCVISD::SRAW: 9269 case RISCVISD::SRLW: 9270 case RISCVISD::DIVW: 9271 case RISCVISD::DIVUW: 9272 case RISCVISD::REMUW: 9273 case RISCVISD::ROLW: 9274 case RISCVISD::RORW: 9275 case RISCVISD::GREVW: 9276 case RISCVISD::GORCW: 9277 case RISCVISD::FSLW: 9278 case RISCVISD::FSRW: 9279 case RISCVISD::SHFLW: 9280 case RISCVISD::UNSHFLW: 9281 case RISCVISD::BCOMPRESSW: 9282 case RISCVISD::BDECOMPRESSW: 9283 case RISCVISD::BFPW: 9284 case RISCVISD::FCVT_W_RV64: 9285 case RISCVISD::FCVT_WU_RV64: 9286 case RISCVISD::STRICT_FCVT_W_RV64: 9287 case RISCVISD::STRICT_FCVT_WU_RV64: 9288 // TODO: As the result is sign-extended, this is conservatively correct. A 9289 // more precise answer could be calculated for SRAW depending on known 9290 // bits in the shift amount. 9291 return 33; 9292 case RISCVISD::SHFL: 9293 case RISCVISD::UNSHFL: { 9294 // There is no SHFLIW, but a i64 SHFLI with bit 4 of the control word 9295 // cleared doesn't affect bit 31. The upper 32 bits will be shuffled, but 9296 // will stay within the upper 32 bits. If there were more than 32 sign bits 9297 // before there will be at least 33 sign bits after. 9298 if (Op.getValueType() == MVT::i64 && 9299 isa<ConstantSDNode>(Op.getOperand(1)) && 9300 (Op.getConstantOperandVal(1) & 0x10) == 0) { 9301 unsigned Tmp = DAG.ComputeNumSignBits(Op.getOperand(0), Depth + 1); 9302 if (Tmp > 32) 9303 return 33; 9304 } 9305 break; 9306 } 9307 case RISCVISD::VMV_X_S: { 9308 // The number of sign bits of the scalar result is computed by obtaining the 9309 // element type of the input vector operand, subtracting its width from the 9310 // XLEN, and then adding one (sign bit within the element type). If the 9311 // element type is wider than XLen, the least-significant XLEN bits are 9312 // taken. 9313 unsigned XLen = Subtarget.getXLen(); 9314 unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits(); 9315 if (EltBits <= XLen) 9316 return XLen - EltBits + 1; 9317 break; 9318 } 9319 } 9320 9321 return 1; 9322 } 9323 9324 static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI, 9325 MachineBasicBlock *BB) { 9326 assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction"); 9327 9328 // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves. 9329 // Should the count have wrapped while it was being read, we need to try 9330 // again. 9331 // ... 9332 // read: 9333 // rdcycleh x3 # load high word of cycle 9334 // rdcycle x2 # load low word of cycle 9335 // rdcycleh x4 # load high word of cycle 9336 // bne x3, x4, read # check if high word reads match, otherwise try again 9337 // ... 9338 9339 MachineFunction &MF = *BB->getParent(); 9340 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9341 MachineFunction::iterator It = ++BB->getIterator(); 9342 9343 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9344 MF.insert(It, LoopMBB); 9345 9346 MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB); 9347 MF.insert(It, DoneMBB); 9348 9349 // Transfer the remainder of BB and its successor edges to DoneMBB. 9350 DoneMBB->splice(DoneMBB->begin(), BB, 9351 std::next(MachineBasicBlock::iterator(MI)), BB->end()); 9352 DoneMBB->transferSuccessorsAndUpdatePHIs(BB); 9353 9354 BB->addSuccessor(LoopMBB); 9355 9356 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 9357 Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 9358 Register LoReg = MI.getOperand(0).getReg(); 9359 Register HiReg = MI.getOperand(1).getReg(); 9360 DebugLoc DL = MI.getDebugLoc(); 9361 9362 const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo(); 9363 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg) 9364 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9365 .addReg(RISCV::X0); 9366 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg) 9367 .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding) 9368 .addReg(RISCV::X0); 9369 BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg) 9370 .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding) 9371 .addReg(RISCV::X0); 9372 9373 BuildMI(LoopMBB, DL, TII->get(RISCV::BNE)) 9374 .addReg(HiReg) 9375 .addReg(ReadAgainReg) 9376 .addMBB(LoopMBB); 9377 9378 LoopMBB->addSuccessor(LoopMBB); 9379 LoopMBB->addSuccessor(DoneMBB); 9380 9381 MI.eraseFromParent(); 9382 9383 return DoneMBB; 9384 } 9385 9386 static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI, 9387 MachineBasicBlock *BB) { 9388 assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction"); 9389 9390 MachineFunction &MF = *BB->getParent(); 9391 DebugLoc DL = MI.getDebugLoc(); 9392 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9393 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9394 Register LoReg = MI.getOperand(0).getReg(); 9395 Register HiReg = MI.getOperand(1).getReg(); 9396 Register SrcReg = MI.getOperand(2).getReg(); 9397 const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass; 9398 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9399 9400 TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC, 9401 RI); 9402 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9403 MachineMemOperand *MMOLo = 9404 MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8)); 9405 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9406 MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8)); 9407 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg) 9408 .addFrameIndex(FI) 9409 .addImm(0) 9410 .addMemOperand(MMOLo); 9411 BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg) 9412 .addFrameIndex(FI) 9413 .addImm(4) 9414 .addMemOperand(MMOHi); 9415 MI.eraseFromParent(); // The pseudo instruction is gone now. 9416 return BB; 9417 } 9418 9419 static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI, 9420 MachineBasicBlock *BB) { 9421 assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo && 9422 "Unexpected instruction"); 9423 9424 MachineFunction &MF = *BB->getParent(); 9425 DebugLoc DL = MI.getDebugLoc(); 9426 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 9427 const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo(); 9428 Register DstReg = MI.getOperand(0).getReg(); 9429 Register LoReg = MI.getOperand(1).getReg(); 9430 Register HiReg = MI.getOperand(2).getReg(); 9431 const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass; 9432 int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF); 9433 9434 MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI); 9435 MachineMemOperand *MMOLo = 9436 MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8)); 9437 MachineMemOperand *MMOHi = MF.getMachineMemOperand( 9438 MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8)); 9439 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9440 .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill())) 9441 .addFrameIndex(FI) 9442 .addImm(0) 9443 .addMemOperand(MMOLo); 9444 BuildMI(*BB, MI, DL, TII.get(RISCV::SW)) 9445 .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill())) 9446 .addFrameIndex(FI) 9447 .addImm(4) 9448 .addMemOperand(MMOHi); 9449 TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI); 9450 MI.eraseFromParent(); // The pseudo instruction is gone now. 9451 return BB; 9452 } 9453 9454 static bool isSelectPseudo(MachineInstr &MI) { 9455 switch (MI.getOpcode()) { 9456 default: 9457 return false; 9458 case RISCV::Select_GPR_Using_CC_GPR: 9459 case RISCV::Select_FPR16_Using_CC_GPR: 9460 case RISCV::Select_FPR32_Using_CC_GPR: 9461 case RISCV::Select_FPR64_Using_CC_GPR: 9462 return true; 9463 } 9464 } 9465 9466 static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB, 9467 unsigned RelOpcode, unsigned EqOpcode, 9468 const RISCVSubtarget &Subtarget) { 9469 DebugLoc DL = MI.getDebugLoc(); 9470 Register DstReg = MI.getOperand(0).getReg(); 9471 Register Src1Reg = MI.getOperand(1).getReg(); 9472 Register Src2Reg = MI.getOperand(2).getReg(); 9473 MachineRegisterInfo &MRI = BB->getParent()->getRegInfo(); 9474 Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass); 9475 const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo(); 9476 9477 // Save the current FFLAGS. 9478 BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags); 9479 9480 auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg) 9481 .addReg(Src1Reg) 9482 .addReg(Src2Reg); 9483 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9484 MIB->setFlag(MachineInstr::MIFlag::NoFPExcept); 9485 9486 // Restore the FFLAGS. 9487 BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS)) 9488 .addReg(SavedFFlags, RegState::Kill); 9489 9490 // Issue a dummy FEQ opcode to raise exception for signaling NaNs. 9491 auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0) 9492 .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill())) 9493 .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill())); 9494 if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept)) 9495 MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept); 9496 9497 // Erase the pseudoinstruction. 9498 MI.eraseFromParent(); 9499 return BB; 9500 } 9501 9502 static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI, 9503 MachineBasicBlock *BB, 9504 const RISCVSubtarget &Subtarget) { 9505 // To "insert" Select_* instructions, we actually have to insert the triangle 9506 // control-flow pattern. The incoming instructions know the destination vreg 9507 // to set, the condition code register to branch on, the true/false values to 9508 // select between, and the condcode to use to select the appropriate branch. 9509 // 9510 // We produce the following control flow: 9511 // HeadMBB 9512 // | \ 9513 // | IfFalseMBB 9514 // | / 9515 // TailMBB 9516 // 9517 // When we find a sequence of selects we attempt to optimize their emission 9518 // by sharing the control flow. Currently we only handle cases where we have 9519 // multiple selects with the exact same condition (same LHS, RHS and CC). 9520 // The selects may be interleaved with other instructions if the other 9521 // instructions meet some requirements we deem safe: 9522 // - They are debug instructions. Otherwise, 9523 // - They do not have side-effects, do not access memory and their inputs do 9524 // not depend on the results of the select pseudo-instructions. 9525 // The TrueV/FalseV operands of the selects cannot depend on the result of 9526 // previous selects in the sequence. 9527 // These conditions could be further relaxed. See the X86 target for a 9528 // related approach and more information. 9529 Register LHS = MI.getOperand(1).getReg(); 9530 Register RHS = MI.getOperand(2).getReg(); 9531 auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm()); 9532 9533 SmallVector<MachineInstr *, 4> SelectDebugValues; 9534 SmallSet<Register, 4> SelectDests; 9535 SelectDests.insert(MI.getOperand(0).getReg()); 9536 9537 MachineInstr *LastSelectPseudo = &MI; 9538 9539 for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI); 9540 SequenceMBBI != E; ++SequenceMBBI) { 9541 if (SequenceMBBI->isDebugInstr()) 9542 continue; 9543 if (isSelectPseudo(*SequenceMBBI)) { 9544 if (SequenceMBBI->getOperand(1).getReg() != LHS || 9545 SequenceMBBI->getOperand(2).getReg() != RHS || 9546 SequenceMBBI->getOperand(3).getImm() != CC || 9547 SelectDests.count(SequenceMBBI->getOperand(4).getReg()) || 9548 SelectDests.count(SequenceMBBI->getOperand(5).getReg())) 9549 break; 9550 LastSelectPseudo = &*SequenceMBBI; 9551 SequenceMBBI->collectDebugValues(SelectDebugValues); 9552 SelectDests.insert(SequenceMBBI->getOperand(0).getReg()); 9553 } else { 9554 if (SequenceMBBI->hasUnmodeledSideEffects() || 9555 SequenceMBBI->mayLoadOrStore()) 9556 break; 9557 if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) { 9558 return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg()); 9559 })) 9560 break; 9561 } 9562 } 9563 9564 const RISCVInstrInfo &TII = *Subtarget.getInstrInfo(); 9565 const BasicBlock *LLVM_BB = BB->getBasicBlock(); 9566 DebugLoc DL = MI.getDebugLoc(); 9567 MachineFunction::iterator I = ++BB->getIterator(); 9568 9569 MachineBasicBlock *HeadMBB = BB; 9570 MachineFunction *F = BB->getParent(); 9571 MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB); 9572 MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB); 9573 9574 F->insert(I, IfFalseMBB); 9575 F->insert(I, TailMBB); 9576 9577 // Transfer debug instructions associated with the selects to TailMBB. 9578 for (MachineInstr *DebugInstr : SelectDebugValues) { 9579 TailMBB->push_back(DebugInstr->removeFromParent()); 9580 } 9581 9582 // Move all instructions after the sequence to TailMBB. 9583 TailMBB->splice(TailMBB->end(), HeadMBB, 9584 std::next(LastSelectPseudo->getIterator()), HeadMBB->end()); 9585 // Update machine-CFG edges by transferring all successors of the current 9586 // block to the new block which will contain the Phi nodes for the selects. 9587 TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB); 9588 // Set the successors for HeadMBB. 9589 HeadMBB->addSuccessor(IfFalseMBB); 9590 HeadMBB->addSuccessor(TailMBB); 9591 9592 // Insert appropriate branch. 9593 BuildMI(HeadMBB, DL, TII.getBrCond(CC)) 9594 .addReg(LHS) 9595 .addReg(RHS) 9596 .addMBB(TailMBB); 9597 9598 // IfFalseMBB just falls through to TailMBB. 9599 IfFalseMBB->addSuccessor(TailMBB); 9600 9601 // Create PHIs for all of the select pseudo-instructions. 9602 auto SelectMBBI = MI.getIterator(); 9603 auto SelectEnd = std::next(LastSelectPseudo->getIterator()); 9604 auto InsertionPoint = TailMBB->begin(); 9605 while (SelectMBBI != SelectEnd) { 9606 auto Next = std::next(SelectMBBI); 9607 if (isSelectPseudo(*SelectMBBI)) { 9608 // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ] 9609 BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(), 9610 TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg()) 9611 .addReg(SelectMBBI->getOperand(4).getReg()) 9612 .addMBB(HeadMBB) 9613 .addReg(SelectMBBI->getOperand(5).getReg()) 9614 .addMBB(IfFalseMBB); 9615 SelectMBBI->eraseFromParent(); 9616 } 9617 SelectMBBI = Next; 9618 } 9619 9620 F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs); 9621 return TailMBB; 9622 } 9623 9624 MachineBasicBlock * 9625 RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 9626 MachineBasicBlock *BB) const { 9627 switch (MI.getOpcode()) { 9628 default: 9629 llvm_unreachable("Unexpected instr type to insert"); 9630 case RISCV::ReadCycleWide: 9631 assert(!Subtarget.is64Bit() && 9632 "ReadCycleWrite is only to be used on riscv32"); 9633 return emitReadCycleWidePseudo(MI, BB); 9634 case RISCV::Select_GPR_Using_CC_GPR: 9635 case RISCV::Select_FPR16_Using_CC_GPR: 9636 case RISCV::Select_FPR32_Using_CC_GPR: 9637 case RISCV::Select_FPR64_Using_CC_GPR: 9638 return emitSelectPseudo(MI, BB, Subtarget); 9639 case RISCV::BuildPairF64Pseudo: 9640 return emitBuildPairF64Pseudo(MI, BB); 9641 case RISCV::SplitF64Pseudo: 9642 return emitSplitF64Pseudo(MI, BB); 9643 case RISCV::PseudoQuietFLE_H: 9644 return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget); 9645 case RISCV::PseudoQuietFLT_H: 9646 return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget); 9647 case RISCV::PseudoQuietFLE_S: 9648 return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget); 9649 case RISCV::PseudoQuietFLT_S: 9650 return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget); 9651 case RISCV::PseudoQuietFLE_D: 9652 return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget); 9653 case RISCV::PseudoQuietFLT_D: 9654 return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget); 9655 } 9656 } 9657 9658 void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 9659 SDNode *Node) const { 9660 // Add FRM dependency to any instructions with dynamic rounding mode. 9661 unsigned Opc = MI.getOpcode(); 9662 auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm); 9663 if (Idx < 0) 9664 return; 9665 if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN) 9666 return; 9667 // If the instruction already reads FRM, don't add another read. 9668 if (MI.readsRegister(RISCV::FRM)) 9669 return; 9670 MI.addOperand( 9671 MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true)); 9672 } 9673 9674 // Calling Convention Implementation. 9675 // The expectations for frontend ABI lowering vary from target to target. 9676 // Ideally, an LLVM frontend would be able to avoid worrying about many ABI 9677 // details, but this is a longer term goal. For now, we simply try to keep the 9678 // role of the frontend as simple and well-defined as possible. The rules can 9679 // be summarised as: 9680 // * Never split up large scalar arguments. We handle them here. 9681 // * If a hardfloat calling convention is being used, and the struct may be 9682 // passed in a pair of registers (fp+fp, int+fp), and both registers are 9683 // available, then pass as two separate arguments. If either the GPRs or FPRs 9684 // are exhausted, then pass according to the rule below. 9685 // * If a struct could never be passed in registers or directly in a stack 9686 // slot (as it is larger than 2*XLEN and the floating point rules don't 9687 // apply), then pass it using a pointer with the byval attribute. 9688 // * If a struct is less than 2*XLEN, then coerce to either a two-element 9689 // word-sized array or a 2*XLEN scalar (depending on alignment). 9690 // * The frontend can determine whether a struct is returned by reference or 9691 // not based on its size and fields. If it will be returned by reference, the 9692 // frontend must modify the prototype so a pointer with the sret annotation is 9693 // passed as the first argument. This is not necessary for large scalar 9694 // returns. 9695 // * Struct return values and varargs should be coerced to structs containing 9696 // register-size fields in the same situations they would be for fixed 9697 // arguments. 9698 9699 static const MCPhysReg ArgGPRs[] = { 9700 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, 9701 RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17 9702 }; 9703 static const MCPhysReg ArgFPR16s[] = { 9704 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, 9705 RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H 9706 }; 9707 static const MCPhysReg ArgFPR32s[] = { 9708 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, 9709 RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F 9710 }; 9711 static const MCPhysReg ArgFPR64s[] = { 9712 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, 9713 RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D 9714 }; 9715 // This is an interim calling convention and it may be changed in the future. 9716 static const MCPhysReg ArgVRs[] = { 9717 RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13, 9718 RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19, 9719 RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23}; 9720 static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2, 9721 RISCV::V14M2, RISCV::V16M2, RISCV::V18M2, 9722 RISCV::V20M2, RISCV::V22M2}; 9723 static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4, 9724 RISCV::V20M4}; 9725 static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8}; 9726 9727 // Pass a 2*XLEN argument that has been split into two XLEN values through 9728 // registers or the stack as necessary. 9729 static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1, 9730 ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2, 9731 MVT ValVT2, MVT LocVT2, 9732 ISD::ArgFlagsTy ArgFlags2) { 9733 unsigned XLenInBytes = XLen / 8; 9734 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9735 // At least one half can be passed via register. 9736 State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg, 9737 VA1.getLocVT(), CCValAssign::Full)); 9738 } else { 9739 // Both halves must be passed on the stack, with proper alignment. 9740 Align StackAlign = 9741 std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign()); 9742 State.addLoc( 9743 CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(), 9744 State.AllocateStack(XLenInBytes, StackAlign), 9745 VA1.getLocVT(), CCValAssign::Full)); 9746 State.addLoc(CCValAssign::getMem( 9747 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9748 LocVT2, CCValAssign::Full)); 9749 return false; 9750 } 9751 9752 if (Register Reg = State.AllocateReg(ArgGPRs)) { 9753 // The second half can also be passed via register. 9754 State.addLoc( 9755 CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full)); 9756 } else { 9757 // The second half is passed via the stack, without additional alignment. 9758 State.addLoc(CCValAssign::getMem( 9759 ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)), 9760 LocVT2, CCValAssign::Full)); 9761 } 9762 9763 return false; 9764 } 9765 9766 static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo, 9767 Optional<unsigned> FirstMaskArgument, 9768 CCState &State, const RISCVTargetLowering &TLI) { 9769 const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT); 9770 if (RC == &RISCV::VRRegClass) { 9771 // Assign the first mask argument to V0. 9772 // This is an interim calling convention and it may be changed in the 9773 // future. 9774 if (FirstMaskArgument.hasValue() && ValNo == FirstMaskArgument.getValue()) 9775 return State.AllocateReg(RISCV::V0); 9776 return State.AllocateReg(ArgVRs); 9777 } 9778 if (RC == &RISCV::VRM2RegClass) 9779 return State.AllocateReg(ArgVRM2s); 9780 if (RC == &RISCV::VRM4RegClass) 9781 return State.AllocateReg(ArgVRM4s); 9782 if (RC == &RISCV::VRM8RegClass) 9783 return State.AllocateReg(ArgVRM8s); 9784 llvm_unreachable("Unhandled register class for ValueType"); 9785 } 9786 9787 // Implements the RISC-V calling convention. Returns true upon failure. 9788 static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo, 9789 MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo, 9790 ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed, 9791 bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI, 9792 Optional<unsigned> FirstMaskArgument) { 9793 unsigned XLen = DL.getLargestLegalIntTypeSizeInBits(); 9794 assert(XLen == 32 || XLen == 64); 9795 MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64; 9796 9797 // Any return value split in to more than two values can't be returned 9798 // directly. Vectors are returned via the available vector registers. 9799 if (!LocVT.isVector() && IsRet && ValNo > 1) 9800 return true; 9801 9802 // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a 9803 // variadic argument, or if no F16/F32 argument registers are available. 9804 bool UseGPRForF16_F32 = true; 9805 // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a 9806 // variadic argument, or if no F64 argument registers are available. 9807 bool UseGPRForF64 = true; 9808 9809 switch (ABI) { 9810 default: 9811 llvm_unreachable("Unexpected ABI"); 9812 case RISCVABI::ABI_ILP32: 9813 case RISCVABI::ABI_LP64: 9814 break; 9815 case RISCVABI::ABI_ILP32F: 9816 case RISCVABI::ABI_LP64F: 9817 UseGPRForF16_F32 = !IsFixed; 9818 break; 9819 case RISCVABI::ABI_ILP32D: 9820 case RISCVABI::ABI_LP64D: 9821 UseGPRForF16_F32 = !IsFixed; 9822 UseGPRForF64 = !IsFixed; 9823 break; 9824 } 9825 9826 // FPR16, FPR32, and FPR64 alias each other. 9827 if (State.getFirstUnallocated(ArgFPR32s) == array_lengthof(ArgFPR32s)) { 9828 UseGPRForF16_F32 = true; 9829 UseGPRForF64 = true; 9830 } 9831 9832 // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and 9833 // similar local variables rather than directly checking against the target 9834 // ABI. 9835 9836 if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) { 9837 LocVT = XLenVT; 9838 LocInfo = CCValAssign::BCvt; 9839 } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) { 9840 LocVT = MVT::i64; 9841 LocInfo = CCValAssign::BCvt; 9842 } 9843 9844 // If this is a variadic argument, the RISC-V calling convention requires 9845 // that it is assigned an 'even' or 'aligned' register if it has 8-byte 9846 // alignment (RV32) or 16-byte alignment (RV64). An aligned register should 9847 // be used regardless of whether the original argument was split during 9848 // legalisation or not. The argument will not be passed by registers if the 9849 // original type is larger than 2*XLEN, so the register alignment rule does 9850 // not apply. 9851 unsigned TwoXLenInBytes = (2 * XLen) / 8; 9852 if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes && 9853 DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) { 9854 unsigned RegIdx = State.getFirstUnallocated(ArgGPRs); 9855 // Skip 'odd' register if necessary. 9856 if (RegIdx != array_lengthof(ArgGPRs) && RegIdx % 2 == 1) 9857 State.AllocateReg(ArgGPRs); 9858 } 9859 9860 SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs(); 9861 SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags = 9862 State.getPendingArgFlags(); 9863 9864 assert(PendingLocs.size() == PendingArgFlags.size() && 9865 "PendingLocs and PendingArgFlags out of sync"); 9866 9867 // Handle passing f64 on RV32D with a soft float ABI or when floating point 9868 // registers are exhausted. 9869 if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) { 9870 assert(!ArgFlags.isSplit() && PendingLocs.empty() && 9871 "Can't lower f64 if it is split"); 9872 // Depending on available argument GPRS, f64 may be passed in a pair of 9873 // GPRs, split between a GPR and the stack, or passed completely on the 9874 // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these 9875 // cases. 9876 Register Reg = State.AllocateReg(ArgGPRs); 9877 LocVT = MVT::i32; 9878 if (!Reg) { 9879 unsigned StackOffset = State.AllocateStack(8, Align(8)); 9880 State.addLoc( 9881 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 9882 return false; 9883 } 9884 if (!State.AllocateReg(ArgGPRs)) 9885 State.AllocateStack(4, Align(4)); 9886 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9887 return false; 9888 } 9889 9890 // Fixed-length vectors are located in the corresponding scalable-vector 9891 // container types. 9892 if (ValVT.isFixedLengthVector()) 9893 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 9894 9895 // Split arguments might be passed indirectly, so keep track of the pending 9896 // values. Split vectors are passed via a mix of registers and indirectly, so 9897 // treat them as we would any other argument. 9898 if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) { 9899 LocVT = XLenVT; 9900 LocInfo = CCValAssign::Indirect; 9901 PendingLocs.push_back( 9902 CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo)); 9903 PendingArgFlags.push_back(ArgFlags); 9904 if (!ArgFlags.isSplitEnd()) { 9905 return false; 9906 } 9907 } 9908 9909 // If the split argument only had two elements, it should be passed directly 9910 // in registers or on the stack. 9911 if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() && 9912 PendingLocs.size() <= 2) { 9913 assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()"); 9914 // Apply the normal calling convention rules to the first half of the 9915 // split argument. 9916 CCValAssign VA = PendingLocs[0]; 9917 ISD::ArgFlagsTy AF = PendingArgFlags[0]; 9918 PendingLocs.clear(); 9919 PendingArgFlags.clear(); 9920 return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT, 9921 ArgFlags); 9922 } 9923 9924 // Allocate to a register if possible, or else a stack slot. 9925 Register Reg; 9926 unsigned StoreSizeBytes = XLen / 8; 9927 Align StackAlign = Align(XLen / 8); 9928 9929 if (ValVT == MVT::f16 && !UseGPRForF16_F32) 9930 Reg = State.AllocateReg(ArgFPR16s); 9931 else if (ValVT == MVT::f32 && !UseGPRForF16_F32) 9932 Reg = State.AllocateReg(ArgFPR32s); 9933 else if (ValVT == MVT::f64 && !UseGPRForF64) 9934 Reg = State.AllocateReg(ArgFPR64s); 9935 else if (ValVT.isVector()) { 9936 Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI); 9937 if (!Reg) { 9938 // For return values, the vector must be passed fully via registers or 9939 // via the stack. 9940 // FIXME: The proposed vector ABI only mandates v8-v15 for return values, 9941 // but we're using all of them. 9942 if (IsRet) 9943 return true; 9944 // Try using a GPR to pass the address 9945 if ((Reg = State.AllocateReg(ArgGPRs))) { 9946 LocVT = XLenVT; 9947 LocInfo = CCValAssign::Indirect; 9948 } else if (ValVT.isScalableVector()) { 9949 LocVT = XLenVT; 9950 LocInfo = CCValAssign::Indirect; 9951 } else { 9952 // Pass fixed-length vectors on the stack. 9953 LocVT = ValVT; 9954 StoreSizeBytes = ValVT.getStoreSize(); 9955 // Align vectors to their element sizes, being careful for vXi1 9956 // vectors. 9957 StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 9958 } 9959 } 9960 } else { 9961 Reg = State.AllocateReg(ArgGPRs); 9962 } 9963 9964 unsigned StackOffset = 9965 Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign); 9966 9967 // If we reach this point and PendingLocs is non-empty, we must be at the 9968 // end of a split argument that must be passed indirectly. 9969 if (!PendingLocs.empty()) { 9970 assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()"); 9971 assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()"); 9972 9973 for (auto &It : PendingLocs) { 9974 if (Reg) 9975 It.convertToReg(Reg); 9976 else 9977 It.convertToMem(StackOffset); 9978 State.addLoc(It); 9979 } 9980 PendingLocs.clear(); 9981 PendingArgFlags.clear(); 9982 return false; 9983 } 9984 9985 assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT || 9986 (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) && 9987 "Expected an XLenVT or vector types at this stage"); 9988 9989 if (Reg) { 9990 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 9991 return false; 9992 } 9993 9994 // When a floating-point value is passed on the stack, no bit-conversion is 9995 // needed. 9996 if (ValVT.isFloatingPoint()) { 9997 LocVT = ValVT; 9998 LocInfo = CCValAssign::Full; 9999 } 10000 State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10001 return false; 10002 } 10003 10004 template <typename ArgTy> 10005 static Optional<unsigned> preAssignMask(const ArgTy &Args) { 10006 for (const auto &ArgIdx : enumerate(Args)) { 10007 MVT ArgVT = ArgIdx.value().VT; 10008 if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1) 10009 return ArgIdx.index(); 10010 } 10011 return None; 10012 } 10013 10014 void RISCVTargetLowering::analyzeInputArgs( 10015 MachineFunction &MF, CCState &CCInfo, 10016 const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet, 10017 RISCVCCAssignFn Fn) const { 10018 unsigned NumArgs = Ins.size(); 10019 FunctionType *FType = MF.getFunction().getFunctionType(); 10020 10021 Optional<unsigned> FirstMaskArgument; 10022 if (Subtarget.hasVInstructions()) 10023 FirstMaskArgument = preAssignMask(Ins); 10024 10025 for (unsigned i = 0; i != NumArgs; ++i) { 10026 MVT ArgVT = Ins[i].VT; 10027 ISD::ArgFlagsTy ArgFlags = Ins[i].Flags; 10028 10029 Type *ArgTy = nullptr; 10030 if (IsRet) 10031 ArgTy = FType->getReturnType(); 10032 else if (Ins[i].isOrigArg()) 10033 ArgTy = FType->getParamType(Ins[i].getOrigArgIndex()); 10034 10035 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10036 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10037 ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this, 10038 FirstMaskArgument)) { 10039 LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type " 10040 << EVT(ArgVT).getEVTString() << '\n'); 10041 llvm_unreachable(nullptr); 10042 } 10043 } 10044 } 10045 10046 void RISCVTargetLowering::analyzeOutputArgs( 10047 MachineFunction &MF, CCState &CCInfo, 10048 const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet, 10049 CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const { 10050 unsigned NumArgs = Outs.size(); 10051 10052 Optional<unsigned> FirstMaskArgument; 10053 if (Subtarget.hasVInstructions()) 10054 FirstMaskArgument = preAssignMask(Outs); 10055 10056 for (unsigned i = 0; i != NumArgs; i++) { 10057 MVT ArgVT = Outs[i].VT; 10058 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10059 Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr; 10060 10061 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10062 if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full, 10063 ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this, 10064 FirstMaskArgument)) { 10065 LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type " 10066 << EVT(ArgVT).getEVTString() << "\n"); 10067 llvm_unreachable(nullptr); 10068 } 10069 } 10070 } 10071 10072 // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect 10073 // values. 10074 static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val, 10075 const CCValAssign &VA, const SDLoc &DL, 10076 const RISCVSubtarget &Subtarget) { 10077 switch (VA.getLocInfo()) { 10078 default: 10079 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10080 case CCValAssign::Full: 10081 if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector()) 10082 Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget); 10083 break; 10084 case CCValAssign::BCvt: 10085 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10086 Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val); 10087 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10088 Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val); 10089 else 10090 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val); 10091 break; 10092 } 10093 return Val; 10094 } 10095 10096 // The caller is responsible for loading the full value if the argument is 10097 // passed with CCValAssign::Indirect. 10098 static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain, 10099 const CCValAssign &VA, const SDLoc &DL, 10100 const RISCVTargetLowering &TLI) { 10101 MachineFunction &MF = DAG.getMachineFunction(); 10102 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10103 EVT LocVT = VA.getLocVT(); 10104 SDValue Val; 10105 const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT()); 10106 Register VReg = RegInfo.createVirtualRegister(RC); 10107 RegInfo.addLiveIn(VA.getLocReg(), VReg); 10108 Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT); 10109 10110 if (VA.getLocInfo() == CCValAssign::Indirect) 10111 return Val; 10112 10113 return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget()); 10114 } 10115 10116 static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val, 10117 const CCValAssign &VA, const SDLoc &DL, 10118 const RISCVSubtarget &Subtarget) { 10119 EVT LocVT = VA.getLocVT(); 10120 10121 switch (VA.getLocInfo()) { 10122 default: 10123 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10124 case CCValAssign::Full: 10125 if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector()) 10126 Val = convertToScalableVector(LocVT, Val, DAG, Subtarget); 10127 break; 10128 case CCValAssign::BCvt: 10129 if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16) 10130 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val); 10131 else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32) 10132 Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val); 10133 else 10134 Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val); 10135 break; 10136 } 10137 return Val; 10138 } 10139 10140 // The caller is responsible for loading the full value if the argument is 10141 // passed with CCValAssign::Indirect. 10142 static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain, 10143 const CCValAssign &VA, const SDLoc &DL) { 10144 MachineFunction &MF = DAG.getMachineFunction(); 10145 MachineFrameInfo &MFI = MF.getFrameInfo(); 10146 EVT LocVT = VA.getLocVT(); 10147 EVT ValVT = VA.getValVT(); 10148 EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0)); 10149 if (ValVT.isScalableVector()) { 10150 // When the value is a scalable vector, we save the pointer which points to 10151 // the scalable vector value in the stack. The ValVT will be the pointer 10152 // type, instead of the scalable vector type. 10153 ValVT = LocVT; 10154 } 10155 int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(), 10156 /*IsImmutable=*/true); 10157 SDValue FIN = DAG.getFrameIndex(FI, PtrVT); 10158 SDValue Val; 10159 10160 ISD::LoadExtType ExtType; 10161 switch (VA.getLocInfo()) { 10162 default: 10163 llvm_unreachable("Unexpected CCValAssign::LocInfo"); 10164 case CCValAssign::Full: 10165 case CCValAssign::Indirect: 10166 case CCValAssign::BCvt: 10167 ExtType = ISD::NON_EXTLOAD; 10168 break; 10169 } 10170 Val = DAG.getExtLoad( 10171 ExtType, DL, LocVT, Chain, FIN, 10172 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT); 10173 return Val; 10174 } 10175 10176 static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain, 10177 const CCValAssign &VA, const SDLoc &DL) { 10178 assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 && 10179 "Unexpected VA"); 10180 MachineFunction &MF = DAG.getMachineFunction(); 10181 MachineFrameInfo &MFI = MF.getFrameInfo(); 10182 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10183 10184 if (VA.isMemLoc()) { 10185 // f64 is passed on the stack. 10186 int FI = 10187 MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true); 10188 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10189 return DAG.getLoad(MVT::f64, DL, Chain, FIN, 10190 MachinePointerInfo::getFixedStack(MF, FI)); 10191 } 10192 10193 assert(VA.isRegLoc() && "Expected register VA assignment"); 10194 10195 Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10196 RegInfo.addLiveIn(VA.getLocReg(), LoVReg); 10197 SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32); 10198 SDValue Hi; 10199 if (VA.getLocReg() == RISCV::X17) { 10200 // Second half of f64 is passed on the stack. 10201 int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true); 10202 SDValue FIN = DAG.getFrameIndex(FI, MVT::i32); 10203 Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN, 10204 MachinePointerInfo::getFixedStack(MF, FI)); 10205 } else { 10206 // Second half of f64 is passed in another GPR. 10207 Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass); 10208 RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg); 10209 Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32); 10210 } 10211 return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi); 10212 } 10213 10214 // FastCC has less than 1% performance improvement for some particular 10215 // benchmark. But theoretically, it may has benenfit for some cases. 10216 static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI, 10217 unsigned ValNo, MVT ValVT, MVT LocVT, 10218 CCValAssign::LocInfo LocInfo, 10219 ISD::ArgFlagsTy ArgFlags, CCState &State, 10220 bool IsFixed, bool IsRet, Type *OrigTy, 10221 const RISCVTargetLowering &TLI, 10222 Optional<unsigned> FirstMaskArgument) { 10223 10224 // X5 and X6 might be used for save-restore libcall. 10225 static const MCPhysReg GPRList[] = { 10226 RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14, 10227 RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28, 10228 RISCV::X29, RISCV::X30, RISCV::X31}; 10229 10230 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10231 if (unsigned Reg = State.AllocateReg(GPRList)) { 10232 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10233 return false; 10234 } 10235 } 10236 10237 if (LocVT == MVT::f16) { 10238 static const MCPhysReg FPR16List[] = { 10239 RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H, 10240 RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H, 10241 RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H, 10242 RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H}; 10243 if (unsigned Reg = State.AllocateReg(FPR16List)) { 10244 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10245 return false; 10246 } 10247 } 10248 10249 if (LocVT == MVT::f32) { 10250 static const MCPhysReg FPR32List[] = { 10251 RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F, 10252 RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F, 10253 RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F, 10254 RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F}; 10255 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10256 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10257 return false; 10258 } 10259 } 10260 10261 if (LocVT == MVT::f64) { 10262 static const MCPhysReg FPR64List[] = { 10263 RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D, 10264 RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D, 10265 RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D, 10266 RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D}; 10267 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10268 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10269 return false; 10270 } 10271 } 10272 10273 if (LocVT == MVT::i32 || LocVT == MVT::f32) { 10274 unsigned Offset4 = State.AllocateStack(4, Align(4)); 10275 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo)); 10276 return false; 10277 } 10278 10279 if (LocVT == MVT::i64 || LocVT == MVT::f64) { 10280 unsigned Offset5 = State.AllocateStack(8, Align(8)); 10281 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo)); 10282 return false; 10283 } 10284 10285 if (LocVT.isVector()) { 10286 if (unsigned Reg = 10287 allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) { 10288 // Fixed-length vectors are located in the corresponding scalable-vector 10289 // container types. 10290 if (ValVT.isFixedLengthVector()) 10291 LocVT = TLI.getContainerForFixedLengthVector(LocVT); 10292 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10293 } else { 10294 // Try and pass the address via a "fast" GPR. 10295 if (unsigned GPRReg = State.AllocateReg(GPRList)) { 10296 LocInfo = CCValAssign::Indirect; 10297 LocVT = TLI.getSubtarget().getXLenVT(); 10298 State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo)); 10299 } else if (ValVT.isFixedLengthVector()) { 10300 auto StackAlign = 10301 MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne(); 10302 unsigned StackOffset = 10303 State.AllocateStack(ValVT.getStoreSize(), StackAlign); 10304 State.addLoc( 10305 CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo)); 10306 } else { 10307 // Can't pass scalable vectors on the stack. 10308 return true; 10309 } 10310 } 10311 10312 return false; 10313 } 10314 10315 return true; // CC didn't match. 10316 } 10317 10318 static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT, 10319 CCValAssign::LocInfo LocInfo, 10320 ISD::ArgFlagsTy ArgFlags, CCState &State) { 10321 10322 if (LocVT == MVT::i32 || LocVT == MVT::i64) { 10323 // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim 10324 // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 10325 static const MCPhysReg GPRList[] = { 10326 RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22, 10327 RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27}; 10328 if (unsigned Reg = State.AllocateReg(GPRList)) { 10329 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10330 return false; 10331 } 10332 } 10333 10334 if (LocVT == MVT::f32) { 10335 // Pass in STG registers: F1, ..., F6 10336 // fs0 ... fs5 10337 static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F, 10338 RISCV::F18_F, RISCV::F19_F, 10339 RISCV::F20_F, RISCV::F21_F}; 10340 if (unsigned Reg = State.AllocateReg(FPR32List)) { 10341 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10342 return false; 10343 } 10344 } 10345 10346 if (LocVT == MVT::f64) { 10347 // Pass in STG registers: D1, ..., D6 10348 // fs6 ... fs11 10349 static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D, 10350 RISCV::F24_D, RISCV::F25_D, 10351 RISCV::F26_D, RISCV::F27_D}; 10352 if (unsigned Reg = State.AllocateReg(FPR64List)) { 10353 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo)); 10354 return false; 10355 } 10356 } 10357 10358 report_fatal_error("No registers left in GHC calling convention"); 10359 return true; 10360 } 10361 10362 // Transform physical registers into virtual registers. 10363 SDValue RISCVTargetLowering::LowerFormalArguments( 10364 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg, 10365 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL, 10366 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const { 10367 10368 MachineFunction &MF = DAG.getMachineFunction(); 10369 10370 switch (CallConv) { 10371 default: 10372 report_fatal_error("Unsupported calling convention"); 10373 case CallingConv::C: 10374 case CallingConv::Fast: 10375 break; 10376 case CallingConv::GHC: 10377 if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] || 10378 !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD]) 10379 report_fatal_error( 10380 "GHC calling convention requires the F and D instruction set extensions"); 10381 } 10382 10383 const Function &Func = MF.getFunction(); 10384 if (Func.hasFnAttribute("interrupt")) { 10385 if (!Func.arg_empty()) 10386 report_fatal_error( 10387 "Functions with the interrupt attribute cannot have arguments!"); 10388 10389 StringRef Kind = 10390 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 10391 10392 if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine")) 10393 report_fatal_error( 10394 "Function interrupt attribute argument not supported!"); 10395 } 10396 10397 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10398 MVT XLenVT = Subtarget.getXLenVT(); 10399 unsigned XLenInBytes = Subtarget.getXLen() / 8; 10400 // Used with vargs to acumulate store chains. 10401 std::vector<SDValue> OutChains; 10402 10403 // Assign locations to all of the incoming arguments. 10404 SmallVector<CCValAssign, 16> ArgLocs; 10405 CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10406 10407 if (CallConv == CallingConv::GHC) 10408 CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC); 10409 else 10410 analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false, 10411 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10412 : CC_RISCV); 10413 10414 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) { 10415 CCValAssign &VA = ArgLocs[i]; 10416 SDValue ArgValue; 10417 // Passing f64 on RV32D with a soft float ABI must be handled as a special 10418 // case. 10419 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) 10420 ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL); 10421 else if (VA.isRegLoc()) 10422 ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, *this); 10423 else 10424 ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL); 10425 10426 if (VA.getLocInfo() == CCValAssign::Indirect) { 10427 // If the original argument was split and passed by reference (e.g. i128 10428 // on RV32), we need to load all parts of it here (using the same 10429 // address). Vectors may be partly split to registers and partly to the 10430 // stack, in which case the base address is partly offset and subsequent 10431 // stores are relative to that. 10432 InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue, 10433 MachinePointerInfo())); 10434 unsigned ArgIndex = Ins[i].OrigArgIndex; 10435 unsigned ArgPartOffset = Ins[i].PartOffset; 10436 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10437 while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) { 10438 CCValAssign &PartVA = ArgLocs[i + 1]; 10439 unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset; 10440 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10441 if (PartVA.getValVT().isScalableVector()) 10442 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10443 SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset); 10444 InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address, 10445 MachinePointerInfo())); 10446 ++i; 10447 } 10448 continue; 10449 } 10450 InVals.push_back(ArgValue); 10451 } 10452 10453 if (IsVarArg) { 10454 ArrayRef<MCPhysReg> ArgRegs = makeArrayRef(ArgGPRs); 10455 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs); 10456 const TargetRegisterClass *RC = &RISCV::GPRRegClass; 10457 MachineFrameInfo &MFI = MF.getFrameInfo(); 10458 MachineRegisterInfo &RegInfo = MF.getRegInfo(); 10459 RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>(); 10460 10461 // Offset of the first variable argument from stack pointer, and size of 10462 // the vararg save area. For now, the varargs save area is either zero or 10463 // large enough to hold a0-a7. 10464 int VaArgOffset, VarArgsSaveSize; 10465 10466 // If all registers are allocated, then all varargs must be passed on the 10467 // stack and we don't need to save any argregs. 10468 if (ArgRegs.size() == Idx) { 10469 VaArgOffset = CCInfo.getNextStackOffset(); 10470 VarArgsSaveSize = 0; 10471 } else { 10472 VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx); 10473 VaArgOffset = -VarArgsSaveSize; 10474 } 10475 10476 // Record the frame index of the first variable argument 10477 // which is a value necessary to VASTART. 10478 int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10479 RVFI->setVarArgsFrameIndex(FI); 10480 10481 // If saving an odd number of registers then create an extra stack slot to 10482 // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures 10483 // offsets to even-numbered registered remain 2*XLEN-aligned. 10484 if (Idx % 2) { 10485 MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true); 10486 VarArgsSaveSize += XLenInBytes; 10487 } 10488 10489 // Copy the integer registers that may have been used for passing varargs 10490 // to the vararg save area. 10491 for (unsigned I = Idx; I < ArgRegs.size(); 10492 ++I, VaArgOffset += XLenInBytes) { 10493 const Register Reg = RegInfo.createVirtualRegister(RC); 10494 RegInfo.addLiveIn(ArgRegs[I], Reg); 10495 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT); 10496 FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true); 10497 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10498 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff, 10499 MachinePointerInfo::getFixedStack(MF, FI)); 10500 cast<StoreSDNode>(Store.getNode()) 10501 ->getMemOperand() 10502 ->setValue((Value *)nullptr); 10503 OutChains.push_back(Store); 10504 } 10505 RVFI->setVarArgsSaveSize(VarArgsSaveSize); 10506 } 10507 10508 // All stores are grouped in one node to allow the matching between 10509 // the size of Ins and InVals. This only happens for vararg functions. 10510 if (!OutChains.empty()) { 10511 OutChains.push_back(Chain); 10512 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains); 10513 } 10514 10515 return Chain; 10516 } 10517 10518 /// isEligibleForTailCallOptimization - Check whether the call is eligible 10519 /// for tail call optimization. 10520 /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization. 10521 bool RISCVTargetLowering::isEligibleForTailCallOptimization( 10522 CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF, 10523 const SmallVector<CCValAssign, 16> &ArgLocs) const { 10524 10525 auto &Callee = CLI.Callee; 10526 auto CalleeCC = CLI.CallConv; 10527 auto &Outs = CLI.Outs; 10528 auto &Caller = MF.getFunction(); 10529 auto CallerCC = Caller.getCallingConv(); 10530 10531 // Exception-handling functions need a special set of instructions to 10532 // indicate a return to the hardware. Tail-calling another function would 10533 // probably break this. 10534 // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This 10535 // should be expanded as new function attributes are introduced. 10536 if (Caller.hasFnAttribute("interrupt")) 10537 return false; 10538 10539 // Do not tail call opt if the stack is used to pass parameters. 10540 if (CCInfo.getNextStackOffset() != 0) 10541 return false; 10542 10543 // Do not tail call opt if any parameters need to be passed indirectly. 10544 // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are 10545 // passed indirectly. So the address of the value will be passed in a 10546 // register, or if not available, then the address is put on the stack. In 10547 // order to pass indirectly, space on the stack often needs to be allocated 10548 // in order to store the value. In this case the CCInfo.getNextStackOffset() 10549 // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs 10550 // are passed CCValAssign::Indirect. 10551 for (auto &VA : ArgLocs) 10552 if (VA.getLocInfo() == CCValAssign::Indirect) 10553 return false; 10554 10555 // Do not tail call opt if either caller or callee uses struct return 10556 // semantics. 10557 auto IsCallerStructRet = Caller.hasStructRetAttr(); 10558 auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet(); 10559 if (IsCallerStructRet || IsCalleeStructRet) 10560 return false; 10561 10562 // Externally-defined functions with weak linkage should not be 10563 // tail-called. The behaviour of branch instructions in this situation (as 10564 // used for tail calls) is implementation-defined, so we cannot rely on the 10565 // linker replacing the tail call with a return. 10566 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) { 10567 const GlobalValue *GV = G->getGlobal(); 10568 if (GV->hasExternalWeakLinkage()) 10569 return false; 10570 } 10571 10572 // The callee has to preserve all registers the caller needs to preserve. 10573 const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10574 const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC); 10575 if (CalleeCC != CallerCC) { 10576 const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC); 10577 if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved)) 10578 return false; 10579 } 10580 10581 // Byval parameters hand the function a pointer directly into the stack area 10582 // we want to reuse during a tail call. Working around this *is* possible 10583 // but less efficient and uglier in LowerCall. 10584 for (auto &Arg : Outs) 10585 if (Arg.Flags.isByVal()) 10586 return false; 10587 10588 return true; 10589 } 10590 10591 static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) { 10592 return DAG.getDataLayout().getPrefTypeAlign( 10593 VT.getTypeForEVT(*DAG.getContext())); 10594 } 10595 10596 // Lower a call to a callseq_start + CALL + callseq_end chain, and add input 10597 // and output parameter nodes. 10598 SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI, 10599 SmallVectorImpl<SDValue> &InVals) const { 10600 SelectionDAG &DAG = CLI.DAG; 10601 SDLoc &DL = CLI.DL; 10602 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs; 10603 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals; 10604 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins; 10605 SDValue Chain = CLI.Chain; 10606 SDValue Callee = CLI.Callee; 10607 bool &IsTailCall = CLI.IsTailCall; 10608 CallingConv::ID CallConv = CLI.CallConv; 10609 bool IsVarArg = CLI.IsVarArg; 10610 EVT PtrVT = getPointerTy(DAG.getDataLayout()); 10611 MVT XLenVT = Subtarget.getXLenVT(); 10612 10613 MachineFunction &MF = DAG.getMachineFunction(); 10614 10615 // Analyze the operands of the call, assigning locations to each operand. 10616 SmallVector<CCValAssign, 16> ArgLocs; 10617 CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext()); 10618 10619 if (CallConv == CallingConv::GHC) 10620 ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC); 10621 else 10622 analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI, 10623 CallConv == CallingConv::Fast ? CC_RISCV_FastCC 10624 : CC_RISCV); 10625 10626 // Check if it's really possible to do a tail call. 10627 if (IsTailCall) 10628 IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs); 10629 10630 if (IsTailCall) 10631 ++NumTailCalls; 10632 else if (CLI.CB && CLI.CB->isMustTailCall()) 10633 report_fatal_error("failed to perform tail call elimination on a call " 10634 "site marked musttail"); 10635 10636 // Get a count of how many bytes are to be pushed on the stack. 10637 unsigned NumBytes = ArgCCInfo.getNextStackOffset(); 10638 10639 // Create local copies for byval args 10640 SmallVector<SDValue, 8> ByValArgs; 10641 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10642 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10643 if (!Flags.isByVal()) 10644 continue; 10645 10646 SDValue Arg = OutVals[i]; 10647 unsigned Size = Flags.getByValSize(); 10648 Align Alignment = Flags.getNonZeroByValAlign(); 10649 10650 int FI = 10651 MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false); 10652 SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout())); 10653 SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT); 10654 10655 Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment, 10656 /*IsVolatile=*/false, 10657 /*AlwaysInline=*/false, IsTailCall, 10658 MachinePointerInfo(), MachinePointerInfo()); 10659 ByValArgs.push_back(FIPtr); 10660 } 10661 10662 if (!IsTailCall) 10663 Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL); 10664 10665 // Copy argument values to their designated locations. 10666 SmallVector<std::pair<Register, SDValue>, 8> RegsToPass; 10667 SmallVector<SDValue, 8> MemOpChains; 10668 SDValue StackPtr; 10669 for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) { 10670 CCValAssign &VA = ArgLocs[i]; 10671 SDValue ArgValue = OutVals[i]; 10672 ISD::ArgFlagsTy Flags = Outs[i].Flags; 10673 10674 // Handle passing f64 on RV32D with a soft float ABI as a special case. 10675 bool IsF64OnRV32DSoftABI = 10676 VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64; 10677 if (IsF64OnRV32DSoftABI && VA.isRegLoc()) { 10678 SDValue SplitF64 = DAG.getNode( 10679 RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue); 10680 SDValue Lo = SplitF64.getValue(0); 10681 SDValue Hi = SplitF64.getValue(1); 10682 10683 Register RegLo = VA.getLocReg(); 10684 RegsToPass.push_back(std::make_pair(RegLo, Lo)); 10685 10686 if (RegLo == RISCV::X17) { 10687 // Second half of f64 is passed on the stack. 10688 // Work out the address of the stack slot. 10689 if (!StackPtr.getNode()) 10690 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10691 // Emit the store. 10692 MemOpChains.push_back( 10693 DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo())); 10694 } else { 10695 // Second half of f64 is passed in another GPR. 10696 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10697 Register RegHigh = RegLo + 1; 10698 RegsToPass.push_back(std::make_pair(RegHigh, Hi)); 10699 } 10700 continue; 10701 } 10702 10703 // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way 10704 // as any other MemLoc. 10705 10706 // Promote the value if needed. 10707 // For now, only handle fully promoted and indirect arguments. 10708 if (VA.getLocInfo() == CCValAssign::Indirect) { 10709 // Store the argument in a stack slot and pass its address. 10710 Align StackAlign = 10711 std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG), 10712 getPrefTypeAlign(ArgValue.getValueType(), DAG)); 10713 TypeSize StoredSize = ArgValue.getValueType().getStoreSize(); 10714 // If the original argument was split (e.g. i128), we need 10715 // to store the required parts of it here (and pass just one address). 10716 // Vectors may be partly split to registers and partly to the stack, in 10717 // which case the base address is partly offset and subsequent stores are 10718 // relative to that. 10719 unsigned ArgIndex = Outs[i].OrigArgIndex; 10720 unsigned ArgPartOffset = Outs[i].PartOffset; 10721 assert(VA.getValVT().isVector() || ArgPartOffset == 0); 10722 // Calculate the total size to store. We don't have access to what we're 10723 // actually storing other than performing the loop and collecting the 10724 // info. 10725 SmallVector<std::pair<SDValue, SDValue>> Parts; 10726 while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) { 10727 SDValue PartValue = OutVals[i + 1]; 10728 unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset; 10729 SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL); 10730 EVT PartVT = PartValue.getValueType(); 10731 if (PartVT.isScalableVector()) 10732 Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset); 10733 StoredSize += PartVT.getStoreSize(); 10734 StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG)); 10735 Parts.push_back(std::make_pair(PartValue, Offset)); 10736 ++i; 10737 } 10738 SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign); 10739 int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex(); 10740 MemOpChains.push_back( 10741 DAG.getStore(Chain, DL, ArgValue, SpillSlot, 10742 MachinePointerInfo::getFixedStack(MF, FI))); 10743 for (const auto &Part : Parts) { 10744 SDValue PartValue = Part.first; 10745 SDValue PartOffset = Part.second; 10746 SDValue Address = 10747 DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset); 10748 MemOpChains.push_back( 10749 DAG.getStore(Chain, DL, PartValue, Address, 10750 MachinePointerInfo::getFixedStack(MF, FI))); 10751 } 10752 ArgValue = SpillSlot; 10753 } else { 10754 ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget); 10755 } 10756 10757 // Use local copy if it is a byval arg. 10758 if (Flags.isByVal()) 10759 ArgValue = ByValArgs[j++]; 10760 10761 if (VA.isRegLoc()) { 10762 // Queue up the argument copies and emit them at the end. 10763 RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue)); 10764 } else { 10765 assert(VA.isMemLoc() && "Argument not register or memory"); 10766 assert(!IsTailCall && "Tail call not allowed if stack is used " 10767 "for passing parameters"); 10768 10769 // Work out the address of the stack slot. 10770 if (!StackPtr.getNode()) 10771 StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT); 10772 SDValue Address = 10773 DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, 10774 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL)); 10775 10776 // Emit the store. 10777 MemOpChains.push_back( 10778 DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo())); 10779 } 10780 } 10781 10782 // Join the stores, which are independent of one another. 10783 if (!MemOpChains.empty()) 10784 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains); 10785 10786 SDValue Glue; 10787 10788 // Build a sequence of copy-to-reg nodes, chained and glued together. 10789 for (auto &Reg : RegsToPass) { 10790 Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue); 10791 Glue = Chain.getValue(1); 10792 } 10793 10794 // Validate that none of the argument registers have been marked as 10795 // reserved, if so report an error. Do the same for the return address if this 10796 // is not a tailcall. 10797 validateCCReservedRegs(RegsToPass, MF); 10798 if (!IsTailCall && 10799 MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1)) 10800 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10801 MF.getFunction(), 10802 "Return address register required, but has been reserved."}); 10803 10804 // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a 10805 // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't 10806 // split it and then direct call can be matched by PseudoCALL. 10807 if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) { 10808 const GlobalValue *GV = S->getGlobal(); 10809 10810 unsigned OpFlags = RISCVII::MO_CALL; 10811 if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV)) 10812 OpFlags = RISCVII::MO_PLT; 10813 10814 Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags); 10815 } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) { 10816 unsigned OpFlags = RISCVII::MO_CALL; 10817 10818 if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(), 10819 nullptr)) 10820 OpFlags = RISCVII::MO_PLT; 10821 10822 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags); 10823 } 10824 10825 // The first call operand is the chain and the second is the target address. 10826 SmallVector<SDValue, 8> Ops; 10827 Ops.push_back(Chain); 10828 Ops.push_back(Callee); 10829 10830 // Add argument registers to the end of the list so that they are 10831 // known live into the call. 10832 for (auto &Reg : RegsToPass) 10833 Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType())); 10834 10835 if (!IsTailCall) { 10836 // Add a register mask operand representing the call-preserved registers. 10837 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo(); 10838 const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv); 10839 assert(Mask && "Missing call preserved mask for calling convention"); 10840 Ops.push_back(DAG.getRegisterMask(Mask)); 10841 } 10842 10843 // Glue the call to the argument copies, if any. 10844 if (Glue.getNode()) 10845 Ops.push_back(Glue); 10846 10847 // Emit the call. 10848 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue); 10849 10850 if (IsTailCall) { 10851 MF.getFrameInfo().setHasTailCall(); 10852 return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops); 10853 } 10854 10855 Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops); 10856 DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge); 10857 Glue = Chain.getValue(1); 10858 10859 // Mark the end of the call, which is glued to the call itself. 10860 Chain = DAG.getCALLSEQ_END(Chain, 10861 DAG.getConstant(NumBytes, DL, PtrVT, true), 10862 DAG.getConstant(0, DL, PtrVT, true), 10863 Glue, DL); 10864 Glue = Chain.getValue(1); 10865 10866 // Assign locations to each value returned by this call. 10867 SmallVector<CCValAssign, 16> RVLocs; 10868 CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext()); 10869 analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV); 10870 10871 // Copy all of the result registers out of their specified physreg. 10872 for (auto &VA : RVLocs) { 10873 // Copy the value out 10874 SDValue RetValue = 10875 DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue); 10876 // Glue the RetValue to the end of the call sequence 10877 Chain = RetValue.getValue(1); 10878 Glue = RetValue.getValue(2); 10879 10880 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10881 assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment"); 10882 SDValue RetValue2 = 10883 DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue); 10884 Chain = RetValue2.getValue(1); 10885 Glue = RetValue2.getValue(2); 10886 RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue, 10887 RetValue2); 10888 } 10889 10890 RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget); 10891 10892 InVals.push_back(RetValue); 10893 } 10894 10895 return Chain; 10896 } 10897 10898 bool RISCVTargetLowering::CanLowerReturn( 10899 CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg, 10900 const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const { 10901 SmallVector<CCValAssign, 16> RVLocs; 10902 CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context); 10903 10904 Optional<unsigned> FirstMaskArgument; 10905 if (Subtarget.hasVInstructions()) 10906 FirstMaskArgument = preAssignMask(Outs); 10907 10908 for (unsigned i = 0, e = Outs.size(); i != e; ++i) { 10909 MVT VT = Outs[i].VT; 10910 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags; 10911 RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI(); 10912 if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full, 10913 ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr, 10914 *this, FirstMaskArgument)) 10915 return false; 10916 } 10917 return true; 10918 } 10919 10920 SDValue 10921 RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv, 10922 bool IsVarArg, 10923 const SmallVectorImpl<ISD::OutputArg> &Outs, 10924 const SmallVectorImpl<SDValue> &OutVals, 10925 const SDLoc &DL, SelectionDAG &DAG) const { 10926 const MachineFunction &MF = DAG.getMachineFunction(); 10927 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 10928 10929 // Stores the assignment of the return value to a location. 10930 SmallVector<CCValAssign, 16> RVLocs; 10931 10932 // Info about the registers and stack slot. 10933 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs, 10934 *DAG.getContext()); 10935 10936 analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true, 10937 nullptr, CC_RISCV); 10938 10939 if (CallConv == CallingConv::GHC && !RVLocs.empty()) 10940 report_fatal_error("GHC functions return void only"); 10941 10942 SDValue Glue; 10943 SmallVector<SDValue, 4> RetOps(1, Chain); 10944 10945 // Copy the result values into the output registers. 10946 for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) { 10947 SDValue Val = OutVals[i]; 10948 CCValAssign &VA = RVLocs[i]; 10949 assert(VA.isRegLoc() && "Can only return in registers!"); 10950 10951 if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) { 10952 // Handle returning f64 on RV32D with a soft float ABI. 10953 assert(VA.isRegLoc() && "Expected return via registers"); 10954 SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL, 10955 DAG.getVTList(MVT::i32, MVT::i32), Val); 10956 SDValue Lo = SplitF64.getValue(0); 10957 SDValue Hi = SplitF64.getValue(1); 10958 Register RegLo = VA.getLocReg(); 10959 assert(RegLo < RISCV::X31 && "Invalid register pair"); 10960 Register RegHi = RegLo + 1; 10961 10962 if (STI.isRegisterReservedByUser(RegLo) || 10963 STI.isRegisterReservedByUser(RegHi)) 10964 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10965 MF.getFunction(), 10966 "Return value register required, but has been reserved."}); 10967 10968 Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue); 10969 Glue = Chain.getValue(1); 10970 RetOps.push_back(DAG.getRegister(RegLo, MVT::i32)); 10971 Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue); 10972 Glue = Chain.getValue(1); 10973 RetOps.push_back(DAG.getRegister(RegHi, MVT::i32)); 10974 } else { 10975 // Handle a 'normal' return. 10976 Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget); 10977 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue); 10978 10979 if (STI.isRegisterReservedByUser(VA.getLocReg())) 10980 MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ 10981 MF.getFunction(), 10982 "Return value register required, but has been reserved."}); 10983 10984 // Guarantee that all emitted copies are stuck together. 10985 Glue = Chain.getValue(1); 10986 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT())); 10987 } 10988 } 10989 10990 RetOps[0] = Chain; // Update chain. 10991 10992 // Add the glue node if we have it. 10993 if (Glue.getNode()) { 10994 RetOps.push_back(Glue); 10995 } 10996 10997 unsigned RetOpc = RISCVISD::RET_FLAG; 10998 // Interrupt service routines use different return instructions. 10999 const Function &Func = DAG.getMachineFunction().getFunction(); 11000 if (Func.hasFnAttribute("interrupt")) { 11001 if (!Func.getReturnType()->isVoidTy()) 11002 report_fatal_error( 11003 "Functions with the interrupt attribute must have void return type!"); 11004 11005 MachineFunction &MF = DAG.getMachineFunction(); 11006 StringRef Kind = 11007 MF.getFunction().getFnAttribute("interrupt").getValueAsString(); 11008 11009 if (Kind == "user") 11010 RetOpc = RISCVISD::URET_FLAG; 11011 else if (Kind == "supervisor") 11012 RetOpc = RISCVISD::SRET_FLAG; 11013 else 11014 RetOpc = RISCVISD::MRET_FLAG; 11015 } 11016 11017 return DAG.getNode(RetOpc, DL, MVT::Other, RetOps); 11018 } 11019 11020 void RISCVTargetLowering::validateCCReservedRegs( 11021 const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs, 11022 MachineFunction &MF) const { 11023 const Function &F = MF.getFunction(); 11024 const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>(); 11025 11026 if (llvm::any_of(Regs, [&STI](auto Reg) { 11027 return STI.isRegisterReservedByUser(Reg.first); 11028 })) 11029 F.getContext().diagnose(DiagnosticInfoUnsupported{ 11030 F, "Argument register required, but has been reserved."}); 11031 } 11032 11033 bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const { 11034 return CI->isTailCall(); 11035 } 11036 11037 const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const { 11038 #define NODE_NAME_CASE(NODE) \ 11039 case RISCVISD::NODE: \ 11040 return "RISCVISD::" #NODE; 11041 // clang-format off 11042 switch ((RISCVISD::NodeType)Opcode) { 11043 case RISCVISD::FIRST_NUMBER: 11044 break; 11045 NODE_NAME_CASE(RET_FLAG) 11046 NODE_NAME_CASE(URET_FLAG) 11047 NODE_NAME_CASE(SRET_FLAG) 11048 NODE_NAME_CASE(MRET_FLAG) 11049 NODE_NAME_CASE(CALL) 11050 NODE_NAME_CASE(SELECT_CC) 11051 NODE_NAME_CASE(BR_CC) 11052 NODE_NAME_CASE(BuildPairF64) 11053 NODE_NAME_CASE(SplitF64) 11054 NODE_NAME_CASE(TAIL) 11055 NODE_NAME_CASE(MULHSU) 11056 NODE_NAME_CASE(SLLW) 11057 NODE_NAME_CASE(SRAW) 11058 NODE_NAME_CASE(SRLW) 11059 NODE_NAME_CASE(DIVW) 11060 NODE_NAME_CASE(DIVUW) 11061 NODE_NAME_CASE(REMUW) 11062 NODE_NAME_CASE(ROLW) 11063 NODE_NAME_CASE(RORW) 11064 NODE_NAME_CASE(CLZW) 11065 NODE_NAME_CASE(CTZW) 11066 NODE_NAME_CASE(FSLW) 11067 NODE_NAME_CASE(FSRW) 11068 NODE_NAME_CASE(FSL) 11069 NODE_NAME_CASE(FSR) 11070 NODE_NAME_CASE(FMV_H_X) 11071 NODE_NAME_CASE(FMV_X_ANYEXTH) 11072 NODE_NAME_CASE(FMV_X_SIGNEXTH) 11073 NODE_NAME_CASE(FMV_W_X_RV64) 11074 NODE_NAME_CASE(FMV_X_ANYEXTW_RV64) 11075 NODE_NAME_CASE(FCVT_X) 11076 NODE_NAME_CASE(FCVT_XU) 11077 NODE_NAME_CASE(FCVT_W_RV64) 11078 NODE_NAME_CASE(FCVT_WU_RV64) 11079 NODE_NAME_CASE(STRICT_FCVT_W_RV64) 11080 NODE_NAME_CASE(STRICT_FCVT_WU_RV64) 11081 NODE_NAME_CASE(READ_CYCLE_WIDE) 11082 NODE_NAME_CASE(GREV) 11083 NODE_NAME_CASE(GREVW) 11084 NODE_NAME_CASE(GORC) 11085 NODE_NAME_CASE(GORCW) 11086 NODE_NAME_CASE(SHFL) 11087 NODE_NAME_CASE(SHFLW) 11088 NODE_NAME_CASE(UNSHFL) 11089 NODE_NAME_CASE(UNSHFLW) 11090 NODE_NAME_CASE(BFP) 11091 NODE_NAME_CASE(BFPW) 11092 NODE_NAME_CASE(BCOMPRESS) 11093 NODE_NAME_CASE(BCOMPRESSW) 11094 NODE_NAME_CASE(BDECOMPRESS) 11095 NODE_NAME_CASE(BDECOMPRESSW) 11096 NODE_NAME_CASE(VMV_V_X_VL) 11097 NODE_NAME_CASE(VFMV_V_F_VL) 11098 NODE_NAME_CASE(VMV_X_S) 11099 NODE_NAME_CASE(VMV_S_X_VL) 11100 NODE_NAME_CASE(VFMV_S_F_VL) 11101 NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL) 11102 NODE_NAME_CASE(READ_VLENB) 11103 NODE_NAME_CASE(TRUNCATE_VECTOR_VL) 11104 NODE_NAME_CASE(VSLIDEUP_VL) 11105 NODE_NAME_CASE(VSLIDE1UP_VL) 11106 NODE_NAME_CASE(VSLIDEDOWN_VL) 11107 NODE_NAME_CASE(VSLIDE1DOWN_VL) 11108 NODE_NAME_CASE(VID_VL) 11109 NODE_NAME_CASE(VFNCVT_ROD_VL) 11110 NODE_NAME_CASE(VECREDUCE_ADD_VL) 11111 NODE_NAME_CASE(VECREDUCE_UMAX_VL) 11112 NODE_NAME_CASE(VECREDUCE_SMAX_VL) 11113 NODE_NAME_CASE(VECREDUCE_UMIN_VL) 11114 NODE_NAME_CASE(VECREDUCE_SMIN_VL) 11115 NODE_NAME_CASE(VECREDUCE_AND_VL) 11116 NODE_NAME_CASE(VECREDUCE_OR_VL) 11117 NODE_NAME_CASE(VECREDUCE_XOR_VL) 11118 NODE_NAME_CASE(VECREDUCE_FADD_VL) 11119 NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL) 11120 NODE_NAME_CASE(VECREDUCE_FMIN_VL) 11121 NODE_NAME_CASE(VECREDUCE_FMAX_VL) 11122 NODE_NAME_CASE(ADD_VL) 11123 NODE_NAME_CASE(AND_VL) 11124 NODE_NAME_CASE(MUL_VL) 11125 NODE_NAME_CASE(OR_VL) 11126 NODE_NAME_CASE(SDIV_VL) 11127 NODE_NAME_CASE(SHL_VL) 11128 NODE_NAME_CASE(SREM_VL) 11129 NODE_NAME_CASE(SRA_VL) 11130 NODE_NAME_CASE(SRL_VL) 11131 NODE_NAME_CASE(SUB_VL) 11132 NODE_NAME_CASE(UDIV_VL) 11133 NODE_NAME_CASE(UREM_VL) 11134 NODE_NAME_CASE(XOR_VL) 11135 NODE_NAME_CASE(SADDSAT_VL) 11136 NODE_NAME_CASE(UADDSAT_VL) 11137 NODE_NAME_CASE(SSUBSAT_VL) 11138 NODE_NAME_CASE(USUBSAT_VL) 11139 NODE_NAME_CASE(FADD_VL) 11140 NODE_NAME_CASE(FSUB_VL) 11141 NODE_NAME_CASE(FMUL_VL) 11142 NODE_NAME_CASE(FDIV_VL) 11143 NODE_NAME_CASE(FNEG_VL) 11144 NODE_NAME_CASE(FABS_VL) 11145 NODE_NAME_CASE(FSQRT_VL) 11146 NODE_NAME_CASE(FMA_VL) 11147 NODE_NAME_CASE(FCOPYSIGN_VL) 11148 NODE_NAME_CASE(SMIN_VL) 11149 NODE_NAME_CASE(SMAX_VL) 11150 NODE_NAME_CASE(UMIN_VL) 11151 NODE_NAME_CASE(UMAX_VL) 11152 NODE_NAME_CASE(FMINNUM_VL) 11153 NODE_NAME_CASE(FMAXNUM_VL) 11154 NODE_NAME_CASE(MULHS_VL) 11155 NODE_NAME_CASE(MULHU_VL) 11156 NODE_NAME_CASE(FP_TO_SINT_VL) 11157 NODE_NAME_CASE(FP_TO_UINT_VL) 11158 NODE_NAME_CASE(SINT_TO_FP_VL) 11159 NODE_NAME_CASE(UINT_TO_FP_VL) 11160 NODE_NAME_CASE(FP_EXTEND_VL) 11161 NODE_NAME_CASE(FP_ROUND_VL) 11162 NODE_NAME_CASE(VWMUL_VL) 11163 NODE_NAME_CASE(VWMULU_VL) 11164 NODE_NAME_CASE(VWMULSU_VL) 11165 NODE_NAME_CASE(VWADD_VL) 11166 NODE_NAME_CASE(VWADDU_VL) 11167 NODE_NAME_CASE(VWSUB_VL) 11168 NODE_NAME_CASE(VWSUBU_VL) 11169 NODE_NAME_CASE(VWADD_W_VL) 11170 NODE_NAME_CASE(VWADDU_W_VL) 11171 NODE_NAME_CASE(VWSUB_W_VL) 11172 NODE_NAME_CASE(VWSUBU_W_VL) 11173 NODE_NAME_CASE(SETCC_VL) 11174 NODE_NAME_CASE(VSELECT_VL) 11175 NODE_NAME_CASE(VP_MERGE_VL) 11176 NODE_NAME_CASE(VMAND_VL) 11177 NODE_NAME_CASE(VMOR_VL) 11178 NODE_NAME_CASE(VMXOR_VL) 11179 NODE_NAME_CASE(VMCLR_VL) 11180 NODE_NAME_CASE(VMSET_VL) 11181 NODE_NAME_CASE(VRGATHER_VX_VL) 11182 NODE_NAME_CASE(VRGATHER_VV_VL) 11183 NODE_NAME_CASE(VRGATHEREI16_VV_VL) 11184 NODE_NAME_CASE(VSEXT_VL) 11185 NODE_NAME_CASE(VZEXT_VL) 11186 NODE_NAME_CASE(VCPOP_VL) 11187 NODE_NAME_CASE(READ_CSR) 11188 NODE_NAME_CASE(WRITE_CSR) 11189 NODE_NAME_CASE(SWAP_CSR) 11190 } 11191 // clang-format on 11192 return nullptr; 11193 #undef NODE_NAME_CASE 11194 } 11195 11196 /// getConstraintType - Given a constraint letter, return the type of 11197 /// constraint it is for this target. 11198 RISCVTargetLowering::ConstraintType 11199 RISCVTargetLowering::getConstraintType(StringRef Constraint) const { 11200 if (Constraint.size() == 1) { 11201 switch (Constraint[0]) { 11202 default: 11203 break; 11204 case 'f': 11205 return C_RegisterClass; 11206 case 'I': 11207 case 'J': 11208 case 'K': 11209 return C_Immediate; 11210 case 'A': 11211 return C_Memory; 11212 case 'S': // A symbolic address 11213 return C_Other; 11214 } 11215 } else { 11216 if (Constraint == "vr" || Constraint == "vm") 11217 return C_RegisterClass; 11218 } 11219 return TargetLowering::getConstraintType(Constraint); 11220 } 11221 11222 std::pair<unsigned, const TargetRegisterClass *> 11223 RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI, 11224 StringRef Constraint, 11225 MVT VT) const { 11226 // First, see if this is a constraint that directly corresponds to a 11227 // RISCV register class. 11228 if (Constraint.size() == 1) { 11229 switch (Constraint[0]) { 11230 case 'r': 11231 // TODO: Support fixed vectors up to XLen for P extension? 11232 if (VT.isVector()) 11233 break; 11234 return std::make_pair(0U, &RISCV::GPRRegClass); 11235 case 'f': 11236 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) 11237 return std::make_pair(0U, &RISCV::FPR16RegClass); 11238 if (Subtarget.hasStdExtF() && VT == MVT::f32) 11239 return std::make_pair(0U, &RISCV::FPR32RegClass); 11240 if (Subtarget.hasStdExtD() && VT == MVT::f64) 11241 return std::make_pair(0U, &RISCV::FPR64RegClass); 11242 break; 11243 default: 11244 break; 11245 } 11246 } else if (Constraint == "vr") { 11247 for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass, 11248 &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11249 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) 11250 return std::make_pair(0U, RC); 11251 } 11252 } else if (Constraint == "vm") { 11253 if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy)) 11254 return std::make_pair(0U, &RISCV::VMV0RegClass); 11255 } 11256 11257 // Clang will correctly decode the usage of register name aliases into their 11258 // official names. However, other frontends like `rustc` do not. This allows 11259 // users of these frontends to use the ABI names for registers in LLVM-style 11260 // register constraints. 11261 unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower()) 11262 .Case("{zero}", RISCV::X0) 11263 .Case("{ra}", RISCV::X1) 11264 .Case("{sp}", RISCV::X2) 11265 .Case("{gp}", RISCV::X3) 11266 .Case("{tp}", RISCV::X4) 11267 .Case("{t0}", RISCV::X5) 11268 .Case("{t1}", RISCV::X6) 11269 .Case("{t2}", RISCV::X7) 11270 .Cases("{s0}", "{fp}", RISCV::X8) 11271 .Case("{s1}", RISCV::X9) 11272 .Case("{a0}", RISCV::X10) 11273 .Case("{a1}", RISCV::X11) 11274 .Case("{a2}", RISCV::X12) 11275 .Case("{a3}", RISCV::X13) 11276 .Case("{a4}", RISCV::X14) 11277 .Case("{a5}", RISCV::X15) 11278 .Case("{a6}", RISCV::X16) 11279 .Case("{a7}", RISCV::X17) 11280 .Case("{s2}", RISCV::X18) 11281 .Case("{s3}", RISCV::X19) 11282 .Case("{s4}", RISCV::X20) 11283 .Case("{s5}", RISCV::X21) 11284 .Case("{s6}", RISCV::X22) 11285 .Case("{s7}", RISCV::X23) 11286 .Case("{s8}", RISCV::X24) 11287 .Case("{s9}", RISCV::X25) 11288 .Case("{s10}", RISCV::X26) 11289 .Case("{s11}", RISCV::X27) 11290 .Case("{t3}", RISCV::X28) 11291 .Case("{t4}", RISCV::X29) 11292 .Case("{t5}", RISCV::X30) 11293 .Case("{t6}", RISCV::X31) 11294 .Default(RISCV::NoRegister); 11295 if (XRegFromAlias != RISCV::NoRegister) 11296 return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass); 11297 11298 // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the 11299 // TableGen record rather than the AsmName to choose registers for InlineAsm 11300 // constraints, plus we want to match those names to the widest floating point 11301 // register type available, manually select floating point registers here. 11302 // 11303 // The second case is the ABI name of the register, so that frontends can also 11304 // use the ABI names in register constraint lists. 11305 if (Subtarget.hasStdExtF()) { 11306 unsigned FReg = StringSwitch<unsigned>(Constraint.lower()) 11307 .Cases("{f0}", "{ft0}", RISCV::F0_F) 11308 .Cases("{f1}", "{ft1}", RISCV::F1_F) 11309 .Cases("{f2}", "{ft2}", RISCV::F2_F) 11310 .Cases("{f3}", "{ft3}", RISCV::F3_F) 11311 .Cases("{f4}", "{ft4}", RISCV::F4_F) 11312 .Cases("{f5}", "{ft5}", RISCV::F5_F) 11313 .Cases("{f6}", "{ft6}", RISCV::F6_F) 11314 .Cases("{f7}", "{ft7}", RISCV::F7_F) 11315 .Cases("{f8}", "{fs0}", RISCV::F8_F) 11316 .Cases("{f9}", "{fs1}", RISCV::F9_F) 11317 .Cases("{f10}", "{fa0}", RISCV::F10_F) 11318 .Cases("{f11}", "{fa1}", RISCV::F11_F) 11319 .Cases("{f12}", "{fa2}", RISCV::F12_F) 11320 .Cases("{f13}", "{fa3}", RISCV::F13_F) 11321 .Cases("{f14}", "{fa4}", RISCV::F14_F) 11322 .Cases("{f15}", "{fa5}", RISCV::F15_F) 11323 .Cases("{f16}", "{fa6}", RISCV::F16_F) 11324 .Cases("{f17}", "{fa7}", RISCV::F17_F) 11325 .Cases("{f18}", "{fs2}", RISCV::F18_F) 11326 .Cases("{f19}", "{fs3}", RISCV::F19_F) 11327 .Cases("{f20}", "{fs4}", RISCV::F20_F) 11328 .Cases("{f21}", "{fs5}", RISCV::F21_F) 11329 .Cases("{f22}", "{fs6}", RISCV::F22_F) 11330 .Cases("{f23}", "{fs7}", RISCV::F23_F) 11331 .Cases("{f24}", "{fs8}", RISCV::F24_F) 11332 .Cases("{f25}", "{fs9}", RISCV::F25_F) 11333 .Cases("{f26}", "{fs10}", RISCV::F26_F) 11334 .Cases("{f27}", "{fs11}", RISCV::F27_F) 11335 .Cases("{f28}", "{ft8}", RISCV::F28_F) 11336 .Cases("{f29}", "{ft9}", RISCV::F29_F) 11337 .Cases("{f30}", "{ft10}", RISCV::F30_F) 11338 .Cases("{f31}", "{ft11}", RISCV::F31_F) 11339 .Default(RISCV::NoRegister); 11340 if (FReg != RISCV::NoRegister) { 11341 assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg"); 11342 if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) { 11343 unsigned RegNo = FReg - RISCV::F0_F; 11344 unsigned DReg = RISCV::F0_D + RegNo; 11345 return std::make_pair(DReg, &RISCV::FPR64RegClass); 11346 } 11347 if (VT == MVT::f32 || VT == MVT::Other) 11348 return std::make_pair(FReg, &RISCV::FPR32RegClass); 11349 if (Subtarget.hasStdExtZfh() && VT == MVT::f16) { 11350 unsigned RegNo = FReg - RISCV::F0_F; 11351 unsigned HReg = RISCV::F0_H + RegNo; 11352 return std::make_pair(HReg, &RISCV::FPR16RegClass); 11353 } 11354 } 11355 } 11356 11357 if (Subtarget.hasVInstructions()) { 11358 Register VReg = StringSwitch<Register>(Constraint.lower()) 11359 .Case("{v0}", RISCV::V0) 11360 .Case("{v1}", RISCV::V1) 11361 .Case("{v2}", RISCV::V2) 11362 .Case("{v3}", RISCV::V3) 11363 .Case("{v4}", RISCV::V4) 11364 .Case("{v5}", RISCV::V5) 11365 .Case("{v6}", RISCV::V6) 11366 .Case("{v7}", RISCV::V7) 11367 .Case("{v8}", RISCV::V8) 11368 .Case("{v9}", RISCV::V9) 11369 .Case("{v10}", RISCV::V10) 11370 .Case("{v11}", RISCV::V11) 11371 .Case("{v12}", RISCV::V12) 11372 .Case("{v13}", RISCV::V13) 11373 .Case("{v14}", RISCV::V14) 11374 .Case("{v15}", RISCV::V15) 11375 .Case("{v16}", RISCV::V16) 11376 .Case("{v17}", RISCV::V17) 11377 .Case("{v18}", RISCV::V18) 11378 .Case("{v19}", RISCV::V19) 11379 .Case("{v20}", RISCV::V20) 11380 .Case("{v21}", RISCV::V21) 11381 .Case("{v22}", RISCV::V22) 11382 .Case("{v23}", RISCV::V23) 11383 .Case("{v24}", RISCV::V24) 11384 .Case("{v25}", RISCV::V25) 11385 .Case("{v26}", RISCV::V26) 11386 .Case("{v27}", RISCV::V27) 11387 .Case("{v28}", RISCV::V28) 11388 .Case("{v29}", RISCV::V29) 11389 .Case("{v30}", RISCV::V30) 11390 .Case("{v31}", RISCV::V31) 11391 .Default(RISCV::NoRegister); 11392 if (VReg != RISCV::NoRegister) { 11393 if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy)) 11394 return std::make_pair(VReg, &RISCV::VMRegClass); 11395 if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy)) 11396 return std::make_pair(VReg, &RISCV::VRRegClass); 11397 for (const auto *RC : 11398 {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) { 11399 if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) { 11400 VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC); 11401 return std::make_pair(VReg, RC); 11402 } 11403 } 11404 } 11405 } 11406 11407 std::pair<Register, const TargetRegisterClass *> Res = 11408 TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT); 11409 11410 // If we picked one of the Zfinx register classes, remap it to the GPR class. 11411 // FIXME: When Zfinx is supported in CodeGen this will need to take the 11412 // Subtarget into account. 11413 if (Res.second == &RISCV::GPRF16RegClass || 11414 Res.second == &RISCV::GPRF32RegClass || 11415 Res.second == &RISCV::GPRF64RegClass) 11416 return std::make_pair(Res.first, &RISCV::GPRRegClass); 11417 11418 return Res; 11419 } 11420 11421 unsigned 11422 RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const { 11423 // Currently only support length 1 constraints. 11424 if (ConstraintCode.size() == 1) { 11425 switch (ConstraintCode[0]) { 11426 case 'A': 11427 return InlineAsm::Constraint_A; 11428 default: 11429 break; 11430 } 11431 } 11432 11433 return TargetLowering::getInlineAsmMemConstraint(ConstraintCode); 11434 } 11435 11436 void RISCVTargetLowering::LowerAsmOperandForConstraint( 11437 SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops, 11438 SelectionDAG &DAG) const { 11439 // Currently only support length 1 constraints. 11440 if (Constraint.length() == 1) { 11441 switch (Constraint[0]) { 11442 case 'I': 11443 // Validate & create a 12-bit signed immediate operand. 11444 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11445 uint64_t CVal = C->getSExtValue(); 11446 if (isInt<12>(CVal)) 11447 Ops.push_back( 11448 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11449 } 11450 return; 11451 case 'J': 11452 // Validate & create an integer zero operand. 11453 if (auto *C = dyn_cast<ConstantSDNode>(Op)) 11454 if (C->getZExtValue() == 0) 11455 Ops.push_back( 11456 DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT())); 11457 return; 11458 case 'K': 11459 // Validate & create a 5-bit unsigned immediate operand. 11460 if (auto *C = dyn_cast<ConstantSDNode>(Op)) { 11461 uint64_t CVal = C->getZExtValue(); 11462 if (isUInt<5>(CVal)) 11463 Ops.push_back( 11464 DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT())); 11465 } 11466 return; 11467 case 'S': 11468 if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 11469 Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op), 11470 GA->getValueType(0))); 11471 } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) { 11472 Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(), 11473 BA->getValueType(0))); 11474 } 11475 return; 11476 default: 11477 break; 11478 } 11479 } 11480 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG); 11481 } 11482 11483 Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder, 11484 Instruction *Inst, 11485 AtomicOrdering Ord) const { 11486 if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent) 11487 return Builder.CreateFence(Ord); 11488 if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord)) 11489 return Builder.CreateFence(AtomicOrdering::Release); 11490 return nullptr; 11491 } 11492 11493 Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder, 11494 Instruction *Inst, 11495 AtomicOrdering Ord) const { 11496 if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord)) 11497 return Builder.CreateFence(AtomicOrdering::Acquire); 11498 return nullptr; 11499 } 11500 11501 TargetLowering::AtomicExpansionKind 11502 RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const { 11503 // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating 11504 // point operations can't be used in an lr/sc sequence without breaking the 11505 // forward-progress guarantee. 11506 if (AI->isFloatingPointOperation()) 11507 return AtomicExpansionKind::CmpXChg; 11508 11509 unsigned Size = AI->getType()->getPrimitiveSizeInBits(); 11510 if (Size == 8 || Size == 16) 11511 return AtomicExpansionKind::MaskedIntrinsic; 11512 return AtomicExpansionKind::None; 11513 } 11514 11515 static Intrinsic::ID 11516 getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) { 11517 if (XLen == 32) { 11518 switch (BinOp) { 11519 default: 11520 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11521 case AtomicRMWInst::Xchg: 11522 return Intrinsic::riscv_masked_atomicrmw_xchg_i32; 11523 case AtomicRMWInst::Add: 11524 return Intrinsic::riscv_masked_atomicrmw_add_i32; 11525 case AtomicRMWInst::Sub: 11526 return Intrinsic::riscv_masked_atomicrmw_sub_i32; 11527 case AtomicRMWInst::Nand: 11528 return Intrinsic::riscv_masked_atomicrmw_nand_i32; 11529 case AtomicRMWInst::Max: 11530 return Intrinsic::riscv_masked_atomicrmw_max_i32; 11531 case AtomicRMWInst::Min: 11532 return Intrinsic::riscv_masked_atomicrmw_min_i32; 11533 case AtomicRMWInst::UMax: 11534 return Intrinsic::riscv_masked_atomicrmw_umax_i32; 11535 case AtomicRMWInst::UMin: 11536 return Intrinsic::riscv_masked_atomicrmw_umin_i32; 11537 } 11538 } 11539 11540 if (XLen == 64) { 11541 switch (BinOp) { 11542 default: 11543 llvm_unreachable("Unexpected AtomicRMW BinOp"); 11544 case AtomicRMWInst::Xchg: 11545 return Intrinsic::riscv_masked_atomicrmw_xchg_i64; 11546 case AtomicRMWInst::Add: 11547 return Intrinsic::riscv_masked_atomicrmw_add_i64; 11548 case AtomicRMWInst::Sub: 11549 return Intrinsic::riscv_masked_atomicrmw_sub_i64; 11550 case AtomicRMWInst::Nand: 11551 return Intrinsic::riscv_masked_atomicrmw_nand_i64; 11552 case AtomicRMWInst::Max: 11553 return Intrinsic::riscv_masked_atomicrmw_max_i64; 11554 case AtomicRMWInst::Min: 11555 return Intrinsic::riscv_masked_atomicrmw_min_i64; 11556 case AtomicRMWInst::UMax: 11557 return Intrinsic::riscv_masked_atomicrmw_umax_i64; 11558 case AtomicRMWInst::UMin: 11559 return Intrinsic::riscv_masked_atomicrmw_umin_i64; 11560 } 11561 } 11562 11563 llvm_unreachable("Unexpected XLen\n"); 11564 } 11565 11566 Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic( 11567 IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr, 11568 Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const { 11569 unsigned XLen = Subtarget.getXLen(); 11570 Value *Ordering = 11571 Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering())); 11572 Type *Tys[] = {AlignedAddr->getType()}; 11573 Function *LrwOpScwLoop = Intrinsic::getDeclaration( 11574 AI->getModule(), 11575 getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys); 11576 11577 if (XLen == 64) { 11578 Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty()); 11579 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11580 ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty()); 11581 } 11582 11583 Value *Result; 11584 11585 // Must pass the shift amount needed to sign extend the loaded value prior 11586 // to performing a signed comparison for min/max. ShiftAmt is the number of 11587 // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which 11588 // is the number of bits to left+right shift the value in order to 11589 // sign-extend. 11590 if (AI->getOperation() == AtomicRMWInst::Min || 11591 AI->getOperation() == AtomicRMWInst::Max) { 11592 const DataLayout &DL = AI->getModule()->getDataLayout(); 11593 unsigned ValWidth = 11594 DL.getTypeStoreSizeInBits(AI->getValOperand()->getType()); 11595 Value *SextShamt = 11596 Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt); 11597 Result = Builder.CreateCall(LrwOpScwLoop, 11598 {AlignedAddr, Incr, Mask, SextShamt, Ordering}); 11599 } else { 11600 Result = 11601 Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering}); 11602 } 11603 11604 if (XLen == 64) 11605 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11606 return Result; 11607 } 11608 11609 TargetLowering::AtomicExpansionKind 11610 RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR( 11611 AtomicCmpXchgInst *CI) const { 11612 unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits(); 11613 if (Size == 8 || Size == 16) 11614 return AtomicExpansionKind::MaskedIntrinsic; 11615 return AtomicExpansionKind::None; 11616 } 11617 11618 Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic( 11619 IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr, 11620 Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const { 11621 unsigned XLen = Subtarget.getXLen(); 11622 Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord)); 11623 Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32; 11624 if (XLen == 64) { 11625 CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty()); 11626 NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty()); 11627 Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty()); 11628 CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64; 11629 } 11630 Type *Tys[] = {AlignedAddr->getType()}; 11631 Function *MaskedCmpXchg = 11632 Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys); 11633 Value *Result = Builder.CreateCall( 11634 MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering}); 11635 if (XLen == 64) 11636 Result = Builder.CreateTrunc(Result, Builder.getInt32Ty()); 11637 return Result; 11638 } 11639 11640 bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT, 11641 EVT DataVT) const { 11642 return false; 11643 } 11644 11645 bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT, 11646 EVT VT) const { 11647 if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple()) 11648 return false; 11649 11650 switch (FPVT.getSimpleVT().SimpleTy) { 11651 case MVT::f16: 11652 return Subtarget.hasStdExtZfh(); 11653 case MVT::f32: 11654 return Subtarget.hasStdExtF(); 11655 case MVT::f64: 11656 return Subtarget.hasStdExtD(); 11657 default: 11658 return false; 11659 } 11660 } 11661 11662 unsigned RISCVTargetLowering::getJumpTableEncoding() const { 11663 // If we are using the small code model, we can reduce size of jump table 11664 // entry to 4 bytes. 11665 if (Subtarget.is64Bit() && !isPositionIndependent() && 11666 getTargetMachine().getCodeModel() == CodeModel::Small) { 11667 return MachineJumpTableInfo::EK_Custom32; 11668 } 11669 return TargetLowering::getJumpTableEncoding(); 11670 } 11671 11672 const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry( 11673 const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB, 11674 unsigned uid, MCContext &Ctx) const { 11675 assert(Subtarget.is64Bit() && !isPositionIndependent() && 11676 getTargetMachine().getCodeModel() == CodeModel::Small); 11677 return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx); 11678 } 11679 11680 bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF, 11681 EVT VT) const { 11682 VT = VT.getScalarType(); 11683 11684 if (!VT.isSimple()) 11685 return false; 11686 11687 switch (VT.getSimpleVT().SimpleTy) { 11688 case MVT::f16: 11689 return Subtarget.hasStdExtZfh(); 11690 case MVT::f32: 11691 return Subtarget.hasStdExtF(); 11692 case MVT::f64: 11693 return Subtarget.hasStdExtD(); 11694 default: 11695 break; 11696 } 11697 11698 return false; 11699 } 11700 11701 Register RISCVTargetLowering::getExceptionPointerRegister( 11702 const Constant *PersonalityFn) const { 11703 return RISCV::X10; 11704 } 11705 11706 Register RISCVTargetLowering::getExceptionSelectorRegister( 11707 const Constant *PersonalityFn) const { 11708 return RISCV::X11; 11709 } 11710 11711 bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const { 11712 // Return false to suppress the unnecessary extensions if the LibCall 11713 // arguments or return value is f32 type for LP64 ABI. 11714 RISCVABI::ABI ABI = Subtarget.getTargetABI(); 11715 if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32)) 11716 return false; 11717 11718 return true; 11719 } 11720 11721 bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const { 11722 if (Subtarget.is64Bit() && Type == MVT::i32) 11723 return true; 11724 11725 return IsSigned; 11726 } 11727 11728 bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT, 11729 SDValue C) const { 11730 // Check integral scalar types. 11731 if (VT.isScalarInteger()) { 11732 // Omit the optimization if the sub target has the M extension and the data 11733 // size exceeds XLen. 11734 if (Subtarget.hasStdExtM() && VT.getSizeInBits() > Subtarget.getXLen()) 11735 return false; 11736 if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) { 11737 // Break the MUL to a SLLI and an ADD/SUB. 11738 const APInt &Imm = ConstNode->getAPIntValue(); 11739 if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() || 11740 (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2()) 11741 return true; 11742 // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12. 11743 if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) && 11744 ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() || 11745 (Imm - 8).isPowerOf2())) 11746 return true; 11747 // Omit the following optimization if the sub target has the M extension 11748 // and the data size >= XLen. 11749 if (Subtarget.hasStdExtM() && VT.getSizeInBits() >= Subtarget.getXLen()) 11750 return false; 11751 // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs 11752 // a pair of LUI/ADDI. 11753 if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) { 11754 APInt ImmS = Imm.ashr(Imm.countTrailingZeros()); 11755 if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() || 11756 (1 - ImmS).isPowerOf2()) 11757 return true; 11758 } 11759 } 11760 } 11761 11762 return false; 11763 } 11764 11765 bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode, 11766 SDValue ConstNode) const { 11767 // Let the DAGCombiner decide for vectors. 11768 EVT VT = AddNode.getValueType(); 11769 if (VT.isVector()) 11770 return true; 11771 11772 // Let the DAGCombiner decide for larger types. 11773 if (VT.getScalarSizeInBits() > Subtarget.getXLen()) 11774 return true; 11775 11776 // It is worse if c1 is simm12 while c1*c2 is not. 11777 ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1)); 11778 ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode); 11779 const APInt &C1 = C1Node->getAPIntValue(); 11780 const APInt &C2 = C2Node->getAPIntValue(); 11781 if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12)) 11782 return false; 11783 11784 // Default to true and let the DAGCombiner decide. 11785 return true; 11786 } 11787 11788 bool RISCVTargetLowering::allowsMisalignedMemoryAccesses( 11789 EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags, 11790 bool *Fast) const { 11791 if (!VT.isVector()) { 11792 if (Fast) 11793 *Fast = false; 11794 return Subtarget.enableUnalignedScalarMem(); 11795 } 11796 11797 // All vector implementations must support element alignment 11798 EVT ElemVT = VT.getVectorElementType(); 11799 if (Alignment >= ElemVT.getStoreSize()) { 11800 if (Fast) 11801 *Fast = true; 11802 return true; 11803 } 11804 11805 return false; 11806 } 11807 11808 bool RISCVTargetLowering::splitValueIntoRegisterParts( 11809 SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts, 11810 unsigned NumParts, MVT PartVT, Optional<CallingConv::ID> CC) const { 11811 bool IsABIRegCopy = CC.hasValue(); 11812 EVT ValueVT = Val.getValueType(); 11813 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11814 // Cast the f16 to i16, extend to i32, pad with ones to make a float nan, 11815 // and cast to f32. 11816 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val); 11817 Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val); 11818 Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val, 11819 DAG.getConstant(0xFFFF0000, DL, MVT::i32)); 11820 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val); 11821 Parts[0] = Val; 11822 return true; 11823 } 11824 11825 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11826 LLVMContext &Context = *DAG.getContext(); 11827 EVT ValueEltVT = ValueVT.getVectorElementType(); 11828 EVT PartEltVT = PartVT.getVectorElementType(); 11829 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11830 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11831 if (PartVTBitSize % ValueVTBitSize == 0) { 11832 assert(PartVTBitSize >= ValueVTBitSize); 11833 // If the element types are different, bitcast to the same element type of 11834 // PartVT first. 11835 // Give an example here, we want copy a <vscale x 1 x i8> value to 11836 // <vscale x 4 x i16>. 11837 // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert 11838 // subvector, then we can bitcast to <vscale x 4 x i16>. 11839 if (ValueEltVT != PartEltVT) { 11840 if (PartVTBitSize > ValueVTBitSize) { 11841 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11842 assert(Count != 0 && "The number of element should not be zero."); 11843 EVT SameEltTypeVT = 11844 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11845 Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT, 11846 DAG.getUNDEF(SameEltTypeVT), Val, 11847 DAG.getVectorIdxConstant(0, DL)); 11848 } 11849 Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val); 11850 } else { 11851 Val = 11852 DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT), 11853 Val, DAG.getVectorIdxConstant(0, DL)); 11854 } 11855 Parts[0] = Val; 11856 return true; 11857 } 11858 } 11859 return false; 11860 } 11861 11862 SDValue RISCVTargetLowering::joinRegisterPartsIntoValue( 11863 SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts, 11864 MVT PartVT, EVT ValueVT, Optional<CallingConv::ID> CC) const { 11865 bool IsABIRegCopy = CC.hasValue(); 11866 if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) { 11867 SDValue Val = Parts[0]; 11868 11869 // Cast the f32 to i32, truncate to i16, and cast back to f16. 11870 Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val); 11871 Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val); 11872 Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val); 11873 return Val; 11874 } 11875 11876 if (ValueVT.isScalableVector() && PartVT.isScalableVector()) { 11877 LLVMContext &Context = *DAG.getContext(); 11878 SDValue Val = Parts[0]; 11879 EVT ValueEltVT = ValueVT.getVectorElementType(); 11880 EVT PartEltVT = PartVT.getVectorElementType(); 11881 unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinSize(); 11882 unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinSize(); 11883 if (PartVTBitSize % ValueVTBitSize == 0) { 11884 assert(PartVTBitSize >= ValueVTBitSize); 11885 EVT SameEltTypeVT = ValueVT; 11886 // If the element types are different, convert it to the same element type 11887 // of PartVT. 11888 // Give an example here, we want copy a <vscale x 1 x i8> value from 11889 // <vscale x 4 x i16>. 11890 // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first, 11891 // then we can extract <vscale x 1 x i8>. 11892 if (ValueEltVT != PartEltVT) { 11893 unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits(); 11894 assert(Count != 0 && "The number of element should not be zero."); 11895 SameEltTypeVT = 11896 EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true); 11897 Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val); 11898 } 11899 Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val, 11900 DAG.getVectorIdxConstant(0, DL)); 11901 return Val; 11902 } 11903 } 11904 return SDValue(); 11905 } 11906 11907 SDValue 11908 RISCVTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor, 11909 SelectionDAG &DAG, 11910 SmallVectorImpl<SDNode *> &Created) const { 11911 AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes(); 11912 if (isIntDivCheap(N->getValueType(0), Attr)) 11913 return SDValue(N, 0); // Lower SDIV as SDIV 11914 11915 assert((Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()) && 11916 "Unexpected divisor!"); 11917 11918 // Conditional move is needed, so do the transformation iff Zbt is enabled. 11919 if (!Subtarget.hasStdExtZbt()) 11920 return SDValue(); 11921 11922 // When |Divisor| >= 2 ^ 12, it isn't profitable to do such transformation. 11923 // Besides, more critical path instructions will be generated when dividing 11924 // by 2. So we keep using the original DAGs for these cases. 11925 unsigned Lg2 = Divisor.countTrailingZeros(); 11926 if (Lg2 == 1 || Lg2 >= 12) 11927 return SDValue(); 11928 11929 // fold (sdiv X, pow2) 11930 EVT VT = N->getValueType(0); 11931 if (VT != MVT::i32 && !(Subtarget.is64Bit() && VT == MVT::i64)) 11932 return SDValue(); 11933 11934 SDLoc DL(N); 11935 SDValue N0 = N->getOperand(0); 11936 SDValue Zero = DAG.getConstant(0, DL, VT); 11937 SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT); 11938 11939 // Add (N0 < 0) ? Pow2 - 1 : 0; 11940 SDValue Cmp = DAG.getSetCC(DL, VT, N0, Zero, ISD::SETLT); 11941 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne); 11942 SDValue Sel = DAG.getNode(ISD::SELECT, DL, VT, Cmp, Add, N0); 11943 11944 Created.push_back(Cmp.getNode()); 11945 Created.push_back(Add.getNode()); 11946 Created.push_back(Sel.getNode()); 11947 11948 // Divide by pow2. 11949 SDValue SRA = 11950 DAG.getNode(ISD::SRA, DL, VT, Sel, DAG.getConstant(Lg2, DL, VT)); 11951 11952 // If we're dividing by a positive value, we're done. Otherwise, we must 11953 // negate the result. 11954 if (Divisor.isNonNegative()) 11955 return SRA; 11956 11957 Created.push_back(SRA.getNode()); 11958 return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA); 11959 } 11960 11961 #define GET_REGISTER_MATCHER 11962 #include "RISCVGenAsmMatcher.inc" 11963 11964 Register 11965 RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT, 11966 const MachineFunction &MF) const { 11967 Register Reg = MatchRegisterAltName(RegName); 11968 if (Reg == RISCV::NoRegister) 11969 Reg = MatchRegisterName(RegName); 11970 if (Reg == RISCV::NoRegister) 11971 report_fatal_error( 11972 Twine("Invalid register name \"" + StringRef(RegName) + "\".")); 11973 BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF); 11974 if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg)) 11975 report_fatal_error(Twine("Trying to obtain non-reserved register \"" + 11976 StringRef(RegName) + "\".")); 11977 return Reg; 11978 } 11979 11980 namespace llvm { 11981 namespace RISCVVIntrinsicsTable { 11982 11983 #define GET_RISCVVIntrinsicsTable_IMPL 11984 #include "RISCVGenSearchableTables.inc" 11985 11986 } // namespace RISCVVIntrinsicsTable 11987 11988 } // namespace llvm 11989